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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.977   ! amueller    4: # $Id: lonnet.pm,v 1.976 2008/12/08 23:00:47 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;
                   1794:     if ($filelink=~/^http\:/) {
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 {
                   4409:     my ($uname,$udom,$tool) = @_;
                   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: 
                   4423:     my $hashid=$uname.':'.$udom;
                   4424:     my ($result,$cached) = &is_cached_new('usertools.'.$tool,$hashid);
                   4425:     if (defined($cached)) {
                   4426:         return $result;
                   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:         &do_cache_new('usertools.'.$tool,$hashid,$access,600);
                   4447:         return $access;
                   4448:     }
                   4449: 
                   4450:     my $is_adv = &is_advanced_user($udom,$uname);
                   4451:     my %domdef = &get_domain_defaults($udom);
                   4452:     if (ref($domdef{$tool}) eq 'HASH') {
                   4453:         if ($is_adv) {
                   4454:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4455:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4456:                     $access = 1;
                   4457:                 } else {
                   4458:                     $access = 0;
                   4459:                 }
                   4460:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
                   4461:                 return $access;
                   4462:             }
                   4463:         }
                   4464:         if ($inststatus ne '') {
                   4465:             my ($hasaccess,$hasnoaccess);
                   4466:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4467:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4468:                     if ($domdef{$tool}{$affiliation}) {
                   4469:                         $hasaccess = 1;
                   4470:                     } else {
                   4471:                         $hasnoaccess = 1;
                   4472:                     }
                   4473:                 }
                   4474:             }
                   4475:             if ($hasaccess || $hasnoaccess) {
                   4476:                 if ($hasaccess) {
                   4477:                     $access = 1;
                   4478:                 } elsif ($hasnoaccess) {
                   4479:                     $access = 0; 
                   4480:                 }
                   4481:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
                   4482:                 return $access;
                   4483:             }
                   4484:         } else {
                   4485:             if ($domdef{$tool}{'default'} ne '') {
                   4486:                 if ($domdef{$tool}{'default'}) {
                   4487:                     $access = 1;
                   4488:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4489:                     $access = 0;
                   4490:                 }
                   4491:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
                   4492:                 return $access;
                   4493:             }
                   4494:         }
                   4495:     } else {
                   4496:         $access = 1;
                   4497:         &do_cache_new('usertools.'.$tool,$hashid,$access,600);
                   4498:         return $access;
                   4499:     }
                   4500: }
                   4501: 
                   4502: sub is_advanced_user {
                   4503:     my ($udom,$uname) = @_;
                   4504:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4505:     my %allroles;
                   4506:     my $is_adv;
                   4507:     foreach my $role (keys(%roleshash)) {
                   4508:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4509:         my $area = '/'.$tdomain.'/'.$trest;
                   4510:         if ($sec ne '') {
                   4511:             $area .= '/'.$sec;
                   4512:         }
                   4513:         if (($area ne '') && ($trole ne '')) {
                   4514:             my $spec=$trole.'.'.$area;
                   4515:             if ($trole =~ /^cr\//) {
                   4516:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4517:             } elsif ($trole ne 'gr') {
                   4518:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4519:             }
                   4520:         }
                   4521:     }
                   4522:     foreach my $role (keys(%allroles)) {
                   4523:         last if ($is_adv);
                   4524:         foreach my $item (split(/:/,$allroles{$role})) {
                   4525:             if ($item ne '') {
                   4526:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4527:                 if ($privilege eq 'adv') {
                   4528:                     $is_adv = 1;
                   4529:                     last;
                   4530:                 }
                   4531:             }
                   4532:         }
                   4533:     }
                   4534:     return $is_adv;
                   4535: }
1.798     raeburn  4536: 
1.341     www      4537: # ---------------------------------------------- Custom access rule evaluation
                   4538: 
                   4539: sub customaccess {
                   4540:     my ($priv,$uri)=@_;
1.807     albertel 4541:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4542:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4543:     $udom = &LONCAPA::clean_domain($udom);
                   4544:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4545:     my $access=0;
1.800     albertel 4546:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4547: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4548: 	if ($type eq 'user') {
                   4549: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4550: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4551: 		if ($tdom) {
                   4552: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4553: 		}
1.896     albertel 4554: 		if ($tuname) {
                   4555: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4556: 		}
                   4557: 		$access=($effect eq 'allow');
                   4558: 		last;
                   4559: 	    }
                   4560: 	} else {
                   4561: 	    if ($role) {
                   4562: 		if ($role ne $urole) { next; }
                   4563: 	    }
                   4564: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4565: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4566: 		if ($tdom) {
                   4567: 		    if ($tdom ne $udom) { next; }
                   4568: 		}
                   4569: 		if ($tcrs) {
                   4570: 		    if ($tcrs ne $ucrs) { next; }
                   4571: 		}
                   4572: 		if ($tsec) {
                   4573: 		    if ($tsec ne $usec) { next; }
                   4574: 		}
                   4575: 		$access=($effect eq 'allow');
                   4576: 		last;
                   4577: 	    }
                   4578: 	    if ($realm eq '' && $role eq '') {
                   4579: 		$access=($effect eq 'allow');
                   4580: 	    }
1.402     bowersj2 4581: 	}
1.341     www      4582:     }
                   4583:     return $access;
                   4584: }
                   4585: 
1.103     harris41 4586: # ------------------------------------------------- Check for a user privilege
1.12      www      4587: 
                   4588: sub allowed {
1.810     raeburn  4589:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4590:     my $ver_orguri=$uri;
1.439     www      4591:     $uri=&deversion($uri);
1.152     www      4592:     my $orguri=$uri;
1.52      www      4593:     $uri=&declutter($uri);
1.809     raeburn  4594: 
1.810     raeburn  4595:     if ($priv eq 'evb') {
                   4596: # Evade communication block restrictions for specified role in a course
                   4597:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4598:             return $1;
                   4599:         } else {
                   4600:             return;
                   4601:         }
                   4602:     }
                   4603: 
1.620     albertel 4604:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4605: # Free bre access to adm and meta resources
1.775     albertel 4606:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4607: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4608: 	&& ($priv eq 'bre')) {
1.14      www      4609: 	return 'F';
1.159     www      4610:     }
                   4611: 
1.545     banghart 4612: # Free bre access to user's own portfolio contents
1.714     raeburn  4613:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4614:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4615: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4616:         my %setters;
                   4617:         my ($startblock,$endblock) = 
                   4618:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4619:         if ($startblock && $endblock) {
                   4620:             return 'B';
                   4621:         } else {
                   4622:             return 'F';
                   4623:         }
1.545     banghart 4624:     }
                   4625: 
1.762     raeburn  4626: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4627:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4628:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4629:         if (exists($env{'request.course.id'})) {
                   4630:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4631:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4632:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4633:                 my $courseprivid=$env{'request.course.id'};
                   4634:                 $courseprivid=~s/\_/\//;
                   4635:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4636:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4637:                     return $1; 
1.762     raeburn  4638:                 } else {
                   4639:                     if ($env{'request.course.sec'}) {
                   4640:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4641:                     }
                   4642:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4643:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4644:                         return $2;
                   4645:                     }
1.714     raeburn  4646:                 }
                   4647:             }
                   4648:         }
                   4649:     }
                   4650: 
1.159     www      4651: # Free bre to public access
                   4652: 
                   4653:     if ($priv eq 'bre') {
1.238     www      4654:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4655: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4656:            return 'F'; 
                   4657:         }
1.238     www      4658:         if ($copyright eq 'priv') {
                   4659:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4660: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4661: 		return '';
                   4662:             }
                   4663:         }
                   4664:         if ($copyright eq 'domain') {
                   4665:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4666: 	    unless (($env{'user.domain'} eq $1) ||
                   4667:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4668: 		return '';
                   4669:             }
1.262     matthew  4670:         }
1.620     albertel 4671:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4672:             # Library role, so allow browsing of resources in this domain.
                   4673:             return 'F';
1.238     www      4674:         }
1.341     www      4675:         if ($copyright eq 'custom') {
                   4676: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4677:         }
1.14      www      4678:     }
1.264     matthew  4679:     # Domain coordinator is trying to create a course
1.620     albertel 4680:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4681:         # uri is the requested domain in this case.
                   4682:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4683:         # a role of dc for the domain in question.
1.620     albertel 4684:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4685:     }
1.29      www      4686: 
1.52      www      4687:     my $thisallowed='';
                   4688:     my $statecond=0;
                   4689:     my $courseprivid='';
                   4690: 
                   4691: # Course
                   4692: 
1.620     albertel 4693:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4694:        $thisallowed.=$1;
                   4695:     }
1.29      www      4696: 
1.52      www      4697: # Domain
                   4698: 
1.620     albertel 4699:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4700:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4701:        $thisallowed.=$1;
                   4702:     }
1.52      www      4703: 
                   4704: # Course: uri itself is a course
1.66      www      4705:     my $courseuri=$uri;
                   4706:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4707:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4708: 
1.620     albertel 4709:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4710:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4711:        $thisallowed.=$1;
                   4712:     }
1.29      www      4713: 
1.665     albertel 4714: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4715: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4716:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4717: 	$thisallowed='';
1.671     raeburn  4718:         my ($match)=&is_on_map($uri);
                   4719:         if ($match) {
                   4720:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4721:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4722:                 $thisallowed.=$1;
                   4723:             }
                   4724:         } else {
1.705     albertel 4725:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4726:             if ($refuri) {
                   4727:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4728:                     $thisallowed='F';
1.671     raeburn  4729:                 } else {
                   4730:                     $refuri=&declutter($refuri);
                   4731:                     my ($match) = &is_on_map($refuri);
                   4732:                     if ($match) {
                   4733:                         $thisallowed='F';
                   4734:                     }
1.669     raeburn  4735:                 }
1.671     raeburn  4736:             }
                   4737:         }
1.314     www      4738:     }
1.492     albertel 4739: 
1.766     albertel 4740:     if ($priv eq 'bre'
                   4741: 	&& $thisallowed ne 'F' 
                   4742: 	&& $thisallowed ne '2'
                   4743: 	&& &is_portfolio_url($uri)) {
                   4744: 	$thisallowed = &portfolio_access($uri);
                   4745:     }
                   4746:     
1.52      www      4747: # Full access at system, domain or course-wide level? Exit.
1.29      www      4748:     if ($thisallowed=~/F/) {
                   4749: 	return 'F';
                   4750:     }
                   4751: 
1.52      www      4752: # If this is generating or modifying users, exit with special codes
1.29      www      4753: 
1.643     www      4754:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4755: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4756: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4757: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4758: 	    unless ($auname) { return $thisallowed; }
                   4759: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4760: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4761: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4762: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4763: 	}
1.52      www      4764: 	return $thisallowed;
                   4765:     }
                   4766: #
1.103     harris41 4767: # Gathered so far: system, domain and course wide privileges
1.52      www      4768: #
                   4769: # Course: See if uri or referer is an individual resource that is part of 
                   4770: # the course
                   4771: 
1.620     albertel 4772:     if ($env{'request.course.id'}) {
1.232     www      4773: 
1.620     albertel 4774:        $courseprivid=$env{'request.course.id'};
                   4775:        if ($env{'request.course.sec'}) {
                   4776:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4777:        }
                   4778:        $courseprivid=~s/\_/\//;
                   4779:        my $checkreferer=1;
1.232     www      4780:        my ($match,$cond)=&is_on_map($uri);
                   4781:        if ($match) {
                   4782:            $statecond=$cond;
1.620     albertel 4783:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4784:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4785:                $thisallowed.=$1;
                   4786:                $checkreferer=0;
                   4787:            }
1.29      www      4788:        }
1.83      www      4789:        
1.148     www      4790:        if ($checkreferer) {
1.620     albertel 4791: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4792:             unless ($refuri) {
1.800     albertel 4793:                 foreach my $key (keys(%env)) {
                   4794: 		    if ($key=~/^httpref\..*\*/) {
                   4795: 			my $pattern=$key;
1.156     www      4796:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4797:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4798:                         $pattern=~s/\//\\\//g;
1.152     www      4799:                         if ($orguri=~/$pattern/) {
1.800     albertel 4800: 			    $refuri=$env{$key};
1.148     www      4801:                         }
                   4802:                     }
1.191     harris41 4803:                 }
1.148     www      4804:             }
1.232     www      4805: 
1.148     www      4806:          if ($refuri) { 
1.152     www      4807: 	  $refuri=&declutter($refuri);
1.232     www      4808:           my ($match,$cond)=&is_on_map($refuri);
                   4809:             if ($match) {
                   4810:               my $refstatecond=$cond;
1.620     albertel 4811:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4812:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4813:                   $thisallowed.=$1;
1.53      www      4814:                   $uri=$refuri;
                   4815:                   $statecond=$refstatecond;
1.52      www      4816:               }
                   4817:           }
1.148     www      4818:         }
1.29      www      4819:        }
1.52      www      4820:    }
1.29      www      4821: 
1.52      www      4822: #
1.103     harris41 4823: # Gathered now: all privileges that could apply, and condition number
1.52      www      4824: # 
                   4825: #
                   4826: # Full or no access?
                   4827: #
1.29      www      4828: 
1.52      www      4829:     if ($thisallowed=~/F/) {
                   4830: 	return 'F';
                   4831:     }
1.29      www      4832: 
1.52      www      4833:     unless ($thisallowed) {
                   4834:         return '';
                   4835:     }
1.29      www      4836: 
1.52      www      4837: # Restrictions exist, deal with them
                   4838: #
                   4839: #   C:according to course preferences
                   4840: #   R:according to resource settings
                   4841: #   L:unless locked
                   4842: #   X:according to user session state
                   4843: #
                   4844: 
                   4845: # Possibly locked functionality, check all courses
1.54      www      4846: # Locks might take effect only after 10 minutes cache expiration for other
                   4847: # courses, and 2 minutes for current course
1.52      www      4848: 
                   4849:     my $envkey;
                   4850:     if ($thisallowed=~/L/) {
1.620     albertel 4851:         foreach $envkey (keys %env) {
1.54      www      4852:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4853:                my $courseid=$2;
                   4854:                my $roleid=$1.'.'.$2;
1.92      www      4855:                $courseid=~s/^\///;
1.54      www      4856:                my $expiretime=600;
1.620     albertel 4857:                if ($env{'request.role'} eq $roleid) {
1.54      www      4858: 		  $expiretime=120;
                   4859:                }
                   4860: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4861:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4862:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4863: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4864:                }
1.620     albertel 4865:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4866:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4867: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4868:                        &log($env{'user.domain'},$env{'user.name'},
                   4869:                             $env{'user.home'},
1.57      www      4870:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4871:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4872:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4873: 		       return '';
                   4874:                    }
                   4875:                }
1.620     albertel 4876:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4877:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4878: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4879:                        &log($env{'user.domain'},$env{'user.name'},
                   4880:                             $env{'user.home'},
1.57      www      4881:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4882:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4883:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4884: 		       return '';
                   4885:                    }
                   4886:                }
                   4887: 	   }
1.29      www      4888:        }
1.52      www      4889:     }
                   4890:    
                   4891: #
                   4892: # Rest of the restrictions depend on selected course
                   4893: #
                   4894: 
1.620     albertel 4895:     unless ($env{'request.course.id'}) {
1.766     albertel 4896: 	if ($thisallowed eq 'A') {
                   4897: 	    return 'A';
1.814     raeburn  4898:         } elsif ($thisallowed eq 'B') {
                   4899:             return 'B';
1.766     albertel 4900: 	} else {
                   4901: 	    return '1';
                   4902: 	}
1.52      www      4903:     }
1.29      www      4904: 
1.52      www      4905: #
                   4906: # Now user is definitely in a course
                   4907: #
1.53      www      4908: 
                   4909: 
                   4910: # Course preferences
                   4911: 
                   4912:    if ($thisallowed=~/C/) {
1.620     albertel 4913:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4914:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4915:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4916: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4917: 	   if ($priv ne 'pch') { 
                   4918: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4919: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4920: 			$env{'request.course.id'});
                   4921: 	   }
1.237     www      4922:            return '';
                   4923:        }
                   4924: 
1.620     albertel 4925:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4926: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4927: 	   if ($priv ne 'pch') { 
                   4928: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4929: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4930: 			$env{'request.course.id'});
                   4931: 	   }
1.54      www      4932:            return '';
                   4933:        }
1.53      www      4934:    }
                   4935: 
                   4936: # Resource preferences
                   4937: 
                   4938:    if ($thisallowed=~/R/) {
1.620     albertel 4939:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4940:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4941: 	   if ($priv ne 'pch') { 
                   4942: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4943: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4944: 	   }
                   4945: 	   return '';
1.54      www      4946:        }
1.53      www      4947:    }
1.30      www      4948: 
1.246     www      4949: # Restricted by state or randomout?
1.30      www      4950: 
1.52      www      4951:    if ($thisallowed=~/X/) {
1.620     albertel 4952:       if ($env{'acc.randomout'}) {
1.579     albertel 4953: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4954:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4955:             return ''; 
                   4956:          }
1.247     www      4957:       }
                   4958:       if (&condval($statecond)) {
1.52      www      4959: 	 return '2';
                   4960:       } else {
                   4961:          return '';
                   4962:       }
                   4963:    }
1.30      www      4964: 
1.766     albertel 4965:     if ($thisallowed eq 'A') {
                   4966: 	return 'A';
1.814     raeburn  4967:     } elsif ($thisallowed eq 'B') {
                   4968:         return 'B';
1.766     albertel 4969:     }
1.52      www      4970:    return 'F';
1.232     www      4971: }
                   4972: 
1.710     albertel 4973: sub split_uri_for_cond {
                   4974:     my $uri=&deversion(&declutter(shift));
                   4975:     my @uriparts=split(/\//,$uri);
                   4976:     my $filename=pop(@uriparts);
                   4977:     my $pathname=join('/',@uriparts);
                   4978:     return ($pathname,$filename);
                   4979: }
1.232     www      4980: # --------------------------------------------------- Is a resource on the map?
                   4981: 
                   4982: sub is_on_map {
1.710     albertel 4983:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4984:     #Trying to find the conditional for the file
1.620     albertel 4985:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4986: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4987:     if ($match) {
1.289     bowersj2 4988: 	return (1,$1);
                   4989:     } else {
1.434     www      4990: 	return (0,0);
1.289     bowersj2 4991:     }
1.12      www      4992: }
                   4993: 
1.427     www      4994: # --------------------------------------------------------- Get symb from alias
                   4995: 
                   4996: sub get_symb_from_alias {
                   4997:     my $symb=shift;
                   4998:     my ($map,$resid,$url)=&decode_symb($symb);
                   4999: # Already is a symb
                   5000:     if ($url) { return $symb; }
                   5001: # Must be an alias
                   5002:     my $aliassymb='';
                   5003:     my %bighash;
1.620     albertel 5004:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5005:                             &GDBM_READER(),0640)) {
                   5006:         my $rid=$bighash{'mapalias_'.$symb};
                   5007: 	if ($rid) {
                   5008: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5009: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5010: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5011: 	}
                   5012:         untie %bighash;
                   5013:     }
                   5014:     return $aliassymb;
                   5015: }
                   5016: 
1.12      www      5017: # ----------------------------------------------------------------- Define Role
                   5018: 
                   5019: sub definerole {
                   5020:   if (allowed('mcr','/')) {
                   5021:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5022:     foreach my $role (split(':',$sysrole)) {
                   5023: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5024:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5025:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5026: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5027:                return "refused:s:$crole&$cqual"; 
                   5028:             }
                   5029:         }
1.191     harris41 5030:     }
1.800     albertel 5031:     foreach my $role (split(':',$domrole)) {
                   5032: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5033:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5034:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5035: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5036:                return "refused:d:$crole&$cqual"; 
                   5037:             }
                   5038:         }
1.191     harris41 5039:     }
1.800     albertel 5040:     foreach my $role (split(':',$courole)) {
                   5041: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5042:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5043:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5044: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5045:                return "refused:c:$crole&$cqual"; 
                   5046:             }
                   5047:         }
1.191     harris41 5048:     }
1.620     albertel 5049:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5050:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5051: 	        "rolesdef_$rolename=".
                   5052:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5053:     return reply($command,$env{'user.home'});
1.12      www      5054:   } else {
                   5055:     return 'refused';
                   5056:   }
1.105     harris41 5057: }
                   5058: 
                   5059: # ---------------- Make a metadata query against the network of library servers
                   5060: 
                   5061: sub metadata_query {
1.244     matthew  5062:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5063:     my %rhash;
1.845     albertel 5064:     my %libserv = &all_library();
1.244     matthew  5065:     my @server_list = (defined($server_array) ? @$server_array
                   5066:                                               : keys(%libserv) );
                   5067:     for my $server (@server_list) {
1.118     harris41 5068: 	unless ($custom or $customshow) {
                   5069: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5070: 	    $rhash{$server}=$reply;
                   5071: 	}
                   5072: 	else {
                   5073: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5074: 			     &escape($custom).':'.&escape($customshow),
                   5075: 			     $server);
                   5076: 	    $rhash{$server}=$reply;
                   5077: 	}
1.112     harris41 5078:     }
1.118     harris41 5079:     return \%rhash;
1.240     www      5080: }
                   5081: 
                   5082: # ----------------------------------------- Send log queries and wait for reply
                   5083: 
                   5084: sub log_query {
                   5085:     my ($uname,$udom,$query,%filters)=@_;
                   5086:     my $uhome=&homeserver($uname,$udom);
                   5087:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5088:     my $uhost=&hostname($uhome);
1.800     albertel 5089:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5090:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5091:                        $uhome);
1.479     albertel 5092:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5093:     return get_query_reply($queryid);
                   5094: }
                   5095: 
1.818     raeburn  5096: # -------------------------- Update MySQL table for portfolio file
                   5097: 
                   5098: sub update_portfolio_table {
1.821     raeburn  5099:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5100:     if ($group ne '') {
                   5101:         $file_name =~s /^\Q$group\E//;
                   5102:     }
1.818     raeburn  5103:     my $homeserver = &homeserver($uname,$udom);
                   5104:     my $queryid=
1.821     raeburn  5105:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5106:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5107:     my $reply = &get_query_reply($queryid);
                   5108:     return $reply;
                   5109: }
                   5110: 
1.899     raeburn  5111: # -------------------------- Update MySQL allusers table
                   5112: 
                   5113: sub update_allusers_table {
                   5114:     my ($uname,$udom,$names) = @_;
                   5115:     my $homeserver = &homeserver($uname,$udom);
                   5116:     my $queryid=
                   5117:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5118:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5119:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5120:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5121:                'generation='.&escape($names->{'generation'}).'%%'.
                   5122:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5123:                'id='.&escape($names->{'id'}),$homeserver);
                   5124:     my $reply = &get_query_reply($queryid);
                   5125:     return $reply;
                   5126: }
                   5127: 
1.508     raeburn  5128: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5129: 
                   5130: sub fetch_enrollment_query {
1.511     raeburn  5131:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5132:     my $homeserver;
1.547     raeburn  5133:     my $maxtries = 1;
1.508     raeburn  5134:     if ($context eq 'automated') {
                   5135:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5136:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5137:     } else {
                   5138:         $homeserver = &homeserver($cnum,$dom);
                   5139:     }
1.838     albertel 5140:     my $host=&hostname($homeserver);
1.506     raeburn  5141:     my $cmd = '';
1.800     albertel 5142:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5143:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5144:     }
                   5145:     $cmd =~ s/%%$//;
                   5146:     $cmd = &escape($cmd);
                   5147:     my $query = 'fetchenrollment';
1.620     albertel 5148:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5149:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5150:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5151:         return 'error: '.$queryid;
                   5152:     }
1.506     raeburn  5153:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5154:     my $tries = 1;
                   5155:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5156:         $reply = &get_query_reply($queryid);
                   5157:         $tries ++;
                   5158:     }
1.526     raeburn  5159:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5160:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5161:     } else {
1.901     albertel 5162:         my @responses = split(/:/,$reply);
1.515     raeburn  5163:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5164:             foreach my $line (@responses) {
                   5165:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5166:                 $$replyref{$key} = $value;
                   5167:             }
                   5168:         } else {
1.506     raeburn  5169:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5170:             foreach my $line (@responses) {
                   5171:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5172:                 $$replyref{$key} = $value;
                   5173:                 if ($value > 0) {
1.800     albertel 5174:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5175:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5176:                         my $destname = $pathname.'/'.$filename;
                   5177:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5178:                         if ($xml_classlist =~ /^error/) {
                   5179:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5180:                         } else {
1.506     raeburn  5181:                             if ( open(FILE,">$destname") ) {
                   5182:                                 print FILE &unescape($xml_classlist);
                   5183:                                 close(FILE);
1.526     raeburn  5184:                             } else {
                   5185:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5186:                             }
                   5187:                         }
                   5188:                     }
                   5189:                 }
                   5190:             }
                   5191:         }
                   5192:         return 'ok';
                   5193:     }
                   5194:     return 'error';
                   5195: }
                   5196: 
1.242     www      5197: sub get_query_reply {
                   5198:     my $queryid=shift;
1.240     www      5199:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5200:     my $reply='';
                   5201:     for (1..100) {
                   5202: 	sleep 2;
                   5203:         if (-e $replyfile.'.end') {
1.448     albertel 5204: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5205: 		$reply = join('',<$fh>);
                   5206: 		close($fh);
1.240     www      5207: 	   } else { return 'error: reply_file_error'; }
1.242     www      5208:            return &unescape($reply);
                   5209: 	}
1.240     www      5210:     }
1.242     www      5211:     return 'timeout:'.$queryid;
1.240     www      5212: }
                   5213: 
                   5214: sub courselog_query {
1.241     www      5215: #
                   5216: # possible filters:
                   5217: # url: url or symb
                   5218: # username
                   5219: # domain
                   5220: # action: view, submit, grade
                   5221: # start: timestamp
                   5222: # end: timestamp
                   5223: #
1.240     www      5224:     my (%filters)=@_;
1.620     albertel 5225:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5226:     if ($filters{'url'}) {
                   5227: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5228:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5229:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5230:     }
1.620     albertel 5231:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5232:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5233:     return &log_query($cname,$cdom,'courselog',%filters);
                   5234: }
                   5235: 
                   5236: sub userlog_query {
1.858     raeburn  5237: #
                   5238: # possible filters:
                   5239: # action: log check role
                   5240: # start: timestamp
                   5241: # end: timestamp
                   5242: #
1.240     www      5243:     my ($uname,$udom,%filters)=@_;
                   5244:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5245: }
                   5246: 
1.506     raeburn  5247: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5248: 
                   5249: sub auto_run {
1.508     raeburn  5250:     my ($cnum,$cdom) = @_;
1.876     raeburn  5251:     my $response = 0;
                   5252:     my $settings;
                   5253:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5254:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5255:         $settings = $domconfig{'autoenroll'};
                   5256:         if ($settings->{'run'} eq '1') {
                   5257:             $response = 1;
                   5258:         }
                   5259:     } else {
1.934     raeburn  5260:         my $homeserver;
                   5261:         if (&is_course($cdom,$cnum)) {
                   5262:             $homeserver = &homeserver($cnum,$cdom);
                   5263:         } else {
                   5264:             $homeserver = &domain($cdom,'primary');
                   5265:         }
                   5266:         if ($homeserver ne 'no_host') {
                   5267:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5268:         }
1.876     raeburn  5269:     }
1.506     raeburn  5270:     return $response;
                   5271: }
1.776     albertel 5272: 
1.506     raeburn  5273: sub auto_get_sections {
1.508     raeburn  5274:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5275:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5276:     my @secs = ();
1.511     raeburn  5277:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5278:     unless ($response eq 'refused') {
1.901     albertel 5279:         @secs = split(/:/,$response);
1.506     raeburn  5280:     }
                   5281:     return @secs;
                   5282: }
1.776     albertel 5283: 
1.506     raeburn  5284: sub auto_new_course {
1.508     raeburn  5285:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5286:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5287:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5288:     return $response;
                   5289: }
1.776     albertel 5290: 
1.506     raeburn  5291: sub auto_validate_courseID {
1.508     raeburn  5292:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5293:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5294:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5295:     return $response;
                   5296: }
1.776     albertel 5297: 
1.506     raeburn  5298: sub auto_create_password {
1.873     raeburn  5299:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5300:     my ($homeserver,$response);
1.506     raeburn  5301:     my $create_passwd = 0;
                   5302:     my $authchk = '';
1.873     raeburn  5303:     if ($udom =~ /^$match_domain$/) {
                   5304:         $homeserver = &domain($udom,'primary');
                   5305:     }
                   5306:     if ($homeserver eq '') {
                   5307:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5308:             $homeserver = &homeserver($cnum,$cdom);
                   5309:         }
                   5310:     }
                   5311:     if ($homeserver eq '') {
                   5312:         $authchk = 'nodomain';
1.506     raeburn  5313:     } else {
1.873     raeburn  5314:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5315:         if ($response eq 'refused') {
                   5316:             $authchk = 'refused';
                   5317:         } else {
1.901     albertel 5318:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5319:         }
1.506     raeburn  5320:     }
                   5321:     return ($authparam,$create_passwd,$authchk);
                   5322: }
                   5323: 
1.706     raeburn  5324: sub auto_photo_permission {
                   5325:     my ($cnum,$cdom,$students) = @_;
                   5326:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5327:     my ($outcome,$perm_reqd,$conditions) = 
                   5328: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5329:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5330: 	return (undef,undef);
                   5331:     }
1.706     raeburn  5332:     return ($outcome,$perm_reqd,$conditions);
                   5333: }
                   5334: 
                   5335: sub auto_checkphotos {
                   5336:     my ($uname,$udom,$pid) = @_;
                   5337:     my $homeserver = &homeserver($uname,$udom);
                   5338:     my ($result,$resulttype);
                   5339:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5340: 				   &escape($uname).':'.&escape($pid),
                   5341: 				   $homeserver));
1.709     albertel 5342:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5343: 	return (undef,undef);
                   5344:     }
1.706     raeburn  5345:     if ($outcome) {
                   5346:         ($result,$resulttype) = split(/:/,$outcome);
                   5347:     } 
                   5348:     return ($result,$resulttype);
                   5349: }
                   5350: 
                   5351: sub auto_photochoice {
                   5352:     my ($cnum,$cdom) = @_;
                   5353:     my $homeserver = &homeserver($cnum,$cdom);
                   5354:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5355: 						       &escape($cdom),
                   5356: 						       $homeserver)));
1.709     albertel 5357:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5358: 	return (undef,undef);
                   5359:     }
1.706     raeburn  5360:     return ($update,$comment);
                   5361: }
                   5362: 
                   5363: sub auto_photoupdate {
                   5364:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5365:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5366:     my $host=&hostname($homeserver);
1.706     raeburn  5367:     my $cmd = '';
                   5368:     my $maxtries = 1;
1.800     albertel 5369:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5370:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5371:     }
                   5372:     $cmd =~ s/%%$//;
                   5373:     $cmd = &escape($cmd);
                   5374:     my $query = 'institutionalphotos';
                   5375:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5376:     unless ($queryid=~/^\Q$host\E\_/) {
                   5377:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5378:         return 'error: '.$queryid;
                   5379:     }
                   5380:     my $reply = &get_query_reply($queryid);
                   5381:     my $tries = 1;
                   5382:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5383:         $reply = &get_query_reply($queryid);
                   5384:         $tries ++;
                   5385:     }
                   5386:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5387:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5388:     } else {
                   5389:         my @responses = split(/:/,$reply);
                   5390:         my $outcome = shift(@responses); 
                   5391:         foreach my $item (@responses) {
                   5392:             my ($key,$value) = split(/=/,$item);
                   5393:             $$photo{$key} = $value;
                   5394:         }
                   5395:         return $outcome;
                   5396:     }
                   5397:     return 'error';
                   5398: }
                   5399: 
1.521     raeburn  5400: sub auto_instcode_format {
1.793     albertel 5401:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5402: 	$cat_order) = @_;
1.521     raeburn  5403:     my $courses = '';
1.772     raeburn  5404:     my @homeservers;
1.521     raeburn  5405:     if ($caller eq 'global') {
1.841     albertel 5406: 	my %servers = &get_servers($codedom,'library');
                   5407: 	foreach my $tryserver (keys(%servers)) {
                   5408: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5409: 		push(@homeservers,$tryserver);
                   5410: 	    }
1.584     raeburn  5411:         }
1.521     raeburn  5412:     } else {
1.772     raeburn  5413:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5414:     }
1.793     albertel 5415:     foreach my $code (keys(%{$instcodes})) {
                   5416:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5417:     }
                   5418:     chop($courses);
1.772     raeburn  5419:     my $ok_response = 0;
                   5420:     my $response;
                   5421:     while (@homeservers > 0 && $ok_response == 0) {
                   5422:         my $server = shift(@homeservers); 
                   5423:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5424:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5425:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5426: 		split(/:/,$response);
1.772     raeburn  5427:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5428:             push(@{$codetitles},&str2array($codetitles_str));
                   5429:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5430:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5431:             $ok_response = 1;
                   5432:         }
                   5433:     }
                   5434:     if ($ok_response) {
1.521     raeburn  5435:         return 'ok';
1.772     raeburn  5436:     } else {
                   5437:         return $response;
1.521     raeburn  5438:     }
                   5439: }
                   5440: 
1.792     raeburn  5441: sub auto_instcode_defaults {
                   5442:     my ($domain,$returnhash,$code_order) = @_;
                   5443:     my @homeservers;
1.841     albertel 5444: 
                   5445:     my %servers = &get_servers($domain,'library');
                   5446:     foreach my $tryserver (keys(%servers)) {
                   5447: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5448: 	    push(@homeservers,$tryserver);
                   5449: 	}
1.792     raeburn  5450:     }
1.841     albertel 5451: 
1.792     raeburn  5452:     my $response;
1.841     albertel 5453:     foreach my $server (@homeservers) {
1.792     raeburn  5454:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5455:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5456: 	
                   5457: 	foreach my $pair (split(/\&/,$response)) {
                   5458: 	    my ($name,$value)=split(/\=/,$pair);
                   5459: 	    if ($name eq 'code_order') {
                   5460: 		@{$code_order} = split(/\&/,&unescape($value));
                   5461: 	    } else {
                   5462: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5463: 	    }
                   5464: 	}
                   5465: 	return 'ok';
1.792     raeburn  5466:     }
1.841     albertel 5467: 
                   5468:     return $response;
1.792     raeburn  5469: } 
                   5470: 
1.777     albertel 5471: sub auto_validate_class_sec {
1.918     raeburn  5472:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5473:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5474:     my $ownerlist;
                   5475:     if (ref($owners) eq 'ARRAY') {
                   5476:         $ownerlist = join(',',@{$owners});
                   5477:     } else {
                   5478:         $ownerlist = $owners;
                   5479:     }
1.773     raeburn  5480:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5481:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5482:     return $response;
                   5483: }
                   5484: 
1.679     raeburn  5485: # ------------------------------------------------------- Course Group routines
                   5486: 
                   5487: sub get_coursegroups {
1.809     raeburn  5488:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5489:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5490: }
                   5491: 
1.679     raeburn  5492: sub modify_coursegroup {
                   5493:     my ($cdom,$cnum,$groupsettings) = @_;
                   5494:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5495: }
                   5496: 
1.809     raeburn  5497: sub toggle_coursegroup_status {
                   5498:     my ($cdom,$cnum,$group,$action) = @_;
                   5499:     my ($from_namespace,$to_namespace);
                   5500:     if ($action eq 'delete') {
                   5501:         $from_namespace = 'coursegroups';
                   5502:         $to_namespace = 'deleted_groups';
                   5503:     } else {
                   5504:         $from_namespace = 'deleted_groups';
                   5505:         $to_namespace = 'coursegroups';
                   5506:     }
                   5507:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5508:     if (my $tmp = &error(%curr_group)) {
                   5509:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5510:         return ('read error',$tmp);
                   5511:     } else {
                   5512:         my %savedsettings = %curr_group; 
1.809     raeburn  5513:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5514:         my $deloutcome;
                   5515:         if ($result eq 'ok') {
1.809     raeburn  5516:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5517:         } else {
                   5518:             return ('write error',$result);
                   5519:         }
                   5520:         if ($deloutcome eq 'ok') {
                   5521:             return 'ok';
                   5522:         } else {
                   5523:             return ('delete error',$deloutcome);
                   5524:         }
                   5525:     }
                   5526: }
                   5527: 
1.679     raeburn  5528: sub modify_group_roles {
1.957     raeburn  5529:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5530:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5531:     my $role = 'gr/'.&escape($userprivs);
                   5532:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5533:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5534:     if ($result eq 'ok') {
                   5535:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5536:     }
1.679     raeburn  5537:     return $result;
                   5538: }
                   5539: 
                   5540: sub modify_coursegroup_membership {
                   5541:     my ($cdom,$cnum,$membership) = @_;
                   5542:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5543:     return $result;
                   5544: }
                   5545: 
1.682     raeburn  5546: sub get_active_groups {
                   5547:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5548:     my $now = time;
                   5549:     my %groups = ();
                   5550:     foreach my $key (keys(%env)) {
1.811     albertel 5551:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5552:             my ($start,$end) = split(/\./,$env{$key});
                   5553:             if (($end!=0) && ($end<$now)) { next; }
                   5554:             if (($start!=0) && ($start>$now)) { next; }
                   5555:             if ($1 eq $cdom && $2 eq $cnum) {
                   5556:                 $groups{$3} = $env{$key} ;
                   5557:             }
                   5558:         }
                   5559:     }
                   5560:     return %groups;
                   5561: }
                   5562: 
1.683     raeburn  5563: sub get_group_membership {
                   5564:     my ($cdom,$cnum,$group) = @_;
                   5565:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5566: }
                   5567: 
                   5568: sub get_users_groups {
                   5569:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5570:     my @usersgroups;
1.683     raeburn  5571:     my $cachetime=1800;
                   5572: 
                   5573:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5574:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5575:     if (defined($cached)) {
1.734     albertel 5576:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5577:     } else {  
                   5578:         $grouplist = '';
1.816     raeburn  5579:         my $courseurl = &courseid_to_courseurl($courseid);
                   5580:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5581:         my $access_end = $env{'course.'.$courseid.
                   5582:                               '.default_enrollment_end_date'};
                   5583:         my $now = time;
                   5584:         foreach my $key (keys(%roleshash)) {
                   5585:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5586:                 my $group = $1;
                   5587:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5588:                     my $start = $2;
                   5589:                     my $end = $1;
                   5590:                     if ($start == -1) { next; } # deleted from group
                   5591:                     if (($start!=0) && ($start>$now)) { next; }
                   5592:                     if (($end!=0) && ($end<$now)) {
                   5593:                         if ($access_end && $access_end < $now) {
                   5594:                             if ($access_end - $end < 86400) {
                   5595:                                 push(@usersgroups,$group);
1.733     raeburn  5596:                             }
                   5597:                         }
1.817     raeburn  5598:                         next;
1.733     raeburn  5599:                     }
1.817     raeburn  5600:                     push(@usersgroups,$group);
1.683     raeburn  5601:                 }
                   5602:             }
                   5603:         }
1.817     raeburn  5604:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5605:         $grouplist = join(':',@usersgroups);
                   5606:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5607:     }
1.733     raeburn  5608:     return @usersgroups;
1.683     raeburn  5609: }
                   5610: 
                   5611: sub devalidate_getgroups_cache {
                   5612:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5613:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5614: 
1.683     raeburn  5615:     my $hashid="$udom:$uname:$courseid";
                   5616:     &devalidate_cache_new('getgroups',$hashid);
                   5617: }
                   5618: 
1.12      www      5619: # ------------------------------------------------------------------ Plain Text
                   5620: 
                   5621: sub plaintext {
1.742     raeburn  5622:     my ($short,$type,$cid) = @_;
1.758     albertel 5623:     if ($short =~ /^cr/) {
                   5624: 	return (split('/',$short))[-1];
                   5625:     }
1.742     raeburn  5626:     if (!defined($cid)) {
                   5627:         $cid = $env{'request.course.id'};
                   5628:     }
                   5629:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5630:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5631:                                           '.plaintext'});
                   5632:     }
                   5633:     my %rolenames = (
                   5634:                       Course => 'std',
                   5635:                       Group => 'alt1',
                   5636:                     );
                   5637:     if (defined($type) && 
                   5638:          defined($rolenames{$type}) && 
                   5639:          defined($prp{$short}{$rolenames{$type}})) {
                   5640:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5641:     } else {
                   5642:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5643:     }
1.12      www      5644: }
                   5645: 
                   5646: # ----------------------------------------------------------------- Assign Role
                   5647: 
                   5648: sub assignrole {
1.957     raeburn  5649:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5650:         $context)=@_;
1.21      www      5651:     my $mrole;
                   5652:     if ($role =~ /^cr\//) {
1.393     www      5653:         my $cwosec=$url;
1.811     albertel 5654:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5655: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5656:            &logthis('Refused custom assignrole: '.
                   5657:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5658: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5659:            return 'refused'; 
                   5660:         }
1.21      www      5661:         $mrole='cr';
1.678     raeburn  5662:     } elsif ($role =~ /^gr\//) {
                   5663:         my $cwogrp=$url;
1.811     albertel 5664:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5665:         unless (&allowed('mdg',$cwogrp)) {
                   5666:             &logthis('Refused group assignrole: '.
                   5667:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5668:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5669:             return 'refused';
                   5670:         }
                   5671:         $mrole='gr';
1.21      www      5672:     } else {
1.82      www      5673:         my $cwosec=$url;
1.811     albertel 5674:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5675:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5676:             my $refused;
                   5677:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5678:                 if (!(&allowed('c'.$role,$url))) {
                   5679:                     $refused = 1;
                   5680:                 }
                   5681:             } else {
                   5682:                 $refused = 1;
                   5683:             }
1.947     raeburn  5684:             if ($refused) {
                   5685:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5686:                     $refused = '';
                   5687:                 } else {
                   5688:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5689:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5690: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5691:                     return 'refused';
                   5692:                 }
1.932     raeburn  5693:             }
1.104     www      5694:         }
1.21      www      5695:         $mrole=$role;
                   5696:     }
1.620     albertel 5697:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5698:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5699:     if ($end) { $command.='_'.$end; }
1.21      www      5700:     if ($start) {
                   5701: 	if ($end) { 
1.81      www      5702:            $command.='_'.$start; 
1.21      www      5703:         } else {
1.81      www      5704:            $command.='_0_'.$start;
1.21      www      5705:         }
                   5706:     }
1.739     raeburn  5707:     my $origstart = $start;
                   5708:     my $origend = $end;
1.957     raeburn  5709:     my $delflag;
1.357     www      5710: # actually delete
                   5711:     if ($deleteflag) {
1.373     www      5712: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5713: # modify command to delete the role
1.620     albertel 5714:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5715:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5716: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5717: # set start and finish to negative values for userrolelog
                   5718:            $start=-1;
                   5719:            $end=-1;
1.957     raeburn  5720:            $delflag = 1;
1.357     www      5721:         }
                   5722:     }
                   5723: # send command
1.349     www      5724:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5725: # log new user role if status is ok
1.349     www      5726:     if ($answer eq 'ok') {
1.663     raeburn  5727: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5728: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5729:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5730:         unless ($role =~ /^gr/) {
                   5731:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5732:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5733:         }
1.349     www      5734:     }
                   5735:     return $answer;
1.169     harris41 5736: }
                   5737: 
                   5738: # -------------------------------------------------- Modify user authentication
1.197     www      5739: # Overrides without validation
                   5740: 
1.169     harris41 5741: sub modifyuserauth {
                   5742:     my ($udom,$uname,$umode,$upass)=@_;
                   5743:     my $uhome=&homeserver($uname,$udom);
1.197     www      5744:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5745:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5746:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5747:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5748:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5749: 		     &escape($upass),$uhome);
1.620     albertel 5750:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5751:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5752:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5753:     &log($udom,,$uname,$uhome,
1.620     albertel 5754:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5755:                                      $env{'user.name'}.', '.$umode.
1.197     www      5756:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5757:     unless ($reply eq 'ok') {
1.197     www      5758:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5759: 	return 'error: '.$reply;
                   5760:     }   
1.170     harris41 5761:     return 'ok';
1.80      www      5762: }
                   5763: 
1.81      www      5764: # --------------------------------------------------------------- Modify a user
1.80      www      5765: 
1.81      www      5766: sub modifyuser {
1.206     matthew  5767:     my ($udom,    $uname, $uid,
                   5768:         $umode,   $upass, $first,
                   5769:         $middle,  $last,  $gene,
1.963     raeburn  5770:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5771:     $udom= &LONCAPA::clean_domain($udom);
                   5772:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5773:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5774:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5775: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5776:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5777:                                      ' desiredhome not specified'). 
1.620     albertel 5778:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5779:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5780:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5781: # ----------------------------------------------------------------- Create User
1.406     albertel 5782:     if (($uhome eq 'no_host') && 
                   5783: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5784:         my $unhome='';
1.844     albertel 5785:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5786:             $unhome = $desiredhome;
1.620     albertel 5787: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5788: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5789:         } else { # load balancing routine for determining $unhome
1.81      www      5790:             my $loadm=10000000;
1.841     albertel 5791: 	    my %servers = &get_servers($udom,'library');
                   5792: 	    foreach my $tryserver (keys(%servers)) {
                   5793: 		my $answer=reply('load',$tryserver);
                   5794: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5795: 		    $loadm=$answer;
                   5796: 		    $unhome=$tryserver;
                   5797: 		}
1.80      www      5798: 	    }
                   5799:         }
                   5800:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5801: 	    return 'error: unable to find a home server for '.$uname.
                   5802:                    ' in domain '.$udom;
1.80      www      5803:         }
                   5804:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5805:                          &escape($upass),$unhome);
                   5806: 	unless ($reply eq 'ok') {
                   5807:             return 'error: '.$reply;
                   5808:         }   
1.230     stredwic 5809:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5810:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5811: 	    return 'error: unable verify users home machine.';
1.80      www      5812:         }
1.209     matthew  5813:     }   # End of creation of new user
1.80      www      5814: # ---------------------------------------------------------------------- Add ID
                   5815:     if ($uid) {
                   5816:        $uid=~tr/A-Z/a-z/;
                   5817:        my %uidhash=&idrget($udom,$uname);
1.196     www      5818:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5819:          && (!$forceid)) {
1.80      www      5820: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5821: 	      return 'error: user id "'.$uid.'" does not match '.
                   5822:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5823:           }
                   5824:        } else {
                   5825: 	  &idput($udom,($uname => $uid));
                   5826:        }
                   5827:     }
                   5828: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5829:     my @tmp=&get('environment',
1.899     raeburn  5830: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5831:                     'permanentemail','inststatus'],
1.134     albertel 5832: 		   $udom,$uname);
1.313     matthew  5833:     my %names;
                   5834:     if ($tmp[0] =~ m/^error:.*/) { 
                   5835:         %names=(); 
                   5836:     } else {
                   5837:         %names = @tmp;
                   5838:     }
1.388     www      5839: #
                   5840: # Make sure to not trash student environment if instructor does not bother
                   5841: # to supply name and email information
                   5842: #
                   5843:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5844:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5845:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5846:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5847:     if ($email) {
                   5848:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5849:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5850:     }
1.899     raeburn  5851:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5852:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5853:     my $reply = &put('environment', \%names, $udom,$uname);
                   5854:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5855:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5856:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5857:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5858:                  $umode.', '.$first.', '.$middle.', '.
                   5859: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5860:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5861:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5862:     } else {
                   5863:         $logmsg .= ' during self creation';
                   5864:     }
                   5865:     &logthis($logmsg);
1.134     albertel 5866:     return 'ok';
1.80      www      5867: }
                   5868: 
1.81      www      5869: # -------------------------------------------------------------- Modify student
1.80      www      5870: 
1.81      www      5871: sub modifystudent {
                   5872:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5873:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5874:         $selfenroll,$context)=@_;
1.455     albertel 5875:     if (!$cid) {
1.620     albertel 5876: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5877: 	    return 'not_in_class';
                   5878: 	}
1.80      www      5879:     }
                   5880: # --------------------------------------------------------------- Make the user
1.81      www      5881:     my $reply=&modifyuser
1.209     matthew  5882: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5883:          $desiredhome,$email);
1.80      www      5884:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5885:     # This will cause &modify_student_enrollment to get the uid from the
                   5886:     # students environment
                   5887:     $uid = undef if (!$forceid);
1.455     albertel 5888:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5889: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5890:     return $reply;
                   5891: }
                   5892: 
                   5893: sub modify_student_enrollment {
1.957     raeburn  5894:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5895:     my ($cdom,$cnum,$chome);
                   5896:     if (!$cid) {
1.620     albertel 5897: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5898: 	    return 'not_in_class';
                   5899: 	}
1.620     albertel 5900: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5901: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5902:     } else {
                   5903: 	($cdom,$cnum)=split(/_/,$cid);
                   5904:     }
1.620     albertel 5905:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5906:     if (!$chome) {
1.457     raeburn  5907: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5908:     }
1.455     albertel 5909:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5910:     # Make sure the user exists
1.81      www      5911:     my $uhome=&homeserver($uname,$udom);
                   5912:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5913: 	return 'error: no such user';
                   5914:     }
1.297     matthew  5915:     # Get student data if we were not given enough information
                   5916:     if (!defined($first)  || $first  eq '' || 
                   5917:         !defined($last)   || $last   eq '' || 
                   5918:         !defined($uid)    || $uid    eq '' || 
                   5919:         !defined($middle) || $middle eq '' || 
                   5920:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5921:         # They did not supply us with enough data to enroll the student, so
                   5922:         # we need to pick up more information.
1.297     matthew  5923:         my %tmp = &get('environment',
1.294     matthew  5924:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5925:                        ,$udom,$uname);
                   5926: 
1.800     albertel 5927:         #foreach my $key (keys(%tmp)) {
                   5928:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5929:         #}
1.294     matthew  5930:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5931:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5932:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5933:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5934:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5935:     }
1.556     albertel 5936:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5937:     my $reply=cput('classlist',
                   5938: 		   {"$uname:$udom" => 
1.515     raeburn  5939: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5940: 		   $cdom,$cnum);
1.81      www      5941:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5942: 	return 'error: '.$reply;
1.652     albertel 5943:     } else {
                   5944: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5945:     }
1.297     matthew  5946:     # Add student role to user
1.83      www      5947:     my $uurl='/'.$cid;
1.81      www      5948:     $uurl=~s/\_/\//g;
                   5949:     if ($usec) {
                   5950: 	$uurl.='/'.$usec;
                   5951:     }
1.957     raeburn  5952:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5953: }
                   5954: 
1.556     albertel 5955: sub format_name {
                   5956:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5957:     my $name;
                   5958:     if ($first ne 'lastname') {
                   5959: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5960:     } else {
                   5961: 	if ($lastname=~/\S/) {
                   5962: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5963: 	    $name=~s/\s+,/,/;
                   5964: 	} else {
                   5965: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5966: 	}
                   5967:     }
                   5968:     $name=~s/^\s+//;
                   5969:     $name=~s/\s+$//;
                   5970:     $name=~s/\s+/ /g;
                   5971:     return $name;
                   5972: }
                   5973: 
1.84      www      5974: # ------------------------------------------------- Write to course preferences
                   5975: 
                   5976: sub writecoursepref {
                   5977:     my ($courseid,%prefs)=@_;
                   5978:     $courseid=~s/^\///;
                   5979:     $courseid=~s/\_/\//g;
                   5980:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5981:     my $chome=homeserver($cnum,$cdomain);
                   5982:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5983: 	return 'error: no such course';
                   5984:     }
                   5985:     my $cstring='';
1.800     albertel 5986:     foreach my $pref (keys(%prefs)) {
                   5987: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5988:     }
1.84      www      5989:     $cstring=~s/\&$//;
                   5990:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5991: }
                   5992: 
                   5993: # ---------------------------------------------------------- Make/modify course
                   5994: 
                   5995: sub createcourse {
1.741     raeburn  5996:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5997:         $course_owner,$crstype)=@_;
1.84      www      5998:     $url=&declutter($url);
                   5999:     my $cid='';
1.264     matthew  6000:     unless (&allowed('ccc',$udom)) {
1.84      www      6001:         return 'refused';
                   6002:     }
                   6003: # ------------------------------------------------------------------- Create ID
1.674     www      6004:    my $uname=int(1+rand(9)).
                   6005:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6006:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6007:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6008: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6009:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6010:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6011:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6012:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6013:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6014:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6015:            return 'error: unable to generate unique course-ID';
                   6016:        } 
                   6017:    }
1.264     matthew  6018: # ------------------------------------------------ Check supplied server name
1.620     albertel 6019:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6020:     if (! &is_library($course_server)) {
1.264     matthew  6021:         return 'error:bad server name '.$course_server;
                   6022:     }
1.84      www      6023: # ------------------------------------------------------------- Make the course
                   6024:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6025:                       $course_server);
1.84      www      6026:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6027:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6028:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6029: 	return 'error: no such course';
                   6030:     }
1.271     www      6031: # ----------------------------------------------------------------- Course made
1.516     raeburn  6032: # log existence
1.918     raeburn  6033:     my $newcourse = {
                   6034:                     $udom.'_'.$uname => {
1.921     raeburn  6035:                                      description => $description,
                   6036:                                      inst_code   => $inst_code,
                   6037:                                      owner       => $course_owner,
                   6038:                                      type        => $crstype,
1.918     raeburn  6039:                                                 },
                   6040:                     };
1.921     raeburn  6041:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6042: # set toplevel url
1.271     www      6043:     my $topurl=$url;
                   6044:     unless ($nonstandard) {
                   6045: # ------------------------------------------ For standard courses, make top url
                   6046:         my $mapurl=&clutter($url);
1.278     www      6047:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6048:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6049: <map>
                   6050: <resource id="1" type="start"></resource>
                   6051: <resource id="2" src="$mapurl"></resource>
                   6052: <resource id="3" type="finish"></resource>
                   6053: <link index="1" from="1" to="2"></link>
                   6054: <link index="2" from="2" to="3"></link>
                   6055: </map>
                   6056: ENDINITMAP
                   6057:         $topurl=&declutter(
1.638     albertel 6058:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6059:                           );
                   6060:     }
                   6061: # ----------------------------------------------------------- Write preferences
1.84      www      6062:     &writecoursepref($udom.'_'.$uname,
                   6063:                      ('description' => $description,
1.271     www      6064:                       'url'         => $topurl));
1.84      www      6065:     return '/'.$udom.'/'.$uname;
                   6066: }
                   6067: 
1.813     albertel 6068: sub is_course {
                   6069:     my ($cdom,$cnum) = @_;
                   6070:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6071: 				undef,'.');
1.813     albertel 6072:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6073:         return 1;
                   6074:     }
                   6075:     return 0;
                   6076: }
                   6077: 
1.21      www      6078: # ---------------------------------------------------------- Assign Custom Role
                   6079: 
                   6080: sub assigncustomrole {
1.957     raeburn  6081:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6082:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6083:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6084: }
                   6085: 
                   6086: # ----------------------------------------------------------------- Revoke Role
                   6087: 
                   6088: sub revokerole {
1.957     raeburn  6089:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6090:     my $now=time;
1.965     raeburn  6091:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6092: }
                   6093: 
                   6094: # ---------------------------------------------------------- Revoke Custom Role
                   6095: 
                   6096: sub revokecustomrole {
1.957     raeburn  6097:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6098:     my $now=time;
1.357     www      6099:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6100:            $deleteflag,$selfenroll,$context);
1.17      www      6101: }
                   6102: 
1.533     banghart 6103: # ------------------------------------------------------------ Disk usage
1.535     albertel 6104: sub diskusage {
1.955     raeburn  6105:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6106:     $directorypath =~ s/\/$//;
                   6107:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6108:                        .&escape($getpropath).':'.&escape($uname).':'
                   6109:                        .&escape($udom),homeserver($uname,$udom));
                   6110:     if ($listing eq 'unknown_cmd') {
                   6111:         if ($getpropath) {
                   6112:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6113:         }
                   6114:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6115:     }
1.514     albertel 6116:     return $listing;
1.512     banghart 6117: }
                   6118: 
1.566     banghart 6119: sub is_locked {
                   6120:     my ($file_name, $domain, $user) = @_;
                   6121:     my @check;
                   6122:     my $is_locked;
                   6123:     push @check, $file_name;
1.613     albertel 6124:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6125: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6126:     my ($tmp)=keys(%locked);
                   6127:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6128:     
1.566     banghart 6129:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6130:         $is_locked = 'false';
                   6131:         foreach my $entry (@{$locked{$file_name}}) {
                   6132:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6133:                $is_locked = 'true';
                   6134:                last;
1.745     raeburn  6135:            }
                   6136:        }
1.566     banghart 6137:     } else {
                   6138:         $is_locked = 'false';
                   6139:     }
                   6140: }
                   6141: 
1.759     albertel 6142: sub declutter_portfile {
                   6143:     my ($file) = @_;
1.833     albertel 6144:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6145:     return $file;
                   6146: }
                   6147: 
1.559     banghart 6148: # ------------------------------------------------------------- Mark as Read Only
                   6149: 
                   6150: sub mark_as_readonly {
                   6151:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6152:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6153:     my ($tmp)=keys(%current_permissions);
                   6154:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6155:     foreach my $file (@{$files}) {
1.759     albertel 6156: 	$file = &declutter_portfile($file);
1.561     banghart 6157:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6158:     }
1.613     albertel 6159:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6160:     return;
                   6161: }
                   6162: 
1.572     banghart 6163: # ------------------------------------------------------------Save Selected Files
                   6164: 
                   6165: sub save_selected_files {
                   6166:     my ($user, $path, @files) = @_;
                   6167:     my $filename = $user."savedfiles";
1.573     banghart 6168:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6169:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6170:     foreach my $file (@files) {
1.620     albertel 6171:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6172:     }
                   6173:     foreach my $file (@other_files) {
1.574     banghart 6174:         print (OUT $file."\n");
1.572     banghart 6175:     }
1.574     banghart 6176:     close (OUT);
1.572     banghart 6177:     return 'ok';
                   6178: }
                   6179: 
1.574     banghart 6180: sub clear_selected_files {
                   6181:     my ($user) = @_;
                   6182:     my $filename = $user."savedfiles";
                   6183:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6184:     print (OUT undef);
                   6185:     close (OUT);
                   6186:     return ("ok");    
                   6187: }
                   6188: 
1.572     banghart 6189: sub files_in_path {
                   6190:     my ($user, $path) = @_;
                   6191:     my $filename = $user."savedfiles";
                   6192:     my %return_files;
1.574     banghart 6193:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6194:     while (my $line_in = <IN>) {
1.574     banghart 6195:         chomp ($line_in);
                   6196:         my @paths_and_file = split (m!/!, $line_in);
                   6197:         my $file_part = pop (@paths_and_file);
                   6198:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6199:         $path_part.='/';
                   6200:         my $path_and_file = $path_part.$file_part;
                   6201:         if ($path_part eq $path) {
                   6202:             $return_files{$file_part}= 'selected';
                   6203:         }
                   6204:     }
1.574     banghart 6205:     close (IN);
                   6206:     return (\%return_files);
1.572     banghart 6207: }
                   6208: 
                   6209: # called in portfolio select mode, to show files selected NOT in current directory
                   6210: sub files_not_in_path {
                   6211:     my ($user, $path) = @_;
                   6212:     my $filename = $user."savedfiles";
                   6213:     my @return_files;
                   6214:     my $path_part;
1.800     albertel 6215:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6216:     while (my $line = <IN>) {
1.572     banghart 6217:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6218:         my @paths_and_file = split(m|/|, $line);
                   6219:         my $file_part = pop(@paths_and_file);
                   6220:         chomp($file_part);
                   6221:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6222:         $path_part .= '/';
                   6223:         my $path_and_file = $path_part.$file_part;
                   6224:         if ($path_part ne $path) {
1.800     albertel 6225:             push(@return_files, ($path_and_file));
1.572     banghart 6226:         }
                   6227:     }
1.800     albertel 6228:     close(OUT);
1.574     banghart 6229:     return (@return_files);
1.572     banghart 6230: }
                   6231: 
1.745     raeburn  6232: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6233: 
1.745     raeburn  6234: sub get_portfile_permissions {
                   6235:     my ($domain,$user) = @_;
1.613     albertel 6236:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6237:     my ($tmp)=keys(%current_permissions);
                   6238:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6239:     return \%current_permissions;
                   6240: }
                   6241: 
                   6242: #---------------------------------------------Get portfolio file access controls
                   6243: 
1.749     raeburn  6244: sub get_access_controls {
1.745     raeburn  6245:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6246:     my %access;
                   6247:     my $real_file = $file;
                   6248:     $file =~ s/\.meta$//;
1.745     raeburn  6249:     if (defined($file)) {
1.749     raeburn  6250:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6251:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6252:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6253:             }
                   6254:         }
1.745     raeburn  6255:     } else {
1.749     raeburn  6256:         foreach my $key (keys(%{$current_permissions})) {
                   6257:             if ($key =~ /\0accesscontrol$/) {
                   6258:                 if (defined($group)) {
                   6259:                     if ($key !~ m-^\Q$group\E/-) {
                   6260:                         next;
                   6261:                     }
                   6262:                 }
                   6263:                 my ($fullpath) = split(/\0/,$key);
                   6264:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6265:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6266:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6267:                     }
                   6268:                 }
                   6269:             }
                   6270:         }
                   6271:     }
                   6272:     return %access;
                   6273: }
                   6274: 
                   6275: sub modify_access_controls {
                   6276:     my ($file_name,$changes,$domain,$user)=@_;
                   6277:     my ($outcome,$deloutcome);
                   6278:     my %store_permissions;
                   6279:     my %new_values;
                   6280:     my %new_control;
                   6281:     my %translation;
                   6282:     my @deletions = ();
                   6283:     my $now = time;
                   6284:     if (exists($$changes{'activate'})) {
                   6285:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6286:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6287:             my $numnew = scalar(@newitems);
                   6288:             for (my $i=0; $i<$numnew; $i++) {
                   6289:                 my $newkey = $newitems[$i];
                   6290:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6291:                 if ($newkey =~ /^\d+:/) { 
                   6292:                     $newkey =~ s/^(\d+)/$newid/;
                   6293:                     $translation{$1} = $newid;
                   6294:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6295:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6296:                     $translation{$1} = $newid;
                   6297:                 }
1.749     raeburn  6298:                 $new_values{$file_name."\0".$newkey} = 
                   6299:                                           $$changes{'activate'}{$newitems[$i]};
                   6300:                 $new_control{$newkey} = $now;
                   6301:             }
                   6302:         }
                   6303:     }
                   6304:     my %todelete;
                   6305:     my %changed_items;
                   6306:     foreach my $action ('delete','update') {
                   6307:         if (exists($$changes{$action})) {
                   6308:             if (ref($$changes{$action}) eq 'HASH') {
                   6309:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6310:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6311:                     if ($action eq 'delete') { 
                   6312:                         $todelete{$itemnum} = 1;
                   6313:                     } else {
                   6314:                         $changed_items{$itemnum} = $key;
                   6315:                     }
                   6316:                 }
1.745     raeburn  6317:             }
                   6318:         }
1.749     raeburn  6319:     }
                   6320:     # get lock on access controls for file.
                   6321:     my $lockhash = {
                   6322:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6323:                                                        ':'.$env{'user.domain'},
                   6324:                    }; 
                   6325:     my $tries = 0;
                   6326:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6327:    
                   6328:     while (($gotlock ne 'ok') && $tries <3) {
                   6329:         $tries ++;
                   6330:         sleep 1;
                   6331:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6332:     }
                   6333:     if ($gotlock eq 'ok') {
                   6334:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6335:         my ($tmp)=keys(%curr_permissions);
                   6336:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6337:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6338:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6339:             if (ref($curr_controls) eq 'HASH') {
                   6340:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6341:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6342:                     if (defined($todelete{$itemnum})) {
                   6343:                         push(@deletions,$file_name."\0".$control_item);
                   6344:                     } else {
                   6345:                         if (defined($changed_items{$itemnum})) {
                   6346:                             $new_control{$changed_items{$itemnum}} = $now;
                   6347:                             push(@deletions,$file_name."\0".$control_item);
                   6348:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6349:                         } else {
                   6350:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6351:                         }
                   6352:                     }
1.745     raeburn  6353:                 }
                   6354:             }
                   6355:         }
1.970     raeburn  6356:         my ($group);
                   6357:         if (&is_course($domain,$user)) {
                   6358:             ($group,my $file) = split(/\//,$file_name,2);
                   6359:         }
1.749     raeburn  6360:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6361:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6362:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6363:         #  remove lock
                   6364:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6365:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6366:         my $sqlresult =
1.970     raeburn  6367:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6368:                                     $group);
1.749     raeburn  6369:     } else {
                   6370:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6371:     }
1.749     raeburn  6372:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6373: }
                   6374: 
1.827     raeburn  6375: sub make_public_indefinitely {
                   6376:     my ($requrl) = @_;
                   6377:     my $now = time;
                   6378:     my $action = 'activate';
                   6379:     my $aclnum = 0;
                   6380:     if (&is_portfolio_url($requrl)) {
                   6381:         my (undef,$udom,$unum,$file_name,$group) =
                   6382:             &parse_portfolio_url($requrl);
                   6383:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6384:         my %access_controls = &get_access_controls($current_perms,
                   6385:                                                    $group,$file_name);
                   6386:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6387:             my ($num,$scope,$end,$start) = 
                   6388:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6389:             if ($scope eq 'public') {
                   6390:                 if ($start <= $now && $end == 0) {
                   6391:                     $action = 'none';
                   6392:                 } else {
                   6393:                     $action = 'update';
                   6394:                     $aclnum = $num;
                   6395:                 }
                   6396:                 last;
                   6397:             }
                   6398:         }
                   6399:         if ($action eq 'none') {
                   6400:              return 'ok';
                   6401:         } else {
                   6402:             my %changes;
                   6403:             my $newend = 0;
                   6404:             my $newstart = $now;
                   6405:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6406:             $changes{$action}{$newkey} = {
                   6407:                 type => 'public',
                   6408:                 time => {
                   6409:                     start => $newstart,
                   6410:                     end   => $newend,
                   6411:                 },
                   6412:             };
                   6413:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6414:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6415:             return $outcome;
                   6416:         }
                   6417:     } else {
                   6418:         return 'invalid';
                   6419:     }
                   6420: }
                   6421: 
1.745     raeburn  6422: #------------------------------------------------------Get Marked as Read Only
                   6423: 
                   6424: sub get_marked_as_readonly {
                   6425:     my ($domain,$user,$what,$group) = @_;
                   6426:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6427:     my @readonly_files;
1.629     banghart 6428:     my $cmp1=$what;
                   6429:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6430:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6431:         if (defined($group)) {
                   6432:             if ($file_name !~ m-^\Q$group\E/-) {
                   6433:                 next;
                   6434:             }
                   6435:         }
1.561     banghart 6436:         if (ref($value) eq "ARRAY"){
                   6437:             foreach my $stored_what (@{$value}) {
1.629     banghart 6438:                 my $cmp2=$stored_what;
1.759     albertel 6439:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6440:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6441:                 }
1.629     banghart 6442:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6443:                     push(@readonly_files, $file_name);
1.745     raeburn  6444:                     last;
1.563     banghart 6445:                 } elsif (!defined($what)) {
                   6446:                     push(@readonly_files, $file_name);
1.745     raeburn  6447:                     last;
1.561     banghart 6448:                 }
                   6449:             }
1.745     raeburn  6450:         }
1.561     banghart 6451:     }
                   6452:     return @readonly_files;
                   6453: }
1.577     banghart 6454: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6455: 
1.577     banghart 6456: sub get_marked_as_readonly_hash {
1.745     raeburn  6457:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6458:     my %readonly_files;
1.745     raeburn  6459:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6460:         if (defined($group)) {
                   6461:             if ($file_name !~ m-^\Q$group\E/-) {
                   6462:                 next;
                   6463:             }
                   6464:         }
1.577     banghart 6465:         if (ref($value) eq "ARRAY"){
                   6466:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6467:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6468:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6469:                         if ($lock_descriptor eq 'graded') {
                   6470:                             $readonly_files{$file_name} = 'graded';
                   6471:                         } elsif ($lock_descriptor eq 'handback') {
                   6472:                             $readonly_files{$file_name} = 'handback';
                   6473:                         } else {
                   6474:                             if (!exists($readonly_files{$file_name})) {
                   6475:                                 $readonly_files{$file_name} = 'locked';
                   6476:                             }
                   6477:                         }
1.745     raeburn  6478:                     }
1.750     banghart 6479:                 } 
1.577     banghart 6480:             }
                   6481:         } 
                   6482:     }
                   6483:     return %readonly_files;
                   6484: }
1.559     banghart 6485: # ------------------------------------------------------------ Unmark as Read Only
                   6486: 
                   6487: sub unmark_as_readonly {
1.629     banghart 6488:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6489:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6490:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6491:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6492:     my $symb_crs = $what;
                   6493:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6494:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6495:     my ($tmp)=keys(%current_permissions);
                   6496:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6497:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6498:     foreach my $file (@readonly_files) {
1.759     albertel 6499: 	my $clean_file = &declutter_portfile($file);
                   6500: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6501: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6502:         my @new_locks;
                   6503:         my @del_keys;
                   6504:         if (ref($current_locks) eq "ARRAY"){
                   6505:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6506:                 my $compare=$locker;
1.749     raeburn  6507:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6508:                     $compare=join('',@{$locker});
1.746     raeburn  6509:                     if ($compare ne $symb_crs) {
                   6510:                         push(@new_locks, $locker);
                   6511:                     }
1.563     banghart 6512:                 }
                   6513:             }
1.650     albertel 6514:             if (scalar(@new_locks) > 0) {
1.563     banghart 6515:                 $current_permissions{$file} = \@new_locks;
                   6516:             } else {
                   6517:                 push(@del_keys, $file);
1.613     albertel 6518:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6519:                 delete($current_permissions{$file});
1.563     banghart 6520:             }
                   6521:         }
1.561     banghart 6522:     }
1.613     albertel 6523:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6524:     return;
                   6525: }
1.512     banghart 6526: 
1.17      www      6527: # ------------------------------------------------------------ Directory lister
                   6528: 
                   6529: sub dirlist {
1.955     raeburn  6530:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6531:     $uri=~s/^\///;
                   6532:     $uri=~s/\/$//;
1.253     stredwic 6533:     my ($udom, $uname);
1.955     raeburn  6534:     if ($getuserdir) {
1.253     stredwic 6535:         $udom = $userdomain;
                   6536:         $uname = $username;
1.955     raeburn  6537:     } else {
                   6538:         (undef,$udom,$uname)=split(/\//,$uri);
                   6539:         if(defined($userdomain)) {
                   6540:             $udom = $userdomain;
                   6541:         }
                   6542:         if(defined($username)) {
                   6543:             $uname = $username;
                   6544:         }
1.253     stredwic 6545:     }
1.955     raeburn  6546:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6547: 
1.955     raeburn  6548:     $dirRoot = $perlvar{'lonDocRoot'};
                   6549:     if (defined($getpropath)) {
                   6550:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6551:         $dirRoot =~ s/\/$//;
1.955     raeburn  6552:     } elsif (defined($getuserdir)) {
                   6553:         my $subdir=$uname.'__';
                   6554:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6555:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6556:                    ."/$udom/$subdir/$uname";
                   6557:     } elsif (defined($alternateRoot)) {
                   6558:         $dirRoot = $alternateRoot;
1.751     banghart 6559:     }
1.253     stredwic 6560: 
                   6561:     if($udom) {
                   6562:         if($uname) {
1.955     raeburn  6563:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6564:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6565:                               .':'.&escape($uname).':'.&escape($udom),
                   6566:                               &homeserver($uname,$udom));
                   6567:             if ($listing eq 'unknown_cmd') {
                   6568:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6569:                                   &homeserver($uname,$udom));
                   6570:             } else {
                   6571:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6572:             }
1.605     matthew  6573:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6574:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6575: 				  &homeserver($uname,$udom));
1.605     matthew  6576:                 @listing_results = split(/:/,$listing);
                   6577:             } else {
                   6578:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6579:             }
                   6580:             return @listing_results;
1.955     raeburn  6581:         } elsif(!$alternateRoot) {
1.800     albertel 6582:             my %allusers;
1.841     albertel 6583: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6584:  	    foreach my $tryserver (keys(%servers)) {
                   6585:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6586:                                   &escape($udom),$tryserver);
                   6587:                 if ($listing eq 'unknown_cmd') {
                   6588: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6589: 				      $udom, $tryserver);
                   6590:                 } else {
                   6591:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6592:                 }
1.841     albertel 6593: 		if ($listing eq 'unknown_cmd') {
                   6594: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6595: 				      $udom, $tryserver);
                   6596: 		    @listing_results = split(/:/,$listing);
                   6597: 		} else {
                   6598: 		    @listing_results =
                   6599: 			map { &unescape($_); } split(/:/,$listing);
                   6600: 		}
                   6601: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6602: 		    $listing_results[0] ne 'empty'       &&
                   6603: 		    $listing_results[0] ne 'con_lost') {
                   6604: 		    foreach my $line (@listing_results) {
                   6605: 			my ($entry) = split(/&/,$line,2);
                   6606: 			$allusers{$entry} = 1;
                   6607: 		    }
                   6608: 		}
1.253     stredwic 6609:             }
                   6610:             my $alluserstr='';
1.800     albertel 6611:             foreach my $user (sort(keys(%allusers))) {
                   6612:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6613:             }
                   6614:             $alluserstr=~s/:$//;
                   6615:             return split(/:/,$alluserstr);
                   6616:         } else {
1.800     albertel 6617:             return ('missing user name');
1.253     stredwic 6618:         }
1.955     raeburn  6619:     } elsif(!defined($getpropath)) {
1.841     albertel 6620:         my @all_domains = sort(&all_domains());
1.955     raeburn  6621:         foreach my $domain (@all_domains) {
                   6622:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6623:         }
                   6624:         return @all_domains;
                   6625:     } else {
1.800     albertel 6626:         return ('missing domain');
1.275     stredwic 6627:     }
                   6628: }
                   6629: 
                   6630: # --------------------------------------------- GetFileTimestamp
                   6631: # This function utilizes dirlist and returns the date stamp for
                   6632: # when it was last modified.  It will also return an error of -1
                   6633: # if an error occurs
                   6634: 
                   6635: sub GetFileTimestamp {
1.955     raeburn  6636:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6637:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6638:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6639:     my ($fileStat) = 
                   6640:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6641:                                  undef,$getuserdir);
1.275     stredwic 6642:     my @stats = split('&', $fileStat);
                   6643:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6644:         # @stats contains first the filename, then the stat output
                   6645:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6646:     } else {
                   6647:         return -1;
1.253     stredwic 6648:     }
1.26      www      6649: }
                   6650: 
1.712     albertel 6651: sub stat_file {
                   6652:     my ($uri) = @_;
1.787     albertel 6653:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6654: 
1.955     raeburn  6655:     my ($udom,$uname,$file);
1.712     albertel 6656:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6657: 	($udom,$uname,$file) =
1.811     albertel 6658: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6659: 	$file = 'userfiles/'.$file;
                   6660:     }
                   6661:     if ($uri =~ m-^/res/-) {
                   6662: 	($udom,$uname) = 
1.807     albertel 6663: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6664: 	$file = $uri;
                   6665:     }
                   6666: 
                   6667:     if (!$udom || !$uname || !$file) {
                   6668: 	# unable to handle the uri
                   6669: 	return ();
                   6670:     }
1.956     raeburn  6671:     my $getpropath;
                   6672:     if ($file =~ /^userfiles\//) {
                   6673:         $getpropath = 1;
                   6674:     }
1.955     raeburn  6675:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6676:     my @stats = split('&', $result);
1.721     banghart 6677:     
1.712     albertel 6678:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6679: 	shift(@stats); #filename is first
                   6680: 	return @stats;
                   6681:     }
                   6682:     return ();
                   6683: }
                   6684: 
1.26      www      6685: # -------------------------------------------------------- Value of a Condition
                   6686: 
1.713     albertel 6687: # gets the value of a specific preevaluated condition
                   6688: #    stored in the string  $env{user.state.<cid>}
                   6689: # or looks up a condition reference in the bighash and if if hasn't
                   6690: # already been evaluated recurses into docondval to get the value of
                   6691: # the condition, then memoizing it to 
                   6692: #   $env{user.state.<cid>.<condition>}
1.40      www      6693: sub directcondval {
                   6694:     my $number=shift;
1.620     albertel 6695:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6696: 	&Apache::lonuserstate::evalstate();
                   6697:     }
1.713     albertel 6698:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6699: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6700:     } elsif ($number =~ /^_/) {
                   6701: 	my $sub_condition;
                   6702: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6703: 		&GDBM_READER(),0640)) {
                   6704: 	    $sub_condition=$bighash{'conditions'.$number};
                   6705: 	    untie(%bighash);
                   6706: 	}
                   6707: 	my $value = &docondval($sub_condition);
1.949     raeburn  6708: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6709: 	return $value;
                   6710:     }
1.620     albertel 6711:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6712:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6713:     } else {
                   6714:        return 2;
                   6715:     }
                   6716: }
                   6717: 
1.713     albertel 6718: # get the collection of conditions for this resource
1.26      www      6719: sub condval {
                   6720:     my $condidx=shift;
1.54      www      6721:     my $allpathcond='';
1.713     albertel 6722:     foreach my $cond (split(/\|/,$condidx)) {
                   6723: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6724: 	    $allpathcond.=
                   6725: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6726: 	}
1.191     harris41 6727:     }
1.54      www      6728:     $allpathcond=~s/\|$//;
1.713     albertel 6729:     return &docondval($allpathcond);
                   6730: }
                   6731: 
                   6732: #evaluates an expression of conditions
                   6733: sub docondval {
                   6734:     my ($allpathcond) = @_;
                   6735:     my $result=0;
                   6736:     if ($env{'request.course.id'}
                   6737: 	&& defined($allpathcond)) {
                   6738: 	my $operand='|';
                   6739: 	my @stack;
                   6740: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6741: 	    if ($chunk eq '(') {
                   6742: 		push @stack,($operand,$result);
                   6743: 	    } elsif ($chunk eq ')') {
                   6744: 		my $before=pop @stack;
                   6745: 		if (pop @stack eq '&') {
                   6746: 		    $result=$result>$before?$before:$result;
                   6747: 		} else {
                   6748: 		    $result=$result>$before?$result:$before;
                   6749: 		}
                   6750: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6751: 		$operand=$chunk;
                   6752: 	    } else {
                   6753: 		my $new=directcondval($chunk);
                   6754: 		if ($operand eq '&') {
                   6755: 		    $result=$result>$new?$new:$result;
                   6756: 		} else {
                   6757: 		    $result=$result>$new?$result:$new;
                   6758: 		}
                   6759: 	    }
                   6760: 	}
1.26      www      6761:     }
                   6762:     return $result;
1.421     albertel 6763: }
                   6764: 
                   6765: # ---------------------------------------------------- Devalidate courseresdata
                   6766: 
                   6767: sub devalidatecourseresdata {
                   6768:     my ($coursenum,$coursedomain)=@_;
                   6769:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6770:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6771: }
                   6772: 
1.763     www      6773: 
1.200     www      6774: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6775: #
                   6776: #  Parameters:
                   6777: #      $coursenum    - Number of the course.
                   6778: #      $coursedomain - Domain at which the course was created.
                   6779: #  Returns:
                   6780: #     A hash of the course parameters along (I think) with timestamps
                   6781: #     and version info.
1.877     foxr     6782: 
1.624     albertel 6783: sub get_courseresdata {
                   6784:     my ($coursenum,$coursedomain)=@_;
1.200     www      6785:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6786:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6787:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6788:     my %dumpreply;
1.417     albertel 6789:     unless (defined($cached)) {
1.624     albertel 6790: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6791: 	$result=\%dumpreply;
1.251     albertel 6792: 	my ($tmp) = keys(%dumpreply);
                   6793: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6794: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6795: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6796: 	    return $tmp;
1.416     albertel 6797: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6798: 	    $result=undef;
1.599     albertel 6799: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6800: 	}
                   6801:     }
1.624     albertel 6802:     return $result;
                   6803: }
                   6804: 
1.633     albertel 6805: sub devalidateuserresdata {
                   6806:     my ($uname,$udom)=@_;
                   6807:     my $hashid="$udom:$uname";
                   6808:     &devalidate_cache_new('userres',$hashid);
                   6809: }
                   6810: 
1.624     albertel 6811: sub get_userresdata {
                   6812:     my ($uname,$udom)=@_;
                   6813:     #most student don\'t have any data set, check if there is some data
                   6814:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6815: 
                   6816:     my $hashid="$udom:$uname";
                   6817:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6818:     if (!defined($cached)) {
                   6819: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6820: 	$result=\%resourcedata;
                   6821: 	&do_cache_new('userres',$hashid,$result,600);
                   6822:     }
                   6823:     my ($tmp)=keys(%$result);
                   6824:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6825: 	return $result;
                   6826:     }
                   6827:     #error 2 occurs when the .db doesn't exist
                   6828:     if ($tmp!~/error: 2 /) {
1.672     albertel 6829: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6830: 		 " Trying to get resource data for ".
                   6831: 		 $uname." at ".$udom.": ".
                   6832: 		 $tmp."</font>");
                   6833:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6834: 	#&EXT_cache_set($udom,$uname);
                   6835: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6836: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6837:     }
                   6838:     return $tmp;
                   6839: }
1.879     foxr     6840: #----------------------------------------------- resdata - return resource data
                   6841: #  Purpose:
                   6842: #    Return resource data for either users or for a course.
                   6843: #  Parameters:
                   6844: #     $name      - Course/user name.
                   6845: #     $domain    - Name of the domain the user/course is registered on.
                   6846: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6847: #     @which     - Array of names of resources desired.
                   6848: #  Returns:
                   6849: #     The value of the first reasource in @which that is found in the
                   6850: #     resource hash.
                   6851: #  Exceptional Conditions:
                   6852: #     If the $type passed in is not valid (not the string 'course' or 
                   6853: #     'user', an undefined  reference is returned.
                   6854: #     If none of the resources are found, an undef is returned
1.624     albertel 6855: sub resdata {
                   6856:     my ($name,$domain,$type,@which)=@_;
                   6857:     my $result;
                   6858:     if ($type eq 'course') {
                   6859: 	$result=&get_courseresdata($name,$domain);
                   6860:     } elsif ($type eq 'user') {
                   6861: 	$result=&get_userresdata($name,$domain);
                   6862:     }
                   6863:     if (!ref($result)) { return $result; }    
1.251     albertel 6864:     foreach my $item (@which) {
1.927     albertel 6865: 	if (defined($result->{$item->[0]})) {
                   6866: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6867: 	}
1.250     albertel 6868:     }
1.291     albertel 6869:     return undef;
1.200     www      6870: }
                   6871: 
1.379     matthew  6872: #
                   6873: # EXT resource caching routines
                   6874: #
                   6875: 
                   6876: sub clear_EXT_cache_status {
1.383     albertel 6877:     &delenv('cache.EXT.');
1.379     matthew  6878: }
                   6879: 
                   6880: sub EXT_cache_status {
                   6881:     my ($target_domain,$target_user) = @_;
1.383     albertel 6882:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6883:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6884:         # We know already the user has no data
                   6885:         return 1;
                   6886:     } else {
                   6887:         return 0;
                   6888:     }
                   6889: }
                   6890: 
                   6891: sub EXT_cache_set {
                   6892:     my ($target_domain,$target_user) = @_;
1.383     albertel 6893:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6894:     #&appenv({$cachename => time});
1.379     matthew  6895: }
                   6896: 
1.28      www      6897: # --------------------------------------------------------- Value of a Variable
1.58      www      6898: sub EXT {
1.715     albertel 6899: 
1.395     albertel 6900:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6901:     unless ($varname) { return ''; }
1.218     albertel 6902:     #get real user name/domain, courseid and symb
                   6903:     my $courseid;
1.359     albertel 6904:     my $publicuser;
1.427     www      6905:     if ($symbparm) {
                   6906: 	$symbparm=&get_symb_from_alias($symbparm);
                   6907:     }
1.218     albertel 6908:     if (!($uname && $udom)) {
1.790     albertel 6909:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6910:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6911:     } else {
1.620     albertel 6912: 	$courseid=$env{'request.course.id'};
1.218     albertel 6913:     }
1.48      www      6914:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6915:     my $rest;
1.320     albertel 6916:     if (defined($therest[0])) {
1.48      www      6917:        $rest=join('.',@therest);
                   6918:     } else {
                   6919:        $rest='';
                   6920:     }
1.320     albertel 6921: 
1.57      www      6922:     my $qualifierrest=$qualifier;
                   6923:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6924:     my $spacequalifierrest=$space;
                   6925:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6926:     if ($realm eq 'user') {
1.48      www      6927: # --------------------------------------------------------------- user.resource
                   6928: 	if ($space eq 'resource') {
1.651     albertel 6929: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6930: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6931: 		 &&
1.744     albertel 6932: 		 ($symbparm eq &symbread()) ) {	
                   6933: 		# if we are in the middle of processing the resource the
                   6934: 		# get the value we are planning on committing
                   6935:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6936:                     return $Apache::lonhomework::results{$qualifierrest};
                   6937:                 } else {
                   6938:                     return $Apache::lonhomework::history{$qualifierrest};
                   6939:                 }
1.335     albertel 6940: 	    } else {
1.359     albertel 6941: 		my %restored;
1.620     albertel 6942: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6943: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6944: 		} else {
                   6945: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6946: 		}
1.335     albertel 6947: 		return $restored{$qualifierrest};
                   6948: 	    }
1.48      www      6949: # ----------------------------------------------------------------- user.access
                   6950:         } elsif ($space eq 'access') {
1.218     albertel 6951: 	    # FIXME - not supporting calls for a specific user
1.48      www      6952:             return &allowed($qualifier,$rest);
                   6953: # ------------------------------------------ user.preferences, user.environment
                   6954:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6955: 	    if (($uname eq $env{'user.name'}) &&
                   6956: 		($udom eq $env{'user.domain'})) {
                   6957: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6958: 	    } else {
1.359     albertel 6959: 		my %returnhash;
                   6960: 		if (!$publicuser) {
                   6961: 		    %returnhash=&userenvironment($udom,$uname,
                   6962: 						 $qualifierrest);
                   6963: 		}
1.218     albertel 6964: 		return $returnhash{$qualifierrest};
                   6965: 	    }
1.48      www      6966: # ----------------------------------------------------------------- user.course
                   6967:         } elsif ($space eq 'course') {
1.218     albertel 6968: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6969:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6970: # ------------------------------------------------------------------- user.role
                   6971:         } elsif ($space eq 'role') {
1.218     albertel 6972: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6973:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6974:             if ($qualifier eq 'value') {
                   6975: 		return $role;
                   6976:             } elsif ($qualifier eq 'extent') {
                   6977:                 return $where;
                   6978:             }
                   6979: # ----------------------------------------------------------------- user.domain
                   6980:         } elsif ($space eq 'domain') {
1.218     albertel 6981:             return $udom;
1.48      www      6982: # ------------------------------------------------------------------- user.name
                   6983:         } elsif ($space eq 'name') {
1.218     albertel 6984:             return $uname;
1.48      www      6985: # ---------------------------------------------------- Any other user namespace
1.29      www      6986:         } else {
1.359     albertel 6987: 	    my %reply;
                   6988: 	    if (!$publicuser) {
                   6989: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6990: 	    }
                   6991: 	    return $reply{$qualifierrest};
1.48      www      6992:         }
1.236     www      6993:     } elsif ($realm eq 'query') {
                   6994: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6995:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6996: 						[$spacequalifierrest]);
1.620     albertel 6997: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6998:    } elsif ($realm eq 'request') {
1.48      www      6999: # ------------------------------------------------------------- request.browser
                   7000:         if ($space eq 'browser') {
1.430     www      7001: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7002: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7003: 		    return 1;
                   7004: 		} else {
                   7005: 		    return 0;
                   7006: 		}
                   7007: 	    } else {
1.620     albertel 7008: 		return $env{'browser.'.$qualifier};
1.430     www      7009: 	    }
1.57      www      7010: # ------------------------------------------------------------ request.filename
                   7011:         } else {
1.620     albertel 7012:             return $env{'request.'.$spacequalifierrest};
1.29      www      7013:         }
1.28      www      7014:     } elsif ($realm eq 'course') {
1.48      www      7015: # ---------------------------------------------------------- course.description
1.620     albertel 7016:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7017:     } elsif ($realm eq 'resource') {
1.165     www      7018: 
1.620     albertel 7019: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7020: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7021: 	}
1.693     albertel 7022: 
                   7023: 	if ($space eq 'title') {
                   7024: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7025: 	    return &gettitle($symbparm);
                   7026: 	}
                   7027: 	
                   7028: 	if ($space eq 'map') {
                   7029: 	    my ($map) = &decode_symb($symbparm);
                   7030: 	    return &symbread($map);
                   7031: 	}
1.905     albertel 7032: 	if ($space eq 'filename') {
                   7033: 	    if ($symbparm) {
                   7034: 		return &clutter((&decode_symb($symbparm))[2]);
                   7035: 	    }
                   7036: 	    return &hreflocation('',$env{'request.filename'});
                   7037: 	}
1.693     albertel 7038: 
                   7039: 	my ($section, $group, @groups);
1.593     albertel 7040: 	my ($courselevelm,$courselevel);
1.539     albertel 7041: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7042: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7043: 
1.218     albertel 7044: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7045: 
1.60      www      7046: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7047: 	    my $symbp=$symbparm;
1.735     albertel 7048: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7049: 
                   7050: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7051: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7052: 
1.620     albertel 7053: 	    if (($env{'user.name'} eq $uname) &&
                   7054: 		($env{'user.domain'} eq $udom)) {
                   7055: 		$section=$env{'request.course.sec'};
1.733     raeburn  7056:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7057:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7058: 	    } else {
1.539     albertel 7059: 		if (! defined($usection)) {
1.551     albertel 7060: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7061: 		} else {
                   7062: 		    $section = $usection;
                   7063: 		}
1.733     raeburn  7064:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7065: 	    }
                   7066: 
                   7067: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7068: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7069: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7070: 
1.593     albertel 7071: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7072: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7073: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7074: 
1.60      www      7075: # ----------------------------------------------------------- first, check user
1.624     albertel 7076: 
                   7077: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7078: 				       ([$courselevelr,'resource'],
                   7079: 					[$courselevelm,'map'     ],
                   7080: 					[$courselevel, 'course'  ]));
1.931     albertel 7081: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7082: 
1.594     albertel 7083: # ------------------------------------------------ second, check some of course
1.684     raeburn  7084:             my $coursereply;
1.691     raeburn  7085:             if (@groups > 0) {
                   7086:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7087:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7088:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7089:             }
1.96      www      7090: 
1.684     raeburn  7091: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7092: 				  $env{'course.'.$courseid.'.domain'},
                   7093: 				  'course',
                   7094: 				  ([$seclevelr,   'resource'],
                   7095: 				   [$seclevelm,   'map'     ],
                   7096: 				   [$seclevel,    'course'  ],
                   7097: 				   [$courselevelr,'resource']));
                   7098: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7099: 
1.60      www      7100: # ------------------------------------------------------ third, check map parms
1.218     albertel 7101: 	    my %parmhash=();
                   7102: 	    my $thisparm='';
                   7103: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7104: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7105: 		    &GDBM_READER(),0640)) {
1.218     albertel 7106: 		$thisparm=$parmhash{$symbparm};
                   7107: 		untie(%parmhash);
                   7108: 	    }
1.927     albertel 7109: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7110: 	}
1.594     albertel 7111: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7112: 
1.218     albertel 7113: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7114: 	my $filename;
                   7115: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7116: 	if ($symbparm) {
1.409     www      7117: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7118: 	} else {
1.620     albertel 7119: 	    $filename=$env{'request.filename'};
1.282     albertel 7120: 	}
                   7121: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7122: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7123: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7124: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7125: 
1.927     albertel 7126: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7127: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7128: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7129: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7130: 				     $env{'course.'.$courseid.'.domain'},
                   7131: 				     'course',
1.927     albertel 7132: 				     ([$courselevelm,'map'   ],
                   7133: 				      [$courselevel, 'course']));
                   7134: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7135: 	}
1.145     www      7136: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7137: 	unless ($space eq '0') {
1.336     albertel 7138: 	    my @parts=split(/_/,$space);
                   7139: 	    my $id=pop(@parts);
                   7140: 	    my $part=join('_',@parts);
                   7141: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7142: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7143: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7144: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7145: 	}
1.395     albertel 7146: 	if ($recurse) { return undef; }
                   7147: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7148: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7149: # ---------------------------------------------------- Any other user namespace
                   7150:     } elsif ($realm eq 'environment') {
                   7151: # ----------------------------------------------------------------- environment
1.620     albertel 7152: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7153: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7154: 	} else {
1.770     albertel 7155: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7156: 		return '';
                   7157: 	    }
1.219     albertel 7158: 	    my %returnhash=&userenvironment($udom,$uname,
                   7159: 					    $spacequalifierrest);
                   7160: 	    return $returnhash{$spacequalifierrest};
                   7161: 	}
1.28      www      7162:     } elsif ($realm eq 'system') {
1.48      www      7163: # ----------------------------------------------------------------- system.time
                   7164: 	if ($space eq 'time') {
                   7165: 	    return time;
                   7166:         }
1.696     albertel 7167:     } elsif ($realm eq 'server') {
                   7168: # ----------------------------------------------------------------- system.time
                   7169: 	if ($space eq 'name') {
                   7170: 	    return $ENV{'SERVER_NAME'};
                   7171:         }
1.28      www      7172:     }
1.48      www      7173:     return '';
1.61      www      7174: }
                   7175: 
1.927     albertel 7176: sub get_reply {
                   7177:     my ($reply_value) = @_;
1.940     raeburn  7178:     if (ref($reply_value) eq 'ARRAY') {
                   7179:         if (wantarray) {
                   7180: 	    return @$reply_value;
                   7181:         }
                   7182:         return $reply_value->[0];
                   7183:     } else {
                   7184:         return $reply_value;
1.927     albertel 7185:     }
                   7186: }
                   7187: 
1.691     raeburn  7188: sub check_group_parms {
                   7189:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7190:     my @groupitems = ();
                   7191:     my $resultitem;
1.927     albertel 7192:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7193:     foreach my $group (@{$groups}) {
                   7194:         foreach my $level (@levels) {
1.927     albertel 7195:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7196:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7197:         }
                   7198:     }
                   7199:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7200:                             $env{'course.'.$courseid.'.domain'},
                   7201:                                      'course',@groupitems);
                   7202:     return $coursereply;
                   7203: }
                   7204: 
                   7205: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7206:     my ($courseid,@groups) = @_;
                   7207:     @groups = sort(@groups);
1.691     raeburn  7208:     return @groups;
                   7209: }
                   7210: 
1.395     albertel 7211: sub packages_tab_default {
                   7212:     my ($uri,$varname)=@_;
                   7213:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7214: 
                   7215:     my (@extension,@specifics,$do_default);
                   7216:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7217: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7218: 	if ($pack_type eq 'default') {
                   7219: 	    $do_default=1;
                   7220: 	} elsif ($pack_type eq 'extension') {
                   7221: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7222: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7223: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7224: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7225: 	}
                   7226:     }
                   7227:     # first look for a package that matches the requested part id
                   7228:     foreach my $package (@specifics) {
                   7229: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7230: 	next if ($pack_part ne $part);
                   7231: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7232: 	    return $packagetab{"$pack_type&$name&default"};
                   7233: 	}
                   7234:     }
                   7235:     # look for any possible matching non extension_ package
                   7236:     foreach my $package (@specifics) {
                   7237: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7238: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7239: 	    return $packagetab{"$pack_type&$name&default"};
                   7240: 	}
1.585     albertel 7241: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7242: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7243: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7244: 	}
                   7245:     }
1.738     albertel 7246:     # look for any posible extension_ match
                   7247:     foreach my $package (@extension) {
                   7248: 	my ($package,$pack_type)=@{$package};
                   7249: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7250: 	    return $packagetab{"$pack_type&$name&default"};
                   7251: 	}
                   7252: 	if (defined($packagetab{$package."&$name&default"})) {
                   7253: 	    return $packagetab{$package."&$name&default"};
                   7254: 	}
                   7255:     }
                   7256:     # look for a global default setting
                   7257:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7258: 	return $packagetab{"default&$name&default"};
                   7259:     }
1.395     albertel 7260:     return undef;
                   7261: }
                   7262: 
1.334     albertel 7263: sub add_prefix_and_part {
                   7264:     my ($prefix,$part)=@_;
                   7265:     my $keyroot;
                   7266:     if (defined($prefix) && $prefix !~ /^__/) {
                   7267: 	# prefix that has a part already
                   7268: 	$keyroot=$prefix;
                   7269:     } elsif (defined($prefix)) {
                   7270: 	# prefix that is missing a part
                   7271: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7272:     } else {
                   7273: 	# no prefix at all
                   7274: 	if (defined($part)) { $keyroot='_'.$part; }
                   7275:     }
                   7276:     return $keyroot;
                   7277: }
                   7278: 
1.71      www      7279: # ---------------------------------------------------------------- Get metadata
                   7280: 
1.599     albertel 7281: my %metaentry;
1.71      www      7282: sub metadata {
1.176     www      7283:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7284:     $uri=&declutter($uri);
1.288     albertel 7285:     # if it is a non metadata possible uri return quickly
1.529     albertel 7286:     if (($uri eq '') || 
                   7287: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7288: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7289:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7290: 	return undef;
                   7291:     }
                   7292:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7293: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7294: 	return undef;
1.288     albertel 7295:     }
1.73      www      7296:     my $filename=$uri;
                   7297:     $uri=~s/\.meta$//;
1.172     www      7298: #
                   7299: # Is the metadata already cached?
1.177     www      7300: # Look at timestamp of caching
1.172     www      7301: # Everything is cached by the main uri, libraries are never directly cached
                   7302: #
1.428     albertel 7303:     if (!defined($liburi)) {
1.599     albertel 7304: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7305: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7306:     }
                   7307:     {
1.172     www      7308: #
                   7309: # Is this a recursive call for a library?
                   7310: #
1.599     albertel 7311: #	if (! exists($metacache{$uri})) {
                   7312: #	    $metacache{$uri}={};
                   7313: #	}
1.924     albertel 7314: 	my $cachetime = 60*60;
1.171     www      7315:         if ($liburi) {
                   7316: 	    $liburi=&declutter($liburi);
                   7317:             $filename=$liburi;
1.401     bowersj2 7318:         } else {
1.599     albertel 7319: 	    &devalidate_cache_new('meta',$uri);
                   7320: 	    undef(%metaentry);
1.401     bowersj2 7321: 	}
1.140     www      7322:         my %metathesekeys=();
1.73      www      7323:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7324: 	my $metastring;
1.924     albertel 7325: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7326: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7327: 	    $metastring = 
1.929     albertel 7328: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7329: 					  ('grade_target' => 'meta'));
                   7330: 	    $cachetime = 1; # only want this cached in the child not long term
                   7331: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7332: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7333: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7334: 	    $metastring=&getfile($file);
1.489     albertel 7335: 	}
1.208     albertel 7336:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7337:         my $token;
1.140     www      7338:         undef %metathesekeys;
1.71      www      7339:         while ($token=$parser->get_token) {
1.339     albertel 7340: 	    if ($token->[0] eq 'S') {
                   7341: 		if (defined($token->[2]->{'package'})) {
1.172     www      7342: #
                   7343: # This is a package - get package info
                   7344: #
1.339     albertel 7345: 		    my $package=$token->[2]->{'package'};
                   7346: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7347: 		    if (defined($token->[2]->{'id'})) { 
                   7348: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7349: 		    }
1.599     albertel 7350: 		    if ($metaentry{':packages'}) {
                   7351: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7352: 		    } else {
1.599     albertel 7353: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7354: 		    }
1.736     albertel 7355: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7356: 			my $part=$keyroot;
                   7357: 			$part=~s/^\_//;
1.736     albertel 7358: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7359: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7360: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7361: 			    # ignore package.tab specified default values
                   7362:                             # here &package_tab_default() will fetch those
                   7363: 			    if ($subp eq 'default') { next; }
1.736     albertel 7364: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7365: 			    my $unikey;
                   7366: 			    if ($pack =~ /_0$/) {
                   7367: 				$unikey='parameter_0_'.$name;
                   7368: 				$part=0;
                   7369: 			    } else {
                   7370: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7371: 			    }
1.339     albertel 7372: 			    if ($subp eq 'display') {
                   7373: 				$value.=' [Part: '.$part.']';
                   7374: 			    }
1.599     albertel 7375: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7376: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7377: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7378: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7379: 			    }
1.599     albertel 7380: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7381: 				$metaentry{':'.$unikey}=
                   7382: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7383: 			    }
1.339     albertel 7384: 			}
                   7385: 		    }
                   7386: 		} else {
1.172     www      7387: #
                   7388: # This is not a package - some other kind of start tag
1.339     albertel 7389: #
                   7390: 		    my $entry=$token->[1];
                   7391: 		    my $unikey;
                   7392: 		    if ($entry eq 'import') {
                   7393: 			$unikey='';
                   7394: 		    } else {
                   7395: 			$unikey=$entry;
                   7396: 		    }
                   7397: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7398: 
                   7399: 		    if (defined($token->[2]->{'id'})) { 
                   7400: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7401: 		    }
1.175     www      7402: 
1.339     albertel 7403: 		    if ($entry eq 'import') {
1.175     www      7404: #
                   7405: # Importing a library here
1.339     albertel 7406: #
                   7407: 			if ($depthcount<20) {
                   7408: 			    my $location=$parser->get_text('/import');
                   7409: 			    my $dir=$filename;
                   7410: 			    $dir=~s|[^/]*$||;
                   7411: 			    $location=&filelocation($dir,$location);
1.736     albertel 7412: 			    my $metadata = 
                   7413: 				&metadata($uri,'keys', $location,$unikey,
                   7414: 					  $depthcount+1);
                   7415: 			    foreach my $meta (split(',',$metadata)) {
                   7416: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7417: 				$metathesekeys{$meta}=1;
1.339     albertel 7418: 			    }
                   7419: 			}
                   7420: 		    } else { 
                   7421: 			
                   7422: 			if (defined($token->[2]->{'name'})) { 
                   7423: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7424: 			}
                   7425: 			$metathesekeys{$unikey}=1;
1.736     albertel 7426: 			foreach my $param (@{$token->[3]}) {
                   7427: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7428: 				$token->[2]->{$param};
1.339     albertel 7429: 			}
                   7430: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7431: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7432: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7433: 		 # only ws inside the tag, and not in default, so use default
                   7434: 		 # as value
1.599     albertel 7435: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7436: 			} elsif ( $internaltext =~ /\S/ ) {
                   7437: 		  # something interesting inside the tag
                   7438: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7439: 			} else {
1.908     albertel 7440: 		  # no interesting values, don't set a default
1.339     albertel 7441: 			}
1.172     www      7442: # end of not-a-package not-a-library import
1.339     albertel 7443: 		    }
1.172     www      7444: # end of not-a-package start tag
1.339     albertel 7445: 		}
1.172     www      7446: # the next is the end of "start tag"
1.339     albertel 7447: 	    }
                   7448: 	}
1.483     albertel 7449: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7450: 	$extension = lc($extension);
                   7451: 	if ($extension eq 'htm') { $extension='html'; }
                   7452: 
1.737     albertel 7453: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7454: 	    #no specific packages #how's our extension
                   7455: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7456: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7457: 					 \%metathesekeys);
                   7458: 	}
1.883     albertel 7459: 
                   7460: 	if (!exists($metaentry{':packages'})
                   7461: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7462: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7463: 		#no specific packages well let's get default then
                   7464: 		if ($key!~/^default&/) { next; }
1.488     albertel 7465: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7466: 					     \%metathesekeys);
                   7467: 	    }
                   7468: 	}
1.338     www      7469: # are there custom rights to evaluate
1.599     albertel 7470: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7471: 
1.338     www      7472:     #
                   7473:     # Importing a rights file here
1.339     albertel 7474:     #
                   7475: 	    unless ($depthcount) {
1.599     albertel 7476: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7477: 		my $dir=$filename;
                   7478: 		$dir=~s|[^/]*$||;
                   7479: 		$location=&filelocation($dir,$location);
1.736     albertel 7480: 		my $rights_metadata =
                   7481: 		    &metadata($uri,'keys',$location,'_rights',
                   7482: 			      $depthcount+1);
                   7483: 		foreach my $rights (split(',',$rights_metadata)) {
                   7484: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7485: 		    $metathesekeys{$rights}=1;
1.339     albertel 7486: 		}
                   7487: 	    }
                   7488: 	}
1.737     albertel 7489: 	# uniqifiy package listing
                   7490: 	my %seen;
                   7491: 	my @uniq_packages =
                   7492: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7493: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7494: 
                   7495: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7496: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7497: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7498: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7499: # this is the end of "was not already recently cached
1.71      www      7500:     }
1.599     albertel 7501:     return $metaentry{':'.$what};
1.261     albertel 7502: }
                   7503: 
1.488     albertel 7504: sub metadata_create_package_def {
1.483     albertel 7505:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7506:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7507:     if ($subp eq 'default') { next; }
                   7508:     
1.599     albertel 7509:     if (defined($metaentry{':packages'})) {
                   7510: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7511:     } else {
1.599     albertel 7512: 	$metaentry{':packages'}=$package;
1.483     albertel 7513:     }
                   7514:     my $value=$packagetab{$key};
                   7515:     my $unikey;
                   7516:     $unikey='parameter_0_'.$name;
1.599     albertel 7517:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7518:     $$metathesekeys{$unikey}=1;
1.599     albertel 7519:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7520: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7521:     }
1.599     albertel 7522:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7523: 	$metaentry{':'.$unikey}=
                   7524: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7525:     }
                   7526: }
                   7527: 
1.261     albertel 7528: sub metadata_generate_part0 {
                   7529:     my ($metadata,$metacache,$uri) = @_;
                   7530:     my %allnames;
1.737     albertel 7531:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7532: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7533: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7534: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7535: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7536: 	    $allnames{$name}=$part;
                   7537: 	  }
                   7538: 	}
                   7539:     }
                   7540:     foreach my $name (keys(%allnames)) {
                   7541:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7542:       my $key=":parameter_0_$name";
1.261     albertel 7543:       $$metacache{"$key.part"}='0';
                   7544:       $$metacache{"$key.name"}=$name;
1.428     albertel 7545:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7546: 					   $allnames{$name}.'_'.$name.
                   7547: 					   '.type'};
1.428     albertel 7548:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7549: 			     '.display'};
1.644     www      7550:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7551:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7552:       $$metacache{"$key.display"}=$olddis;
                   7553:     }
1.71      www      7554: }
                   7555: 
1.764     albertel 7556: # ------------------------------------------------------ Devalidate title cache
                   7557: 
                   7558: sub devalidate_title_cache {
                   7559:     my ($url)=@_;
                   7560:     if (!$env{'request.course.id'}) { return; }
                   7561:     my $symb=&symbread($url);
                   7562:     if (!$symb) { return; }
                   7563:     my $key=$env{'request.course.id'}."\0".$symb;
                   7564:     &devalidate_cache_new('title',$key);
                   7565: }
                   7566: 
1.301     www      7567: # ------------------------------------------------- Get the title of a resource
                   7568: 
                   7569: sub gettitle {
                   7570:     my $urlsymb=shift;
                   7571:     my $symb=&symbread($urlsymb);
1.534     albertel 7572:     if ($symb) {
1.620     albertel 7573: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7574: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7575: 	if (defined($cached)) { 
                   7576: 	    return $result;
                   7577: 	}
1.534     albertel 7578: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7579: 	my $title='';
1.907     albertel 7580: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7581: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7582: 	} else {
                   7583: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7584: 		    &GDBM_READER(),0640)) {
                   7585: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7586: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7587: 		untie(%bighash);
                   7588: 	    }
1.534     albertel 7589: 	}
                   7590: 	$title=~s/\&colon\;/\:/gs;
                   7591: 	if ($title) {
1.599     albertel 7592: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7593: 	}
                   7594: 	$urlsymb=$url;
                   7595:     }
                   7596:     my $title=&metadata($urlsymb,'title');
                   7597:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7598:     return $title;
1.301     www      7599: }
1.613     albertel 7600: 
1.614     albertel 7601: sub get_slot {
                   7602:     my ($which,$cnum,$cdom)=@_;
                   7603:     if (!$cnum || !$cdom) {
1.790     albertel 7604: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7605: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7606: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7607:     }
1.703     albertel 7608:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7609:     my %slotinfo;
                   7610:     if (exists($remembered{$key})) {
                   7611: 	$slotinfo{$which} = $remembered{$key};
                   7612:     } else {
                   7613: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7614: 	&Apache::lonhomework::showhash(%slotinfo);
                   7615: 	my ($tmp)=keys(%slotinfo);
                   7616: 	if ($tmp=~/^error:/) { return (); }
                   7617: 	$remembered{$key} = $slotinfo{$which};
                   7618:     }
1.616     albertel 7619:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7620: 	return %{$slotinfo{$which}};
                   7621:     }
                   7622:     return $slotinfo{$which};
1.614     albertel 7623: }
1.31      www      7624: # ------------------------------------------------- Update symbolic store links
                   7625: 
                   7626: sub symblist {
                   7627:     my ($mapname,%newhash)=@_;
1.438     www      7628:     $mapname=&deversion(&declutter($mapname));
1.31      www      7629:     my %hash;
1.620     albertel 7630:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7631:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7632:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7633: 	    foreach my $url (keys %newhash) {
                   7634: 		next if ($url eq 'last_known'
                   7635: 			 && $env{'form.no_update_last_known'});
                   7636: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7637: 						    $newhash{$url}->[1],
                   7638: 						    $newhash{$url}->[0]);
1.191     harris41 7639:             }
1.31      www      7640:             if (untie(%hash)) {
                   7641: 		return 'ok';
                   7642:             }
                   7643:         }
                   7644:     }
                   7645:     return 'error';
1.212     www      7646: }
                   7647: 
                   7648: # --------------------------------------------------------------- Verify a symb
                   7649: 
                   7650: sub symbverify {
1.510     www      7651:     my ($symb,$thisurl)=@_;
                   7652:     my $thisfn=$thisurl;
1.439     www      7653:     $thisfn=&declutter($thisfn);
1.215     www      7654: # direct jump to resource in page or to a sequence - will construct own symbs
                   7655:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7656: # check URL part
1.409     www      7657:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7658: 
1.431     www      7659:     unless ($url eq $thisfn) { return 0; }
1.213     www      7660: 
1.216     www      7661:     $symb=&symbclean($symb);
1.510     www      7662:     $thisurl=&deversion($thisurl);
1.439     www      7663:     $thisfn=&deversion($thisfn);
1.213     www      7664: 
                   7665:     my %bighash;
                   7666:     my $okay=0;
1.431     www      7667: 
1.620     albertel 7668:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7669:                             &GDBM_READER(),0640)) {
1.510     www      7670:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7671:         unless ($ids) { 
1.510     www      7672:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7673:         }
                   7674:         if ($ids) {
                   7675: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7676: 	    foreach my $id (split(/\,/,$ids)) {
                   7677: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7678:                if (
                   7679:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7680:    eq $symb) { 
1.620     albertel 7681: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7682: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7683: 		       $okay=1; 
                   7684: 		   }
                   7685: 	       }
1.216     www      7686: 	   }
                   7687:         }
1.213     www      7688: 	untie(%bighash);
                   7689:     }
                   7690:     return $okay;
1.31      www      7691: }
                   7692: 
1.210     www      7693: # --------------------------------------------------------------- Clean-up symb
                   7694: 
                   7695: sub symbclean {
                   7696:     my $symb=shift;
1.568     albertel 7697:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7698: # remove version from map
                   7699:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7700: 
1.210     www      7701: # remove version from URL
                   7702:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7703: 
1.507     www      7704: # remove wrapper
                   7705: 
1.510     www      7706:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7707:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7708:     return $symb;
1.409     www      7709: }
                   7710: 
                   7711: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7712: 
                   7713: sub encode_symb {
                   7714:     my ($map,$resid,$url)=@_;
                   7715:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7716: }
1.409     www      7717: 
                   7718: sub decode_symb {
1.568     albertel 7719:     my $symb=shift;
                   7720:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7721:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7722:     return (&fixversion($map),$resid,&fixversion($url));
                   7723: }
                   7724: 
                   7725: sub fixversion {
                   7726:     my $fn=shift;
1.609     banghart 7727:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7728:     my %bighash;
                   7729:     my $uri=&clutter($fn);
1.620     albertel 7730:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7731: # is this cached?
1.599     albertel 7732:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7733:     if (defined($cached)) { return $result; }
                   7734: # unfortunately not cached, or expired
1.620     albertel 7735:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7736: 	    &GDBM_READER(),0640)) {
                   7737:  	if ($bighash{'version_'.$uri}) {
                   7738:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7739:  	    unless (($version eq 'mostrecent') || 
                   7740: 		    ($version==&getversion($uri))) {
1.440     www      7741:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7742:  	    }
                   7743:  	}
                   7744:  	untie %bighash;
1.413     www      7745:     }
1.599     albertel 7746:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7747: }
                   7748: 
                   7749: sub deversion {
                   7750:     my $url=shift;
                   7751:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7752:     return $url;
1.210     www      7753: }
                   7754: 
1.31      www      7755: # ------------------------------------------------------ Return symb list entry
                   7756: 
                   7757: sub symbread {
1.249     www      7758:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7759:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7760:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7761: # no filename provided? try from environment
1.44      www      7762:     unless ($thisfn) {
1.620     albertel 7763:         if ($env{'request.symb'}) {
                   7764: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7765: 	}
1.620     albertel 7766: 	$thisfn=$env{'request.filename'};
1.44      www      7767:     }
1.569     albertel 7768:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7769: # is that filename actually a symb? Verify, clean, and return
                   7770:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7771: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7772: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7773: 	}
1.242     www      7774:     }
1.44      www      7775:     $thisfn=declutter($thisfn);
1.31      www      7776:     my %hash;
1.37      www      7777:     my %bighash;
                   7778:     my $syval='';
1.620     albertel 7779:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7780:         my $targetfn = $thisfn;
1.609     banghart 7781:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7782:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7783:         }
1.687     albertel 7784: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7785: 	    $targetfn=$1;
                   7786: 	}
1.620     albertel 7787:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7788:                       &GDBM_READER(),0640)) {
1.481     raeburn  7789: 	    $syval=$hash{$targetfn};
1.37      www      7790:             untie(%hash);
                   7791:         }
                   7792: # ---------------------------------------------------------- There was an entry
                   7793:         if ($syval) {
1.601     albertel 7794: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7795: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7796: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7797: 		    #return $env{$cache_str}='';
1.601     albertel 7798: 		#}    
                   7799: 		#$syval.=$1;
                   7800: 	    #}
1.37      www      7801:         } else {
                   7802: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7803:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7804:                             &GDBM_READER(),0640)) {
1.37      www      7805: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7806:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7807:               unless ($ids) { 
                   7808:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7809:               }
                   7810:               unless ($ids) {
                   7811: # alias?
                   7812: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7813:               }
1.37      www      7814:               if ($ids) {
                   7815: # ------------------------------------------------------------------- Has ID(s)
                   7816:                  my @possibilities=split(/\,/,$ids);
1.39      www      7817:                  if ($#possibilities==0) {
                   7818: # ----------------------------------------------- There is only one possibility
1.37      www      7819: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7820: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7821: 						    $resid,$thisfn);
1.249     www      7822:                  } elsif (!$donotrecurse) {
1.39      www      7823: # ------------------------------------------ There is more than one possibility
                   7824:                      my $realpossible=0;
1.800     albertel 7825:                      foreach my $id (@possibilities) {
                   7826: 			 my $file=$bighash{'src_'.$id};
1.39      www      7827:                          if (&allowed('bre',$file)) {
1.800     albertel 7828:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7829:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7830: 				$realpossible++;
1.626     albertel 7831:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7832: 						    $resid,$thisfn);
1.39      www      7833:                             }
                   7834: 			 }
1.191     harris41 7835:                      }
1.39      www      7836: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7837:                  } else {
                   7838:                      $syval='';
1.37      www      7839:                  }
                   7840: 	      }
                   7841:               untie(%bighash)
1.481     raeburn  7842:            }
1.31      www      7843:         }
1.62      www      7844:         if ($syval) {
1.620     albertel 7845: 	    return $env{$cache_str}=$syval;
1.62      www      7846:         }
1.31      www      7847:     }
1.949     raeburn  7848:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7849:     return $env{$cache_str}='';
1.31      www      7850: }
                   7851: 
                   7852: # ---------------------------------------------------------- Return random seed
                   7853: 
1.32      www      7854: sub numval {
                   7855:     my $txt=shift;
                   7856:     $txt=~tr/A-J/0-9/;
                   7857:     $txt=~tr/a-j/0-9/;
                   7858:     $txt=~tr/K-T/0-9/;
                   7859:     $txt=~tr/k-t/0-9/;
                   7860:     $txt=~tr/U-Z/0-5/;
                   7861:     $txt=~tr/u-z/0-5/;
                   7862:     $txt=~s/\D//g;
1.564     albertel 7863:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7864:     return int($txt);
1.368     albertel 7865: }
                   7866: 
1.484     albertel 7867: sub numval2 {
                   7868:     my $txt=shift;
                   7869:     $txt=~tr/A-J/0-9/;
                   7870:     $txt=~tr/a-j/0-9/;
                   7871:     $txt=~tr/K-T/0-9/;
                   7872:     $txt=~tr/k-t/0-9/;
                   7873:     $txt=~tr/U-Z/0-5/;
                   7874:     $txt=~tr/u-z/0-5/;
                   7875:     $txt=~s/\D//g;
                   7876:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7877:     my $total;
                   7878:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7879:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7880:     return int($total);
                   7881: }
                   7882: 
1.575     albertel 7883: sub numval3 {
                   7884:     use integer;
                   7885:     my $txt=shift;
                   7886:     $txt=~tr/A-J/0-9/;
                   7887:     $txt=~tr/a-j/0-9/;
                   7888:     $txt=~tr/K-T/0-9/;
                   7889:     $txt=~tr/k-t/0-9/;
                   7890:     $txt=~tr/U-Z/0-5/;
                   7891:     $txt=~tr/u-z/0-5/;
                   7892:     $txt=~s/\D//g;
                   7893:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7894:     my $total;
                   7895:     foreach my $val (@txts) { $total+=$val; }
                   7896:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7897:     return $total;
                   7898: }
                   7899: 
1.675     albertel 7900: sub digest {
                   7901:     my ($data)=@_;
                   7902:     my $digest=&Digest::MD5::md5($data);
                   7903:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7904:     my ($e,$f);
                   7905:     {
                   7906:         use integer;
                   7907:         $e=($a+$b);
                   7908:         $f=($c+$d);
                   7909:         if ($_64bit) {
                   7910:             $e=(($e<<32)>>32);
                   7911:             $f=(($f<<32)>>32);
                   7912:         }
                   7913:     }
                   7914:     if (wantarray) {
                   7915: 	return ($e,$f);
                   7916:     } else {
                   7917: 	my $g;
                   7918: 	{
                   7919: 	    use integer;
                   7920: 	    $g=($e+$f);
                   7921: 	    if ($_64bit) {
                   7922: 		$g=(($g<<32)>>32);
                   7923: 	    }
                   7924: 	}
                   7925: 	return $g;
                   7926:     }
                   7927: }
                   7928: 
1.368     albertel 7929: sub latest_rnd_algorithm_id {
1.675     albertel 7930:     return '64bit5';
1.366     albertel 7931: }
1.32      www      7932: 
1.503     albertel 7933: sub get_rand_alg {
                   7934:     my ($courseid)=@_;
1.790     albertel 7935:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7936:     if ($courseid) {
1.620     albertel 7937: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7938:     }
                   7939:     return &latest_rnd_algorithm_id();
                   7940: }
                   7941: 
1.562     albertel 7942: sub validCODE {
                   7943:     my ($CODE)=@_;
                   7944:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7945:     return 0;
                   7946: }
                   7947: 
1.491     albertel 7948: sub getCODE {
1.620     albertel 7949:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7950:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7951: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7952: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7953: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7954:     }
                   7955:     return undef;
                   7956: }
                   7957: 
1.31      www      7958: sub rndseed {
1.155     albertel 7959:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7960:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7961:     if (!defined($symb)) {
1.366     albertel 7962: 	unless ($symb=$wsymb) { return time; }
                   7963:     }
                   7964:     if (!$courseid) { $courseid=$wcourseid; }
                   7965:     if (!$domain) { $domain=$wdomain; }
                   7966:     if (!$username) { $username=$wusername }
1.503     albertel 7967:     my $which=&get_rand_alg();
1.803     albertel 7968: 
1.491     albertel 7969:     if (defined(&getCODE())) {
1.675     albertel 7970: 	if ($which eq '64bit5') {
                   7971: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7972: 	} elsif ($which eq '64bit4') {
1.575     albertel 7973: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7974: 	} else {
                   7975: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7976: 	}
1.675     albertel 7977:     } elsif ($which eq '64bit5') {
                   7978: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7979:     } elsif ($which eq '64bit4') {
                   7980: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7981:     } elsif ($which eq '64bit3') {
                   7982: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7983:     } elsif ($which eq '64bit2') {
                   7984: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7985:     } elsif ($which eq '64bit') {
                   7986: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7987:     }
                   7988:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7989: }
                   7990: 
                   7991: sub rndseed_32bit {
                   7992:     my ($symb,$courseid,$domain,$username)=@_;
                   7993:     {
                   7994: 	use integer;
                   7995: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7996: 	my $symbseed=numval($symb) << 22;
                   7997: 	my $namechck=unpack("%32C*",$username) << 17;
                   7998: 	my $nameseed=numval($username) << 12;
                   7999: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8000: 	my $courseseed=unpack("%32C*",$courseid);
                   8001: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8002: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8003: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8004: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8005: 	return $num;
                   8006:     }
                   8007: }
                   8008: 
                   8009: sub rndseed_64bit {
                   8010:     my ($symb,$courseid,$domain,$username)=@_;
                   8011:     {
                   8012: 	use integer;
                   8013: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8014: 	my $symbseed=numval($symb) << 10;
                   8015: 	my $namechck=unpack("%32S*",$username);
                   8016: 	
                   8017: 	my $nameseed=numval($username) << 21;
                   8018: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8019: 	my $courseseed=unpack("%32S*",$courseid);
                   8020: 	
                   8021: 	my $num1=$symbchck+$symbseed+$namechck;
                   8022: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8023: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8024: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8025: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8026: 	return "$num1,$num2";
1.155     albertel 8027:     }
1.366     albertel 8028: }
                   8029: 
1.443     albertel 8030: sub rndseed_64bit2 {
                   8031:     my ($symb,$courseid,$domain,$username)=@_;
                   8032:     {
                   8033: 	use integer;
                   8034: 	# strings need to be an even # of cahracters long, it it is odd the
                   8035:         # last characters gets thrown away
                   8036: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8037: 	my $symbseed=numval($symb) << 10;
                   8038: 	my $namechck=unpack("%32S*",$username.' ');
                   8039: 	
                   8040: 	my $nameseed=numval($username) << 21;
1.501     albertel 8041: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8042: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8043: 	
                   8044: 	my $num1=$symbchck+$symbseed+$namechck;
                   8045: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8046: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8047: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8048: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8049: 	return "$num1,$num2";
                   8050:     }
                   8051: }
                   8052: 
                   8053: sub rndseed_64bit3 {
                   8054:     my ($symb,$courseid,$domain,$username)=@_;
                   8055:     {
                   8056: 	use integer;
                   8057: 	# strings need to be an even # of cahracters long, it it is odd the
                   8058:         # last characters gets thrown away
                   8059: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8060: 	my $symbseed=numval2($symb) << 10;
                   8061: 	my $namechck=unpack("%32S*",$username.' ');
                   8062: 	
                   8063: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8064: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8065: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8066: 	
                   8067: 	my $num1=$symbchck+$symbseed+$namechck;
                   8068: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8069: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8070: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8071: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8072: 	
1.503     albertel 8073: 	return "$num1:$num2";
1.443     albertel 8074:     }
                   8075: }
                   8076: 
1.575     albertel 8077: sub rndseed_64bit4 {
                   8078:     my ($symb,$courseid,$domain,$username)=@_;
                   8079:     {
                   8080: 	use integer;
                   8081: 	# strings need to be an even # of cahracters long, it it is odd the
                   8082:         # last characters gets thrown away
                   8083: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8084: 	my $symbseed=numval3($symb) << 10;
                   8085: 	my $namechck=unpack("%32S*",$username.' ');
                   8086: 	
                   8087: 	my $nameseed=numval3($username) << 21;
                   8088: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8089: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8090: 	
                   8091: 	my $num1=$symbchck+$symbseed+$namechck;
                   8092: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8093: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8094: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8095: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8096: 	
                   8097: 	return "$num1:$num2";
                   8098:     }
                   8099: }
                   8100: 
1.675     albertel 8101: sub rndseed_64bit5 {
                   8102:     my ($symb,$courseid,$domain,$username)=@_;
                   8103:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8104:     return "$num1:$num2";
                   8105: }
                   8106: 
1.366     albertel 8107: sub rndseed_CODE_64bit {
                   8108:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8109:     {
1.366     albertel 8110: 	use integer;
1.443     albertel 8111: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8112: 	my $symbseed=numval2($symb);
1.491     albertel 8113: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8114: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8115: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8116: 	my $num1=$symbseed+$CODEchck;
                   8117: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8118: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8119: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8120: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8121: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8122: 	return "$num1:$num2";
1.366     albertel 8123:     }
                   8124: }
                   8125: 
1.575     albertel 8126: sub rndseed_CODE_64bit4 {
                   8127:     my ($symb,$courseid,$domain,$username)=@_;
                   8128:     {
                   8129: 	use integer;
                   8130: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8131: 	my $symbseed=numval3($symb);
                   8132: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8133: 	my $CODEseed=numval3(&getCODE());
                   8134: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8135: 	my $num1=$symbseed+$CODEchck;
                   8136: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8137: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8138: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8139: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8140: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8141: 	return "$num1:$num2";
                   8142:     }
                   8143: }
                   8144: 
1.675     albertel 8145: sub rndseed_CODE_64bit5 {
                   8146:     my ($symb,$courseid,$domain,$username)=@_;
                   8147:     my $code = &getCODE();
                   8148:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8149:     return "$num1:$num2";
                   8150: }
                   8151: 
1.366     albertel 8152: sub setup_random_from_rndseed {
                   8153:     my ($rndseed)=@_;
1.503     albertel 8154:     if ($rndseed =~/([,:])/) {
                   8155: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8156: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8157:     } else {
                   8158: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8159:     }
1.36      albertel 8160: }
                   8161: 
1.474     albertel 8162: sub latest_receipt_algorithm_id {
1.835     albertel 8163:     return 'receipt3';
1.474     albertel 8164: }
                   8165: 
1.480     www      8166: sub recunique {
                   8167:     my $fucourseid=shift;
                   8168:     my $unique;
1.835     albertel 8169:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8170: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8171: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8172:     } else {
                   8173: 	$unique=$perlvar{'lonReceipt'};
                   8174:     }
                   8175:     return unpack("%32C*",$unique);
                   8176: }
                   8177: 
                   8178: sub recprefix {
                   8179:     my $fucourseid=shift;
                   8180:     my $prefix;
1.835     albertel 8181:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8182: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8183: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8184:     } else {
                   8185: 	$prefix=$perlvar{'lonHostID'};
                   8186:     }
                   8187:     return unpack("%32C*",$prefix);
                   8188: }
                   8189: 
1.76      www      8190: sub ireceipt {
1.474     albertel 8191:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8192: 
                   8193:     my $return =&recprefix($fucourseid).'-';
                   8194: 
                   8195:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8196: 	$env{'request.state'} eq 'construct') {
                   8197: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8198: 	return $return;
                   8199:     }
                   8200: 
1.76      www      8201:     my $cuname=unpack("%32C*",$funame);
                   8202:     my $cudom=unpack("%32C*",$fudom);
                   8203:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8204:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8205:     my $cunique=&recunique($fucourseid);
1.474     albertel 8206:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8207:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8208: 
1.790     albertel 8209: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8210: 			       
                   8211: 	$return.= ($cunique%$cuname+
                   8212: 		   $cunique%$cudom+
                   8213: 		   $cusymb%$cuname+
                   8214: 		   $cusymb%$cudom+
                   8215: 		   $cucourseid%$cuname+
                   8216: 		   $cucourseid%$cudom+
                   8217: 		   $cpart%$cuname+
                   8218: 		   $cpart%$cudom);
                   8219:     } else {
                   8220: 	$return.= ($cunique%$cuname+
                   8221: 		   $cunique%$cudom+
                   8222: 		   $cusymb%$cuname+
                   8223: 		   $cusymb%$cudom+
                   8224: 		   $cucourseid%$cuname+
                   8225: 		   $cucourseid%$cudom);
                   8226:     }
                   8227:     return $return;
1.76      www      8228: }
                   8229: 
                   8230: sub receipt {
1.474     albertel 8231:     my ($part)=@_;
1.790     albertel 8232:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8233:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8234: }
1.260     ng       8235: 
1.790     albertel 8236: sub whichuser {
                   8237:     my ($passedsymb)=@_;
                   8238:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8239:     if (defined($env{'form.grade_symb'})) {
                   8240: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8241: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8242: 	if (!$allowed &&
                   8243: 	    exists($env{'request.course.sec'}) &&
                   8244: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8245: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8246: 			      '/'.$env{'request.course.sec'});
                   8247: 	}
                   8248: 	if ($allowed) {
                   8249: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8250: 	    $courseid=$tmp_courseid;
                   8251: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8252: 	    ($name)=&get_env_multiple('form.grade_username');
                   8253: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8254: 	}
                   8255:     }
                   8256:     if (!$passedsymb) {
                   8257: 	$symb=&symbread();
                   8258:     } else {
                   8259: 	$symb=$passedsymb;
                   8260:     }
                   8261:     $courseid=$env{'request.course.id'};
                   8262:     $domain=$env{'user.domain'};
                   8263:     $name=$env{'user.name'};
                   8264:     if ($name eq 'public' && $domain eq 'public') {
                   8265: 	if (!defined($env{'form.username'})) {
                   8266: 	    $env{'form.username'}.=time.rand(10000000);
                   8267: 	}
                   8268: 	$name.=$env{'form.username'};
                   8269:     }
                   8270:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8271: 
                   8272: }
                   8273: 
1.36      albertel 8274: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8275: # returns either the contents of the file or 
                   8276: # -1 if the file doesn't exist
1.481     raeburn  8277: #
                   8278: # if the target is a file that was uploaded via DOCS, 
                   8279: # a check will be made to see if a current copy exists on the local server,
                   8280: # if it does this will be served, otherwise a copy will be retrieved from
                   8281: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8282: # the local server.   
1.472     albertel 8283: 
1.36      albertel 8284: sub getfile {
1.538     albertel 8285:     my ($file) = @_;
1.609     banghart 8286:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8287:     &repcopy($file);
                   8288:     return &readfile($file);
                   8289: }
                   8290: 
                   8291: sub repcopy_userfile {
                   8292:     my ($file)=@_;
1.609     banghart 8293:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8294:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8295:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8296: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8297:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8298:     if (-e "$file") {
1.828     www      8299: # we already have a local copy, check it out
1.538     albertel 8300: 	my @fileinfo = stat($file);
1.828     www      8301: 	my $rtncode;
                   8302: 	my $info;
1.538     albertel 8303: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8304: 	if ($lwpresp ne 'ok') {
1.828     www      8305: # there is no such file anymore, even though we had a local copy
1.482     albertel 8306: 	    if ($rtncode eq '404') {
1.538     albertel 8307: 		unlink($file);
1.482     albertel 8308: 	    }
                   8309: 	    return -1;
                   8310: 	}
                   8311: 	if ($info < $fileinfo[9]) {
1.828     www      8312: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8313: 	    return 'ok';
1.828     www      8314: 	} else {
                   8315: # the file is outdated, get rid of it
                   8316: 	    unlink($file);
1.482     albertel 8317: 	}
1.828     www      8318:     }
                   8319: # one way or the other, at this point, we don't have the file
                   8320: # construct the correct path for the file
                   8321:     my @parts = ($cdom,$cnum); 
                   8322:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8323: 	push @parts, split(/\//,$1);
                   8324:     }
                   8325:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8326:     foreach my $part (@parts) {
                   8327: 	$path .= '/'.$part;
                   8328: 	if (!-e $path) {
                   8329: 	    mkdir($path,0770);
1.482     albertel 8330: 	}
                   8331:     }
1.828     www      8332: # now the path exists for sure
                   8333: # get a user agent
                   8334:     my $ua=new LWP::UserAgent;
                   8335:     my $transferfile=$file.'.in.transfer';
                   8336: # FIXME: this should flock
                   8337:     if (-e $transferfile) { return 'ok'; }
                   8338:     my $request;
                   8339:     $uri=~s/^\///;
1.838     albertel 8340:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8341:     my $response=$ua->request($request,$transferfile);
                   8342: # did it work?
                   8343:     if ($response->is_error()) {
                   8344: 	unlink($transferfile);
                   8345: 	&logthis("Userfile repcopy failed for $uri");
                   8346: 	return -1;
                   8347:     }
                   8348: # worked, rename the transfer file
                   8349:     rename($transferfile,$file);
1.607     raeburn  8350:     return 'ok';
1.481     raeburn  8351: }
                   8352: 
1.517     albertel 8353: sub tokenwrapper {
                   8354:     my $uri=shift;
1.552     albertel 8355:     $uri=~s|^http\://([^/]+)||;
                   8356:     $uri=~s|^/||;
1.620     albertel 8357:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8358:     my $token=$1;
1.552     albertel 8359:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8360:     if ($udom && $uname && $file) {
                   8361: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8362:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8363:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8364:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8365:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8366:     } else {
                   8367:         return '/adm/notfound.html';
                   8368:     }
                   8369: }
                   8370: 
1.828     www      8371: # call with reqtype HEAD: get last modification time
                   8372: # call with reqtype GET: get the file contents
                   8373: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8374: #
1.481     raeburn  8375: sub getuploaded {
                   8376:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8377:     $uri=~s/^\///;
1.838     albertel 8378:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8379:     my $ua=new LWP::UserAgent;
                   8380:     my $request=new HTTP::Request($reqtype,$uri);
                   8381:     my $response=$ua->request($request);
                   8382:     $$rtncode = $response->code;
1.482     albertel 8383:     if (! $response->is_success()) {
                   8384: 	return 'failed';
                   8385:     }      
                   8386:     if ($reqtype eq 'HEAD') {
1.486     www      8387: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8388:     } elsif ($reqtype eq 'GET') {
                   8389: 	$$info = $response->content;
1.472     albertel 8390:     }
1.482     albertel 8391:     return 'ok';
1.36      albertel 8392: }
                   8393: 
1.481     raeburn  8394: sub readfile {
                   8395:     my $file = shift;
                   8396:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8397:     my $fh;
                   8398:     open($fh,"<$file");
                   8399:     my $a='';
1.800     albertel 8400:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8401:     return $a;
                   8402: }
                   8403: 
1.36      albertel 8404: sub filelocation {
1.590     banghart 8405:     my ($dir,$file) = @_;
                   8406:     my $location;
                   8407:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8408: 
                   8409:     if ($file =~ m-^/adm/-) {
                   8410: 	$file=~s-^/adm/wrapper/-/-;
                   8411: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8412:     }
1.882     albertel 8413: 
1.590     banghart 8414:     if ($file=~m:^/~:) { # is a contruction space reference
                   8415:         $location = $file;
                   8416:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8417:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8418: 	# is a correct contruction space reference
                   8419:         $location = $file;
1.956     raeburn  8420:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8421:         $location = $file;
1.609     banghart 8422:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8423:         my ($udom,$uname,$filename)=
1.811     albertel 8424:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8425:         my $home=&homeserver($uname,$udom);
                   8426:         my $is_me=0;
                   8427:         my @ids=&current_machine_ids();
                   8428:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8429:         if ($is_me) {
1.955     raeburn  8430:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8431:         } else {
                   8432:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8433:   	      $udom.'/'.$uname.'/'.$filename;
                   8434:         }
1.882     albertel 8435:     } elsif ($file =~ m-^/adm/-) {
                   8436: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8437:     } else {
                   8438:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8439:         $file=~s:^/res/:/:;
                   8440:         if ( !( $file =~ m:^/:) ) {
                   8441:             $location = $dir. '/'.$file;
                   8442:         } else {
                   8443:             $location = '/home/httpd/html/res'.$file;
                   8444:         }
1.59      albertel 8445:     }
1.590     banghart 8446:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8447:     while ($location=~m{/\.\./}) {
                   8448: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8449: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8450: 	} else {
                   8451: 	    $location=~ s{/\.\./}{/}g;
                   8452: 	}
                   8453:     } #remove dir/..
1.590     banghart 8454:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8455:     return $location;
1.46      www      8456: }
1.36      albertel 8457: 
1.46      www      8458: sub hreflocation {
                   8459:     my ($dir,$file)=@_;
1.460     albertel 8460:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8461: 	$file=filelocation($dir,$file);
1.700     albertel 8462:     } elsif ($file=~m-^/adm/-) {
                   8463: 	$file=~s-^/adm/wrapper/-/-;
                   8464: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8465:     }
                   8466:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8467: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8468:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8469: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8470:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8471: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8472: 	    -/uploaded/$1/$2/-x;
1.46      www      8473:     }
1.913     albertel 8474:     if ($file=~ m{^/userfiles/}) {
                   8475: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8476:     }
1.462     albertel 8477:     return $file;
1.465     albertel 8478: }
                   8479: 
                   8480: sub current_machine_domains {
1.853     albertel 8481:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8482: }
                   8483: 
                   8484: sub machine_domains {
                   8485:     my ($hostname) = @_;
1.465     albertel 8486:     my @domains;
1.838     albertel 8487:     my %hostname = &all_hostnames();
1.465     albertel 8488:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8489: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8490: 	if ($hostname eq $name) {
1.844     albertel 8491: 	    push(@domains,&host_domain($id));
1.465     albertel 8492: 	}
                   8493:     }
                   8494:     return @domains;
                   8495: }
                   8496: 
                   8497: sub current_machine_ids {
1.853     albertel 8498:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8499: }
                   8500: 
                   8501: sub machine_ids {
                   8502:     my ($hostname) = @_;
                   8503:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8504:     my @ids;
1.888     albertel 8505:     my %name_to_host = &all_names();
1.889     albertel 8506:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8507: 	return @{ $name_to_host{$hostname} };
                   8508:     }
                   8509:     return;
1.31      www      8510: }
                   8511: 
1.824     raeburn  8512: sub additional_machine_domains {
                   8513:     my @domains;
                   8514:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8515:     while( my $line = <$fh>) {
                   8516:         $line =~ s/\s//g;
                   8517:         push(@domains,$line);
                   8518:     }
                   8519:     return @domains;
                   8520: }
                   8521: 
                   8522: sub default_login_domain {
                   8523:     my $domain = $perlvar{'lonDefDomain'};
                   8524:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8525:     foreach my $posdom (&current_machine_domains(),
                   8526:                         &additional_machine_domains()) {
                   8527:         if (lc($posdom) eq lc($testdomain)) {
                   8528:             $domain=$posdom;
                   8529:             last;
                   8530:         }
                   8531:     }
                   8532:     return $domain;
                   8533: }
                   8534: 
1.31      www      8535: # ------------------------------------------------------------- Declutters URLs
                   8536: 
                   8537: sub declutter {
                   8538:     my $thisfn=shift;
1.569     albertel 8539:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8540:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8541:     $thisfn=~s/^\///;
1.697     albertel 8542:     $thisfn=~s|^adm/wrapper/||;
                   8543:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8544:     $thisfn=~s/^res\///;
1.235     www      8545:     $thisfn=~s/\?.+$//;
1.268     www      8546:     return $thisfn;
                   8547: }
                   8548: 
                   8549: # ------------------------------------------------------------- Clutter up URLs
                   8550: 
                   8551: sub clutter {
                   8552:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8553:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8554: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8555:        $thisfn='/res'.$thisfn; 
                   8556:     }
1.694     albertel 8557:     if ($thisfn !~m|/adm|) {
1.695     albertel 8558: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8559: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8560: 	} else {
                   8561: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8562: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8563: 	    if ($embstyle eq 'ssi'
                   8564: 		|| ($embstyle eq 'hdn')
                   8565: 		|| ($embstyle eq 'rat')
                   8566: 		|| ($embstyle eq 'prv')
                   8567: 		|| ($embstyle eq 'ign')) {
                   8568: 		#do nothing with these
                   8569: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8570: 		|| ($embstyle eq 'emb')
                   8571: 		|| ($embstyle eq 'wrp')) {
                   8572: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8573: 	    } elsif ($embstyle eq 'unk'
                   8574: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8575: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8576: 	    } else {
1.718     www      8577: #		&logthis("Got a blank emb style");
1.695     albertel 8578: 	    }
1.694     albertel 8579: 	}
                   8580:     }
1.31      www      8581:     return $thisfn;
1.12      www      8582: }
                   8583: 
1.787     albertel 8584: sub clutter_with_no_wrapper {
                   8585:     my $uri = &clutter(shift);
                   8586:     if ($uri =~ m-^/adm/-) {
                   8587: 	$uri =~ s-^/adm/wrapper/-/-;
                   8588: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8589:     }
                   8590:     return $uri;
                   8591: }
                   8592: 
1.557     albertel 8593: sub freeze_escape {
                   8594:     my ($value)=@_;
                   8595:     if (ref($value)) {
                   8596: 	$value=&nfreeze($value);
                   8597: 	return '__FROZEN__'.&escape($value);
                   8598:     }
                   8599:     return &escape($value);
                   8600: }
                   8601: 
1.11      www      8602: 
1.557     albertel 8603: sub thaw_unescape {
                   8604:     my ($value)=@_;
                   8605:     if ($value =~ /^__FROZEN__/) {
                   8606: 	substr($value,0,10,undef);
                   8607: 	$value=&unescape($value);
                   8608: 	return &thaw($value);
                   8609:     }
                   8610:     return &unescape($value);
                   8611: }
                   8612: 
1.436     albertel 8613: sub correct_line_ends {
                   8614:     my ($result)=@_;
                   8615:     $$result =~s/\r\n/\n/mg;
                   8616:     $$result =~s/\r/\n/mg;
1.415     albertel 8617: }
1.1       albertel 8618: # ================================================================ Main Program
                   8619: 
1.184     www      8620: sub goodbye {
1.204     albertel 8621:    &logthis("Starting Shut down");
1.443     albertel 8622: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8623:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8624: #converted
1.599     albertel 8625: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8626:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8627: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8628: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8629: #1.1 only
1.870     albertel 8630: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8631: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8632: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8633: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8634:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8635:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8636:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8637:    &flushcourselogs();
                   8638:    &logthis("Shutting down");
                   8639: }
                   8640: 
1.852     albertel 8641: sub get_dns {
1.869     albertel 8642:     my ($url,$func,$ignore_cache) = @_;
                   8643:     if (!$ignore_cache) {
                   8644: 	my ($content,$cached)=
                   8645: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8646: 	if ($cached) {
                   8647: 	    &$func($content);
                   8648: 	    return;
                   8649: 	}
                   8650:     }
                   8651: 
                   8652:     my %alldns;
1.852     albertel 8653:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8654:     foreach my $dns (<$config>) {
                   8655: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8656: 	$alldns{$1} = 1;
                   8657:     }
                   8658:     while (%alldns) {
                   8659: 	my ($dns) = keys(%alldns);
                   8660: 	delete($alldns{$dns});
1.852     albertel 8661: 	my $ua=new LWP::UserAgent;
                   8662: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8663: 	my $response=$ua->request($request);
                   8664: 	next if ($response->is_error());
                   8665: 	my @content = split("\n",$response->content);
1.869     albertel 8666: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8667: 	&$func(\@content);
1.869     albertel 8668: 	return;
1.852     albertel 8669:     }
                   8670:     close($config);
1.871     albertel 8671:     my $which = (split('/',$url))[3];
                   8672:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8673:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8674:     my @content = <$config>;
                   8675:     &$func(\@content);
                   8676:     return;
1.852     albertel 8677: }
1.327     albertel 8678: # ------------------------------------------------------------ Read domain file
                   8679: {
1.852     albertel 8680:     my $loaded;
1.846     albertel 8681:     my %domain;
                   8682: 
1.852     albertel 8683:     sub parse_domain_tab {
                   8684: 	my ($lines) = @_;
                   8685: 	foreach my $line (@$lines) {
                   8686: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8687: 
1.846     albertel 8688: 	    chomp($line);
1.852     albertel 8689: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8690: 	    my %this_domain;
                   8691: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8692: 			       'lang_def', 'city', 'longi', 'lati',
                   8693: 			       'primary') {
                   8694: 		$this_domain{$field} = shift(@elements);
                   8695: 	    }
                   8696: 	    $domain{$name} = \%this_domain;
1.852     albertel 8697: 	}
                   8698:     }
1.864     albertel 8699: 
                   8700:     sub reset_domain_info {
                   8701: 	undef($loaded);
                   8702: 	undef(%domain);
                   8703:     }
                   8704: 
1.852     albertel 8705:     sub load_domain_tab {
1.869     albertel 8706: 	my ($ignore_cache) = @_;
                   8707: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8708: 	my $fh;
                   8709: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8710: 	    my @lines = <$fh>;
                   8711: 	    &parse_domain_tab(\@lines);
1.448     albertel 8712: 	}
1.852     albertel 8713: 	close($fh);
                   8714: 	$loaded = 1;
1.327     albertel 8715:     }
1.846     albertel 8716: 
                   8717:     sub domain {
1.852     albertel 8718: 	&load_domain_tab() if (!$loaded);
                   8719: 
1.846     albertel 8720: 	my ($name,$what) = @_;
                   8721: 	return if ( !exists($domain{$name}) );
                   8722: 
                   8723: 	if (!$what) {
                   8724: 	    return $domain{$name}{'description'};
                   8725: 	}
                   8726: 	return $domain{$name}{$what};
                   8727:     }
1.974     raeburn  8728: 
                   8729:     sub domain_info {
                   8730:         &load_domain_tab() if (!$loaded);
                   8731:         return %domain;
                   8732:     }
                   8733: 
1.327     albertel 8734: }
                   8735: 
                   8736: 
1.1       albertel 8737: # ------------------------------------------------------------- Read hosts file
                   8738: {
1.838     albertel 8739:     my %hostname;
1.844     albertel 8740:     my %hostdom;
1.845     albertel 8741:     my %libserv;
1.852     albertel 8742:     my $loaded;
1.888     albertel 8743:     my %name_to_host;
1.852     albertel 8744: 
                   8745:     sub parse_hosts_tab {
                   8746: 	my ($file) = @_;
                   8747: 	foreach my $configline (@$file) {
                   8748: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8749: 	    next if ($configline =~ /^\^/);
                   8750: 	    chomp($configline);
1.968     raeburn  8751: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8752: 	    $name=~s/\s//g;
                   8753: 	    if ($id && $domain && $role && $name) {
                   8754: 		$hostname{$id}=$name;
1.888     albertel 8755: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8756: 		$hostdom{$id}=$domain;
                   8757: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8758:                 if (defined($protocol)) {
                   8759:                     if ($protocol eq 'https') {
                   8760:                         $protocol{$id} = $protocol;
                   8761:                     } else {
                   8762:                         $protocol{$id} = 'http'; 
                   8763:                     }
1.968     raeburn  8764:                 } else {
1.969     raeburn  8765:                     $protocol{$id} = 'http';
1.968     raeburn  8766:                 }
1.852     albertel 8767: 	    }
                   8768: 	}
                   8769:     }
1.864     albertel 8770:     
                   8771:     sub reset_hosts_info {
1.897     albertel 8772: 	&purge_remembered();
1.864     albertel 8773: 	&reset_domain_info();
                   8774: 	&reset_hosts_ip_info();
1.892     albertel 8775: 	undef(%name_to_host);
1.864     albertel 8776: 	undef(%hostname);
                   8777: 	undef(%hostdom);
                   8778: 	undef(%libserv);
                   8779: 	undef($loaded);
                   8780:     }
1.1       albertel 8781: 
1.852     albertel 8782:     sub load_hosts_tab {
1.869     albertel 8783: 	my ($ignore_cache) = @_;
                   8784: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8785: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8786: 	my @config = <$config>;
                   8787: 	&parse_hosts_tab(\@config);
                   8788: 	close($config);
                   8789: 	$loaded=1;
1.1       albertel 8790:     }
1.852     albertel 8791: 
1.838     albertel 8792:     sub hostname {
1.852     albertel 8793: 	&load_hosts_tab() if (!$loaded);
                   8794: 
1.838     albertel 8795: 	my ($lonid) = @_;
                   8796: 	return $hostname{$lonid};
                   8797:     }
1.845     albertel 8798: 
1.838     albertel 8799:     sub all_hostnames {
1.852     albertel 8800: 	&load_hosts_tab() if (!$loaded);
                   8801: 
1.838     albertel 8802: 	return %hostname;
                   8803:     }
1.845     albertel 8804: 
1.888     albertel 8805:     sub all_names {
                   8806: 	&load_hosts_tab() if (!$loaded);
                   8807: 
                   8808: 	return %name_to_host;
                   8809:     }
                   8810: 
1.974     raeburn  8811:     sub all_host_domain {
                   8812:         &load_hosts_tab() if (!$loaded);
                   8813:         return %hostdom;
                   8814:     }
                   8815: 
1.845     albertel 8816:     sub is_library {
1.852     albertel 8817: 	&load_hosts_tab() if (!$loaded);
                   8818: 
1.845     albertel 8819: 	return exists($libserv{$_[0]});
                   8820:     }
                   8821: 
                   8822:     sub all_library {
1.852     albertel 8823: 	&load_hosts_tab() if (!$loaded);
                   8824: 
1.845     albertel 8825: 	return %libserv;
                   8826:     }
                   8827: 
1.841     albertel 8828:     sub get_servers {
1.852     albertel 8829: 	&load_hosts_tab() if (!$loaded);
                   8830: 
1.841     albertel 8831: 	my ($domain,$type) = @_;
                   8832: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8833: 	                                          : %hostname;
                   8834: 	my %result;
1.842     albertel 8835: 	if (ref($domain) eq 'ARRAY') {
                   8836: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8837: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8838: 		    $result{$host} = $hostname;
                   8839: 		}
                   8840: 	    }
                   8841: 	} else {
                   8842: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8843: 		if ($hostdom{$host} eq $domain) {
                   8844: 		    $result{$host} = $hostname;
                   8845: 		}
1.841     albertel 8846: 	    }
                   8847: 	}
                   8848: 	return %result;
                   8849:     }
1.845     albertel 8850: 
1.844     albertel 8851:     sub host_domain {
1.852     albertel 8852: 	&load_hosts_tab() if (!$loaded);
                   8853: 
1.844     albertel 8854: 	my ($lonid) = @_;
                   8855: 	return $hostdom{$lonid};
                   8856:     }
                   8857: 
1.841     albertel 8858:     sub all_domains {
1.852     albertel 8859: 	&load_hosts_tab() if (!$loaded);
                   8860: 
1.841     albertel 8861: 	my %seen;
                   8862: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8863: 	return @uniq;
                   8864:     }
1.1       albertel 8865: }
                   8866: 
1.847     albertel 8867: { 
                   8868:     my %iphost;
1.856     albertel 8869:     my %name_to_ip;
                   8870:     my %lonid_to_ip;
1.869     albertel 8871: 
1.847     albertel 8872:     sub get_hosts_from_ip {
                   8873: 	my ($ip) = @_;
                   8874: 	my %iphosts = &get_iphost();
                   8875: 	if (ref($iphosts{$ip})) {
                   8876: 	    return @{$iphosts{$ip}};
                   8877: 	}
                   8878: 	return;
1.839     albertel 8879:     }
1.864     albertel 8880:     
                   8881:     sub reset_hosts_ip_info {
                   8882: 	undef(%iphost);
                   8883: 	undef(%name_to_ip);
                   8884: 	undef(%lonid_to_ip);
                   8885:     }
1.856     albertel 8886: 
                   8887:     sub get_host_ip {
                   8888: 	my ($lonid) = @_;
                   8889: 	if (exists($lonid_to_ip{$lonid})) {
                   8890: 	    return $lonid_to_ip{$lonid};
                   8891: 	}
                   8892: 	my $name=&hostname($lonid);
                   8893:    	my $ip = gethostbyname($name);
                   8894: 	return if (!$ip || length($ip) ne 4);
                   8895: 	$ip=inet_ntoa($ip);
                   8896: 	$name_to_ip{$name}   = $ip;
                   8897: 	$lonid_to_ip{$lonid} = $ip;
                   8898: 	return $ip;
                   8899:     }
1.847     albertel 8900:     
                   8901:     sub get_iphost {
1.869     albertel 8902: 	my ($ignore_cache) = @_;
1.894     albertel 8903: 
1.869     albertel 8904: 	if (!$ignore_cache) {
                   8905: 	    if (%iphost) {
                   8906: 		return %iphost;
                   8907: 	    }
                   8908: 	    my ($ip_info,$cached)=
                   8909: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8910: 	    if ($cached) {
                   8911: 		%iphost      = %{$ip_info->[0]};
                   8912: 		%name_to_ip  = %{$ip_info->[1]};
                   8913: 		%lonid_to_ip = %{$ip_info->[2]};
                   8914: 		return %iphost;
                   8915: 	    }
                   8916: 	}
1.894     albertel 8917: 
                   8918: 	# get yesterday's info for fallback
                   8919: 	my %old_name_to_ip;
                   8920: 	my ($ip_info,$cached)=
                   8921: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8922: 	if ($cached) {
                   8923: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8924: 	}
                   8925: 
1.888     albertel 8926: 	my %name_to_host = &all_names();
                   8927: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8928: 	    my $ip;
                   8929: 	    if (!exists($name_to_ip{$name})) {
                   8930: 		$ip = gethostbyname($name);
                   8931: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8932: 		    if (defined($old_name_to_ip{$name})) {
                   8933: 			$ip = $old_name_to_ip{$name};
                   8934: 			&logthis("Can't find $name defaulting to old $ip");
                   8935: 		    } else {
                   8936: 			&logthis("Name $name no IP found");
                   8937: 			next;
                   8938: 		    }
                   8939: 		} else {
                   8940: 		    $ip=inet_ntoa($ip);
1.847     albertel 8941: 		}
                   8942: 		$name_to_ip{$name} = $ip;
                   8943: 	    } else {
                   8944: 		$ip = $name_to_ip{$name};
1.653     albertel 8945: 	    }
1.888     albertel 8946: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8947: 		$lonid_to_ip{$id} = $ip;
                   8948: 	    }
                   8949: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8950: 	}
1.869     albertel 8951: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8952: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8953: 				      48*60*60);
1.869     albertel 8954: 
1.847     albertel 8955: 	return %iphost;
1.598     albertel 8956:     }
                   8957: }
                   8958: 
1.862     albertel 8959: BEGIN {
                   8960: 
                   8961: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8962:     unless ($readit) {
                   8963: {
                   8964:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8965:     %perlvar = (%perlvar,%{$configvars});
                   8966: }
                   8967: 
                   8968: 
1.1       albertel 8969: # ------------------------------------------------------ Read spare server file
                   8970: {
1.448     albertel 8971:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8972: 
                   8973:     while (my $configline=<$config>) {
                   8974:        chomp($configline);
1.284     matthew  8975:        if ($configline) {
1.784     albertel 8976: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8977: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8978: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8979:        }
                   8980:     }
1.448     albertel 8981:     close($config);
1.1       albertel 8982: }
1.11      www      8983: # ------------------------------------------------------------ Read permissions
                   8984: {
1.448     albertel 8985:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8986: 
                   8987:     while (my $configline=<$config>) {
1.448     albertel 8988: 	chomp($configline);
                   8989: 	if ($configline) {
                   8990: 	    my ($role,$perm)=split(/ /,$configline);
                   8991: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8992: 	}
1.11      www      8993:     }
1.448     albertel 8994:     close($config);
1.11      www      8995: }
                   8996: 
                   8997: # -------------------------------------------- Read plain texts for permissions
                   8998: {
1.448     albertel 8999:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9000: 
                   9001:     while (my $configline=<$config>) {
1.448     albertel 9002: 	chomp($configline);
                   9003: 	if ($configline) {
1.742     raeburn  9004: 	    my ($short,@plain)=split(/:/,$configline);
                   9005:             %{$prp{$short}} = ();
                   9006: 	    if (@plain > 0) {
                   9007:                 $prp{$short}{'std'} = $plain[0];
                   9008:                 for (my $i=1; $i<@plain; $i++) {
                   9009:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9010:                 }
                   9011:             }
1.448     albertel 9012: 	}
1.135     www      9013:     }
1.448     albertel 9014:     close($config);
1.135     www      9015: }
                   9016: 
                   9017: # ---------------------------------------------------------- Read package table
                   9018: {
1.448     albertel 9019:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9020: 
                   9021:     while (my $configline=<$config>) {
1.483     albertel 9022: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9023: 	chomp($configline);
                   9024: 	my ($short,$plain)=split(/:/,$configline);
                   9025: 	my ($pack,$name)=split(/\&/,$short);
                   9026: 	if ($plain ne '') {
                   9027: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9028: 	    $packagetab{$short}=$plain; 
                   9029: 	}
1.11      www      9030:     }
1.448     albertel 9031:     close($config);
1.329     matthew  9032: }
                   9033: 
                   9034: # ------------- set up temporary directory
                   9035: {
                   9036:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9037: 
1.11      www      9038: }
                   9039: 
1.794     albertel 9040: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9041: 				'compress_threshold'=> 20_000,
                   9042:  			        });
1.185     www      9043: 
1.281     www      9044: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9045: $dumpcount=0;
1.958     www      9046: $locknum=0;
1.22      www      9047: 
1.163     harris41 9048: &logtouch();
1.672     albertel 9049: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9050: $readit=1;
1.564     albertel 9051:     {
                   9052: 	use integer;
                   9053: 	my $test=(2**32)+1;
1.568     albertel 9054: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9055: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9056:     }
1.195     www      9057: }
1.1       albertel 9058: }
1.179     www      9059: 
1.1       albertel 9060: 1;
1.191     harris41 9061: __END__
                   9062: 
1.243     albertel 9063: =pod
                   9064: 
1.191     harris41 9065: =head1 NAME
                   9066: 
1.243     albertel 9067: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9068: 
                   9069: =head1 SYNOPSIS
                   9070: 
1.243     albertel 9071: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9072: 
                   9073:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9074: 
1.243     albertel 9075: Common parameters:
                   9076: 
                   9077: =over 4
                   9078: 
                   9079: =item *
                   9080: 
                   9081: $uname : an internal username (if $cname expecting a course Id specifically)
                   9082: 
                   9083: =item *
                   9084: 
                   9085: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9086: 
                   9087: =item *
                   9088: 
                   9089: $symb : a resource instance identifier
                   9090: 
                   9091: =item *
                   9092: 
                   9093: $namespace : the name of a .db file that contains the data needed or
                   9094: being set.
                   9095: 
                   9096: =back
                   9097: 
1.394     bowersj2 9098: =head1 OVERVIEW
1.191     harris41 9099: 
1.394     bowersj2 9100: lonnet provides subroutines which interact with the
                   9101: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9102: about classes, users, and resources.
1.243     albertel 9103: 
                   9104: For many of these objects you can also use this to store data about
                   9105: them or modify them in various ways.
1.191     harris41 9106: 
1.394     bowersj2 9107: =head2 Symbs
1.191     harris41 9108: 
1.394     bowersj2 9109: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9110: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9111: map, the resource number of the resource in the map, and the URL of
                   9112: the resource itself. The latter is somewhat redundant, but might help
                   9113: if maps change.
                   9114: 
                   9115: An example is
                   9116: 
                   9117:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9118: 
                   9119: The respective map entry is
                   9120: 
                   9121:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9122:   title="Problem 2">
                   9123:  </resource>
                   9124: 
                   9125: Symbs are used by the random number generator, as well as to store and
                   9126: restore data specific to a certain instance of for example a problem.
                   9127: 
                   9128: =head2 Storing And Retrieving Data
                   9129: 
                   9130: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9131: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9132: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9133: is is the non-critical message twin of cstore. These functions are for
                   9134: handlers to store a perl hash to a user's permanent data space in an
                   9135: easy manner, and to retrieve it again on another call. It is expected
                   9136: that a handler would use this once at the beginning to retrieve data,
                   9137: and then again once at the end to send only the new data back.
                   9138: 
                   9139: The data is stored in the user's data directory on the user's
                   9140: homeserver under the ID of the course.
                   9141: 
                   9142: The hash that is returned by restore will have all of the previous
                   9143: value for all of the elements of the hash.
                   9144: 
                   9145: Example:
                   9146: 
                   9147:  #creating a hash
                   9148:  my %hash;
                   9149:  $hash{'foo'}='bar';
                   9150: 
                   9151:  #storing it
                   9152:  &Apache::lonnet::cstore(\%hash);
                   9153: 
                   9154:  #changing a value
                   9155:  $hash{'foo'}='notbar';
                   9156: 
                   9157:  #adding a new value
                   9158:  $hash{'bar'}='foo';
                   9159:  &Apache::lonnet::cstore(\%hash);
                   9160: 
                   9161:  #retrieving the hash
                   9162:  my %history=&Apache::lonnet::restore();
                   9163: 
                   9164:  #print the hash
                   9165:  foreach my $key (sort(keys(%history))) {
                   9166:    print("\%history{$key} = $history{$key}");
                   9167:  }
                   9168: 
                   9169: Will print out:
1.191     harris41 9170: 
1.394     bowersj2 9171:  %history{1:foo} = bar
                   9172:  %history{1:keys} = foo:timestamp
                   9173:  %history{1:timestamp} = 990455579
                   9174:  %history{2:bar} = foo
                   9175:  %history{2:foo} = notbar
                   9176:  %history{2:keys} = foo:bar:timestamp
                   9177:  %history{2:timestamp} = 990455580
                   9178:  %history{bar} = foo
                   9179:  %history{foo} = notbar
                   9180:  %history{timestamp} = 990455580
                   9181:  %history{version} = 2
                   9182: 
                   9183: Note that the special hash entries C<keys>, C<version> and
                   9184: C<timestamp> were added to the hash. C<version> will be equal to the
                   9185: total number of versions of the data that have been stored. The
                   9186: C<timestamp> attribute will be the UNIX time the hash was
                   9187: stored. C<keys> is available in every historical section to list which
                   9188: keys were added or changed at a specific historical revision of a
                   9189: hash.
                   9190: 
                   9191: B<Warning>: do not store the hash that restore returns directly. This
                   9192: will cause a mess since it will restore the historical keys as if the
                   9193: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9194: 
1.394     bowersj2 9195: Calling convention:
1.191     harris41 9196: 
1.394     bowersj2 9197:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9198:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9199: 
1.394     bowersj2 9200: For more detailed information, see lonnet specific documentation.
1.191     harris41 9201: 
1.394     bowersj2 9202: =head1 RETURN MESSAGES
1.191     harris41 9203: 
1.394     bowersj2 9204: =over 4
1.191     harris41 9205: 
1.394     bowersj2 9206: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9207: 
1.394     bowersj2 9208: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9209: when the connection is brought back up
1.191     harris41 9210: 
1.394     bowersj2 9211: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9212: for later delivery
1.191     harris41 9213: 
1.967     bisitz   9214: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9215: 
1.394     bowersj2 9216: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9217: that was requested
1.191     harris41 9218: 
1.243     albertel 9219: =back
1.191     harris41 9220: 
1.243     albertel 9221: =head1 PUBLIC SUBROUTINES
1.191     harris41 9222: 
1.243     albertel 9223: =head2 Session Environment Functions
1.191     harris41 9224: 
1.243     albertel 9225: =over 4
1.191     harris41 9226: 
1.394     bowersj2 9227: =item * 
                   9228: X<appenv()>
1.949     raeburn  9229: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9230: the user envirnoment file, and will be restored for each access this
1.620     albertel 9231: user makes during this session, also modifies the %env for the current
1.949     raeburn  9232: process. Optional rolesarrayref - if defined contains a reference to an array
                   9233: of roles which are exempt from the restriction on modifying user.role entries 
                   9234: in the user's environment.db and in %env.    
1.191     harris41 9235: 
                   9236: =item *
1.394     bowersj2 9237: X<delenv()>
                   9238: B<delenv($regexp)>: removes all items from the session
                   9239: environment file that matches the regular expression in $regexp. The
1.620     albertel 9240: values are also delted from the current processes %env.
1.191     harris41 9241: 
1.795     albertel 9242: =item * get_env_multiple($name) 
                   9243: 
                   9244: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9245: values may be defined and end up as an array ref.
                   9246: 
                   9247: returns an array of values
                   9248: 
1.243     albertel 9249: =back
                   9250: 
                   9251: =head2 User Information
1.191     harris41 9252: 
1.243     albertel 9253: =over 4
1.191     harris41 9254: 
                   9255: =item *
1.394     bowersj2 9256: X<queryauthenticate()>
                   9257: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9258: authentication scheme
                   9259: 
                   9260: =item *
1.394     bowersj2 9261: X<authenticate()>
                   9262: B<authenticate($uname,$upass,$udom)>: try to
                   9263: authenticate user from domain's lib servers (first use the current
                   9264: one). C<$upass> should be the users password.
1.191     harris41 9265: 
                   9266: =item *
1.394     bowersj2 9267: X<homeserver()>
                   9268: B<homeserver($uname,$udom)>: find the server which has
                   9269: the user's directory and files (there must be only one), this caches
                   9270: the answer, and also caches if there is a borken connection.
1.191     harris41 9271: 
                   9272: =item *
1.394     bowersj2 9273: X<idget()>
                   9274: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9275: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9276: username, and only 1 username per ID in a specific domain) (returns
                   9277: hash: id=>name,id=>name)
1.191     harris41 9278: 
                   9279: =item *
1.394     bowersj2 9280: X<idrget()>
                   9281: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9282: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9283: 
                   9284: =item *
1.394     bowersj2 9285: X<idput()>
                   9286: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9287: 
                   9288: =item *
1.394     bowersj2 9289: X<rolesinit()>
                   9290: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9291: 
                   9292: =item *
1.551     albertel 9293: X<getsection()>
                   9294: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9295: course $cname, return section name/number or '' for "not in course"
                   9296: and '-1' for "no section"
                   9297: 
                   9298: =item *
1.394     bowersj2 9299: X<userenvironment()>
                   9300: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9301: passed in @what from the requested user's environment, returns a hash
                   9302: 
1.858     raeburn  9303: =item * 
                   9304: X<userlog_query()>
1.859     albertel 9305: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9306: activity.log file. %filters defines filters applied when parsing the
                   9307: log file. These can be start or end timestamps, or the type of action
                   9308: - log to look for Login or Logout events, check for Checkin or
                   9309: Checkout, role for role selection. The response is in the form
                   9310: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9311: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9312: 
1.243     albertel 9313: =back
                   9314: 
                   9315: =head2 User Roles
                   9316: 
                   9317: =over 4
                   9318: 
                   9319: =item *
                   9320: 
1.810     raeburn  9321: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9322:  F: full access
                   9323:  U,I,K: authentication modes (cxx only)
                   9324:  '': forbidden
                   9325:  1: user needs to choose course
                   9326:  2: browse allowed
1.766     albertel 9327:  A: passphrase authentication needed
1.243     albertel 9328: 
                   9329: =item *
                   9330: 
                   9331: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9332: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9333: and course level
                   9334: 
                   9335: =item *
                   9336: 
                   9337: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9338: explanation of a user role term
                   9339: 
1.832     raeburn  9340: =item *
                   9341: 
1.935     raeburn  9342: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9343: All arguments are optional. Returns a hash of a roles, either for
                   9344: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9345: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9346: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9347: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9348: For each key, value is set to colon-separated start and end times for
                   9349: the role.  If no username and domain are specified, will default to
1.934     raeburn  9350: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9351: of role statuses (active, future or previous), roles 
                   9352: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9353: to restrict the list of roles reported. If no array ref is 
                   9354: provided for types, will default to return only active roles.
1.834     albertel 9355: 
1.243     albertel 9356: =back
                   9357: 
                   9358: =head2 User Modification
                   9359: 
                   9360: =over 4
                   9361: 
                   9362: =item *
                   9363: 
1.957     raeburn  9364: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9365: user for the level given by URL.  Optional start and end dates (leave empty
                   9366: string or zero for "no date")
1.191     harris41 9367: 
                   9368: =item *
                   9369: 
1.243     albertel 9370: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9371: change a users, password, possible return values are: ok,
                   9372: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9373: refused
1.191     harris41 9374: 
                   9375: =item *
                   9376: 
1.243     albertel 9377: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9378: 
                   9379: =item *
                   9380: 
1.963     raeburn  9381: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9382:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9383: modify user
1.191     harris41 9384: 
                   9385: =item *
                   9386: 
1.286     matthew  9387: modifystudent
                   9388: 
1.957     raeburn  9389: modify a student's enrollment and identification information.
1.286     matthew  9390: The course id is resolved based on the current users environment.  
                   9391: This means the envoking user must be a course coordinator or otherwise
                   9392: associated with a course.
                   9393: 
1.297     matthew  9394: This call is essentially a wrapper for lonnet::modifyuser and
                   9395: lonnet::modify_student_enrollment
1.286     matthew  9396: 
                   9397: Inputs: 
                   9398: 
                   9399: =over 4
                   9400: 
1.957     raeburn  9401: =item B<$udom> Student's loncapa domain
1.286     matthew  9402: 
1.957     raeburn  9403: =item B<$uname> Student's loncapa login name
1.286     matthew  9404: 
1.964     bisitz   9405: =item B<$uid> Student/Employee ID
1.286     matthew  9406: 
1.957     raeburn  9407: =item B<$umode> Student's authentication mode
1.286     matthew  9408: 
1.957     raeburn  9409: =item B<$upass> Student's password
1.286     matthew  9410: 
1.957     raeburn  9411: =item B<$first> Student's first name
1.286     matthew  9412: 
1.957     raeburn  9413: =item B<$middle> Student's middle name
1.286     matthew  9414: 
1.957     raeburn  9415: =item B<$last> Student's last name
1.286     matthew  9416: 
1.957     raeburn  9417: =item B<$gene> Student's generation
1.286     matthew  9418: 
1.957     raeburn  9419: =item B<$usec> Student's section in course
1.286     matthew  9420: 
                   9421: =item B<$end> Unix time of the roles expiration
                   9422: 
                   9423: =item B<$start> Unix time of the roles start date
                   9424: 
                   9425: =item B<$forceid> If defined, allow $uid to be changed
                   9426: 
                   9427: =item B<$desiredhome> server to use as home server for student
                   9428: 
1.957     raeburn  9429: =item B<$email> Student's permanent e-mail address
                   9430: 
                   9431: =item B<$type> Type of enrollment (auto or manual)
                   9432: 
1.963     raeburn  9433: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9434: 
                   9435: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9436: 
1.963     raeburn  9437: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9438: 
1.963     raeburn  9439: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9440: 
1.963     raeburn  9441: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9442: 
1.286     matthew  9443: =back
1.297     matthew  9444: 
                   9445: =item *
                   9446: 
                   9447: modify_student_enrollment
                   9448: 
                   9449: Change a students enrollment status in a class.  The environment variable
                   9450: 'role.request.course' must be defined for this function to proceed.
                   9451: 
                   9452: Inputs:
                   9453: 
                   9454: =over 4
                   9455: 
                   9456: =item $udom, students domain
                   9457: 
                   9458: =item $uname, students name
                   9459: 
                   9460: =item $uid, students user id
                   9461: 
                   9462: =item $first, students first name
                   9463: 
                   9464: =item $middle
                   9465: 
                   9466: =item $last
                   9467: 
                   9468: =item $gene
                   9469: 
                   9470: =item $usec
                   9471: 
                   9472: =item $end
                   9473: 
                   9474: =item $start
                   9475: 
1.957     raeburn  9476: =item $type
                   9477: 
                   9478: =item $locktype
                   9479: 
                   9480: =item $cid
                   9481: 
                   9482: =item $selfenroll
                   9483: 
                   9484: =item $context
                   9485: 
1.297     matthew  9486: =back
                   9487: 
1.191     harris41 9488: 
                   9489: =item *
                   9490: 
1.243     albertel 9491: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9492: custom role; give a custom role to a user for the level given by URL.  Specify
                   9493: name and domain of role author, and role name
1.191     harris41 9494: 
                   9495: =item *
                   9496: 
1.243     albertel 9497: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9498: 
                   9499: =item *
                   9500: 
1.243     albertel 9501: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9502: 
                   9503: =back
                   9504: 
                   9505: =head2 Course Infomation
                   9506: 
                   9507: =over 4
1.191     harris41 9508: 
                   9509: =item *
                   9510: 
1.631     albertel 9511: coursedescription($courseid) : returns a hash of information about the
                   9512: specified course id, including all environment settings for the
                   9513: course, the description of the course will be in the hash under the
                   9514: key 'description'
1.191     harris41 9515: 
                   9516: =item *
                   9517: 
1.624     albertel 9518: resdata($name,$domain,$type,@which) : request for current parameter
                   9519: setting for a specific $type, where $type is either 'course' or 'user',
                   9520: @what should be a list of parameters to ask about. This routine caches
                   9521: answers for 5 minutes.
1.243     albertel 9522: 
1.877     foxr     9523: =item *
                   9524: 
                   9525: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9526: data base, returning a hash that is keyed by the resource name and has
                   9527: values that are the resource value.  I believe that the timestamps and
                   9528: versions are also returned.
                   9529: 
                   9530: 
1.243     albertel 9531: =back
                   9532: 
                   9533: =head2 Course Modification
                   9534: 
                   9535: =over 4
1.191     harris41 9536: 
                   9537: =item *
                   9538: 
1.243     albertel 9539: writecoursepref($courseid,%prefs) : write preferences (environment
                   9540: database) for a course
1.191     harris41 9541: 
                   9542: =item *
                   9543: 
1.243     albertel 9544: createcourse($udom,$description,$url) : make/modify course
                   9545: 
                   9546: =back
                   9547: 
                   9548: =head2 Resource Subroutines
                   9549: 
                   9550: =over 4
1.191     harris41 9551: 
                   9552: =item *
                   9553: 
1.243     albertel 9554: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9555: 
                   9556: =item *
                   9557: 
1.243     albertel 9558: repcopy($filename) : subscribes to the requested file, and attempts to
                   9559: replicate from the owning library server, Might return
1.607     raeburn  9560: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9561: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9562: resource. Expects the local filesystem pathname
                   9563: (/home/httpd/html/res/....)
                   9564: 
                   9565: =back
                   9566: 
                   9567: =head2 Resource Information
                   9568: 
                   9569: =over 4
1.191     harris41 9570: 
                   9571: =item *
                   9572: 
1.243     albertel 9573: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9574: a vairety of different possible values, $varname should be a request
                   9575: string, and the other parameters can be used to specify who and what
                   9576: one is asking about.
                   9577: 
                   9578: Possible values for $varname are environment.lastname (or other item
                   9579: from the envirnment hash), user.name (or someother aspect about the
                   9580: user), resource.0.maxtries (or some other part and parameter of a
                   9581: resource)
1.204     albertel 9582: 
                   9583: =item *
                   9584: 
1.243     albertel 9585: directcondval($number) : get current value of a condition; reads from a state
                   9586: string
1.204     albertel 9587: 
                   9588: =item *
                   9589: 
1.243     albertel 9590: condval($condidx) : value of condition index based on state
1.204     albertel 9591: 
                   9592: =item *
                   9593: 
1.243     albertel 9594: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9595: resource's metadata, $what should be either a specific key, or either
                   9596: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9597: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9598: 
                   9599: this function automatically caches all requests
1.191     harris41 9600: 
                   9601: =item *
                   9602: 
1.243     albertel 9603: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9604: network of library servers; returns file handle of where SQL and regex results
                   9605: will be stored for query
1.191     harris41 9606: 
                   9607: =item *
                   9608: 
1.243     albertel 9609: symbread($filename) : return symbolic list entry (filename argument optional);
                   9610: returns the data handle
1.191     harris41 9611: 
                   9612: =item *
                   9613: 
1.243     albertel 9614: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9615: a possible symb for the URL in $thisfn, and if is an encryypted
                   9616: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9617: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9618: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9619: 
1.191     harris41 9620: 
                   9621: =item *
                   9622: 
1.243     albertel 9623: symbclean($symb) : removes versions numbers from a symb, returns the
                   9624: cleaned symb
1.191     harris41 9625: 
                   9626: =item *
                   9627: 
1.243     albertel 9628: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9629: course map, user must be in a course for it to work.
1.191     harris41 9630: 
                   9631: =item *
                   9632: 
1.243     albertel 9633: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9634: 
                   9635: =item *
                   9636: 
1.243     albertel 9637: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9638: a random seed, all arguments are optional, if they aren't sent it uses the
                   9639: environment to derive them. Note: if symb isn't sent and it can't get one
                   9640: from &symbread it will use the current time as its return value
1.191     harris41 9641: 
                   9642: =item *
                   9643: 
1.243     albertel 9644: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9645: unfakeable, receipt
1.191     harris41 9646: 
                   9647: =item *
                   9648: 
1.620     albertel 9649: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9650: 
                   9651: =item *
                   9652: 
1.243     albertel 9653: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9654: 
                   9655: =item *
                   9656: 
1.243     albertel 9657: 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 9658: 
                   9659: =item *
                   9660: 
1.243     albertel 9661: 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 9662: 
                   9663: =item *
                   9664: 
1.243     albertel 9665: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9666: 
                   9667: =item *
                   9668: 
1.243     albertel 9669: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9670: forcing spreadsheet to reevaluate the resource scores next time.
                   9671: 
                   9672: =back
                   9673: 
                   9674: =head2 Storing/Retreiving Data
                   9675: 
                   9676: =over 4
1.191     harris41 9677: 
                   9678: =item *
                   9679: 
1.243     albertel 9680: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9681: for this url; hashref needs to be given and should be a \%hashname; the
                   9682: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9683: be derived from the env
1.191     harris41 9684: 
                   9685: =item *
                   9686: 
1.243     albertel 9687: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9688: uses critical subroutine
1.191     harris41 9689: 
                   9690: =item *
                   9691: 
1.243     albertel 9692: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9693: all args are optional
1.191     harris41 9694: 
                   9695: =item *
                   9696: 
1.717     albertel 9697: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9698: dumps the complete (or key matching regexp) namespace into a hash
                   9699: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9700: normally &store()ed into
                   9701: 
                   9702: $range should be either an integer '100' (give me the first 100
                   9703:                                            matching records)
                   9704:               or be  two integers sperated by a - with no spaces
                   9705:                  '30-50' (give me the 30th through the 50th matching
                   9706:                           records)
                   9707: 
                   9708: 
                   9709: =item *
                   9710: 
                   9711: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9712: replaces a &store() version of data with a replacement set of data
                   9713: for a particular resource in a namespace passed in the $storehash hash 
                   9714: reference
                   9715: 
                   9716: =item *
                   9717: 
1.243     albertel 9718: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9719: works very similar to store/cstore, but all data is stored in a
                   9720: temporary location and can be reset using tmpreset, $storehash should
                   9721: be a hash reference, returns nothing on success
1.191     harris41 9722: 
                   9723: =item *
                   9724: 
1.243     albertel 9725: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9726: similar to restore, but all data is stored in a temporary location and
                   9727: can be reset using tmpreset. Returns a hash of values on success,
                   9728: error string otherwise.
1.191     harris41 9729: 
                   9730: =item *
                   9731: 
1.243     albertel 9732: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9733: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9734: 
                   9735: =item *
                   9736: 
1.243     albertel 9737: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9738: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9739: 
                   9740: =item *
                   9741: 
1.243     albertel 9742: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9743: namesp ($udom and $uname are optional)
1.191     harris41 9744: 
                   9745: =item *
                   9746: 
1.702     albertel 9747: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9748: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9749: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9750: 
1.702     albertel 9751: $range should be either an integer '100' (give me the first 100
                   9752:                                            matching records)
                   9753:               or be  two integers sperated by a - with no spaces
                   9754:                  '30-50' (give me the 30th through the 50th matching
                   9755:                           records)
1.449     matthew  9756: =item *
                   9757: 
                   9758: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9759: $store can be a scalar, an array reference, or if the amount to be 
                   9760: incremented is > 1, a hash reference.
                   9761: 
                   9762: ($udom and $uname are optional)
1.191     harris41 9763: 
                   9764: =item *
                   9765: 
1.243     albertel 9766: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9767: ($udom and $uname are optional)
1.191     harris41 9768: 
                   9769: =item *
                   9770: 
1.243     albertel 9771: cput($namespace,$storehash,$udom,$uname) : critical put
                   9772: ($udom and $uname are optional)
1.191     harris41 9773: 
                   9774: =item *
                   9775: 
1.748     albertel 9776: newput($namespace,$storehash,$udom,$uname) :
                   9777: 
                   9778: Attempts to store the items in the $storehash, but only if they don't
                   9779: currently exist, if this succeeds you can be certain that you have 
                   9780: successfully created a new key value pair in the $namespace db.
                   9781: 
                   9782: 
                   9783: Args:
                   9784:  $namespace: name of database to store values to
                   9785:  $storehash: hashref to store to the db
                   9786:  $udom: (optional) domain of user containing the db
                   9787:  $uname: (optional) name of user caontaining the db
                   9788: 
                   9789: Returns:
                   9790:  'ok' -> succeeded in storing all keys of $storehash
                   9791:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9792:                         least <key> already existed in the db (other
                   9793:                         requested keys may also already exist)
1.967     bisitz   9794:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9795:  'con_lost' -> unable to contact request server
                   9796:  'refused' -> action was not allowed by remote machine
                   9797: 
                   9798: 
                   9799: =item *
                   9800: 
1.243     albertel 9801: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9802: reference filled in from namesp (encrypts the return communication)
                   9803: ($udom and $uname are optional)
1.191     harris41 9804: 
                   9805: =item *
                   9806: 
1.243     albertel 9807: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9808: critical subroutine
                   9809: 
1.806     raeburn  9810: =item *
                   9811: 
1.860     raeburn  9812: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9813: array reference filled in from namespace found in domain level on either
                   9814: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9815: 
                   9816: =item *
                   9817: 
1.860     raeburn  9818: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9819: domain level either on specified domain server ($uhome) or primary domain 
                   9820: server ($udom and $uhome are optional)
1.806     raeburn  9821: 
1.943     raeburn  9822: =item * 
                   9823: 
                   9824: get_domain_defaults($target_domain) : returns hash with defaults for
                   9825: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9826: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9827: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9828: Values are retrieved from cache (if current), or from domain's configuration.db
                   9829: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9830: or lonTabs/domain.tab. 
                   9831: 
                   9832: %domdefaults = &get_auth_defaults($target_domain);
                   9833: 
1.243     albertel 9834: =back
                   9835: 
                   9836: =head2 Network Status Functions
                   9837: 
                   9838: =over 4
1.191     harris41 9839: 
                   9840: =item *
                   9841: 
                   9842: dirlist($uri) : return directory list based on URI
                   9843: 
                   9844: =item *
                   9845: 
1.243     albertel 9846: spareserver() : find server with least workload from spare.tab
                   9847: 
                   9848: =back
                   9849: 
                   9850: =head2 Apache Request
                   9851: 
                   9852: =over 4
1.191     harris41 9853: 
                   9854: =item *
                   9855: 
1.243     albertel 9856: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9857: localhost, posts hash
                   9858: 
                   9859: =back
                   9860: 
                   9861: =head2 Data to String to Data
                   9862: 
                   9863: =over 4
1.191     harris41 9864: 
                   9865: =item *
                   9866: 
1.243     albertel 9867: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9868: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9869: 
                   9870: =item *
                   9871: 
1.243     albertel 9872: hashref2str($hashref) : convert a hashref into a string complete with
                   9873: escaping and '=' and '&' separators, supports elements that are
                   9874: arrayrefs and hashrefs
1.191     harris41 9875: 
                   9876: =item *
                   9877: 
1.243     albertel 9878: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9879: with escaping and '&' separators, supports elements that are arrayrefs
                   9880: and hashrefs
1.191     harris41 9881: 
                   9882: =item *
                   9883: 
1.243     albertel 9884: str2hash($string) : convert string to hash using unescaping and
                   9885: splitting on '=' and '&', supports elements that are arrayrefs and
                   9886: hashrefs
1.191     harris41 9887: 
                   9888: =item *
                   9889: 
1.243     albertel 9890: str2array($string) : convert string to hash using unescaping and
                   9891: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9892: 
                   9893: =back
                   9894: 
                   9895: =head2 Logging Routines
                   9896: 
                   9897: =over 4
                   9898: 
                   9899: These routines allow one to make log messages in the lonnet.log and
                   9900: lonnet.perm logfiles.
1.191     harris41 9901: 
                   9902: =item *
                   9903: 
1.243     albertel 9904: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9905: 
                   9906: =item *
                   9907: 
1.243     albertel 9908: logthis() : append message to the normal lonnet.log file, it gets
                   9909: preiodically rolled over and deleted.
1.191     harris41 9910: 
                   9911: =item *
                   9912: 
1.243     albertel 9913: logperm() : append a permanent message to lonnet.perm.log, this log
                   9914: file never gets deleted by any automated portion of the system, only
                   9915: messages of critical importance should go in here.
                   9916: 
                   9917: =back
                   9918: 
                   9919: =head2 General File Helper Routines
                   9920: 
                   9921: =over 4
1.191     harris41 9922: 
                   9923: =item *
                   9924: 
1.481     raeburn  9925: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9926: (a) files in /uploaded
                   9927:   (i) If a local copy of the file exists - 
                   9928:       compares modification date of local copy with last-modified date for 
                   9929:       definitive version stored on home server for course. If local copy is 
                   9930:       stale, requests a new version from the home server and stores it. 
                   9931:       If the original has been removed from the home server, then local copy 
                   9932:       is unlinked.
                   9933:   (ii) If local copy does not exist -
                   9934:       requests the file from the home server and stores it. 
                   9935:   
                   9936:   If $caller is 'uploadrep':  
                   9937:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9938:     for request for files originally uploaded via DOCS. 
                   9939:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9940:   
                   9941:   Otherwise:
                   9942:      This indicates a call from the content generation phase of the request.
                   9943:      -  returns the entire contents of the file or -1.
                   9944:      
                   9945: (b) files in /res
                   9946:    - returns the entire contents of a file or -1; 
                   9947:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9948: 
1.712     albertel 9949: 
                   9950: =item *
                   9951: 
                   9952: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9953:                   reference
                   9954: 
                   9955: returns either a stat() list of data about the file or an empty list
                   9956: if the file doesn't exist or couldn't find out about it (connection
                   9957: problems or user unknown)
                   9958: 
1.191     harris41 9959: =item *
                   9960: 
1.243     albertel 9961: filelocation($dir,$file) : returns file system location of a file
                   9962: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9963: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9964: and a file of ../bob will become /a/bob)
1.191     harris41 9965: 
                   9966: =item *
                   9967: 
                   9968: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9969: filelocation except for hrefs
                   9970: 
                   9971: =item *
                   9972: 
                   9973: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9974: 
1.243     albertel 9975: =back
                   9976: 
1.608     albertel 9977: =head2 Usererfile file routines (/uploaded*)
                   9978: 
                   9979: =over 4
                   9980: 
                   9981: =item *
                   9982: 
                   9983: userfileupload(): main rotine for putting a file in a user or course's
                   9984:                   filespace, arguments are,
                   9985: 
1.620     albertel 9986:  formname - required - this is the name of the element in $env where the
1.608     albertel 9987:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9988:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9989:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9990:  coursedoc - if true, store the file in the course of the active role
                   9991:              of the current user
                   9992:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9993:          if undefined, it will be placed in "unknown"
                   9994: 
                   9995:  (This routine calls clean_filename() to remove any dangerous
                   9996:  characters from the filename, and then calls finuserfileupload() to
                   9997:  complete the transaction)
                   9998: 
                   9999:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10000:  and /adm/notfound.html if unsuccessful
                   10001: 
                   10002: =item *
                   10003: 
                   10004: clean_filename(): routine for cleaing a filename up for storage in
                   10005:                  userfile space, argument is:
                   10006: 
                   10007:  filename - proposed filename
                   10008: 
                   10009: returns: the new clean filename
                   10010: 
                   10011: =item *
                   10012: 
                   10013: finishuserfileupload(): routine that creaes and sends the file to
                   10014: userspace, probably shouldn't be called directly
                   10015: 
                   10016:   docuname: username or courseid of destination for the file
                   10017:   docudom: domain of user/course of destination for the file
                   10018:   formname: same as for userfileupload()
                   10019:   fname: filename (inculding subdirectories) for the file
                   10020: 
                   10021:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10022:  and /adm/notfound.html if unsuccessful
                   10023: 
                   10024: =item *
                   10025: 
                   10026: renameuserfile(): renames an existing userfile to a new name
                   10027: 
                   10028:   Args:
                   10029:    docuname: username or courseid of destination for the file
                   10030:    docudom: domain of user/course of destination for the file
                   10031:    old: current file name (including any subdirs under userfiles)
                   10032:    new: desired file name (including any subdirs under userfiles)
                   10033: 
                   10034: =item *
                   10035: 
                   10036: mkdiruserfile(): creates a directory is a userfiles dir
                   10037: 
                   10038:   Args:
                   10039:    docuname: username or courseid of destination for the file
                   10040:    docudom: domain of user/course of destination for the file
                   10041:    dir: dir to create (including any subdirs under userfiles)
                   10042: 
                   10043: =item *
                   10044: 
                   10045: removeuserfile(): removes a file that exists in userfiles
                   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:    fname: filname to delete (including any subdirs under userfiles)
                   10051: 
                   10052: =item *
                   10053: 
                   10054: removeuploadedurl(): convience function for removeuserfile()
                   10055: 
                   10056:   Args:
                   10057:    url:  a full /uploaded/... url to delete
                   10058: 
1.747     albertel 10059: =item * 
                   10060: 
                   10061: get_portfile_permissions():
                   10062:   Args:
                   10063:     domain: domain of user or course contain the portfolio files
                   10064:     user: name of user or num of course contain the portfolio files
                   10065:   Returns:
                   10066:     hashref of a dump of the proper file_permissions.db
                   10067:    
                   10068: 
                   10069: =item * 
                   10070: 
                   10071: get_access_controls():
                   10072: 
                   10073: Args:
                   10074:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10075:   group: (optional) the group you want the files associated with
                   10076:   file: (optional) the file you want access info on
                   10077: 
                   10078: Returns:
1.749     raeburn  10079:     a hash (keys are file names) of hashes containing
                   10080:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10081:         values are XML containing access control settings (see below) 
1.747     albertel 10082: 
                   10083: Internal notes:
                   10084: 
1.749     raeburn  10085:  access controls are stored in file_permissions.db as key=value pairs.
                   10086:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10087:         where scope -> public,guest,course,group,domains or users.
                   10088:               end -> UNIX time for end of access (0 -> no end date)
                   10089:               start -> UNIX time for start of access
                   10090: 
                   10091:     value -> XML description of access control
                   10092:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10093:             <start></start>
                   10094:             <end></end>
                   10095: 
                   10096:             <password></password>  for scope type = guest
                   10097: 
                   10098:             <domain></domain>     for scope type = course or group
                   10099:             <number></number>
                   10100:             <roles id="">
                   10101:              <role></role>
                   10102:              <access></access>
                   10103:              <section></section>
                   10104:              <group></group>
                   10105:             </roles>
                   10106: 
                   10107:             <dom></dom>         for scope type = domains
                   10108: 
                   10109:             <users>             for scope type = users
                   10110:              <user>
                   10111:               <uname></uname>
                   10112:               <udom></udom>
                   10113:              </user>
                   10114:             </users>
                   10115:            </scope> 
                   10116:               
                   10117:  Access data is also aggregated for each file in an additional key=value pair:
                   10118:  key -> path to file/file_name\0accesscontrol 
                   10119:  value -> reference to hash
                   10120:           hash contains key = value pairs
                   10121:           where key = uniqueID:scope_end_start
                   10122:                 value = UNIX time record was last updated
                   10123: 
                   10124:           Used to improve speed of look-ups of access controls for each file.  
                   10125:  
                   10126:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10127: 
                   10128: modify_access_controls():
                   10129: 
                   10130: Modifies access controls for a portfolio file
                   10131: Args
                   10132: 1. file name
                   10133: 2. reference to hash of required changes,
                   10134: 3. domain
                   10135: 4. username
                   10136:   where domain,username are the domain of the portfolio owner 
                   10137:   (either a user or a course) 
                   10138: 
                   10139: Returns:
                   10140: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10141: 2. result of deletions ('ok' or 'error', with error message).
                   10142: 3. reference to hash of any new or updated access controls.
                   10143: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10144:    key = integer (inbound ID)
                   10145:    value = uniqueID  
1.747     albertel 10146: 
1.608     albertel 10147: =back
                   10148: 
1.243     albertel 10149: =head2 HTTP Helper Routines
                   10150: 
                   10151: =over 4
                   10152: 
1.191     harris41 10153: =item *
                   10154: 
                   10155: escape() : unpack non-word characters into CGI-compatible hex codes
                   10156: 
                   10157: =item *
                   10158: 
                   10159: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10160: 
1.243     albertel 10161: =back
                   10162: 
                   10163: =head1 PRIVATE SUBROUTINES
                   10164: 
                   10165: =head2 Underlying communication routines (Shouldn't call)
                   10166: 
                   10167: =over 4
                   10168: 
                   10169: =item *
                   10170: 
                   10171: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10172: 
                   10173: =item *
                   10174: 
                   10175: reply() : uses subreply to send a message to remote machine, logs all failures
                   10176: 
                   10177: =item *
                   10178: 
                   10179: critical() : passes a critical message to another server; if cannot
                   10180: get through then place message in connection buffer directory and
                   10181: returns con_delayed, if incapable of saving message, returns
                   10182: con_failed
                   10183: 
                   10184: =item *
                   10185: 
                   10186: reconlonc() : tries to reconnect lonc client processes.
                   10187: 
                   10188: =back
                   10189: 
                   10190: =head2 Resource Access Logging
                   10191: 
                   10192: =over 4
                   10193: 
                   10194: =item *
                   10195: 
                   10196: flushcourselogs() : flush (save) buffer logs and access logs
                   10197: 
                   10198: =item *
                   10199: 
                   10200: courselog($what) : save message for course in hash
                   10201: 
                   10202: =item *
                   10203: 
                   10204: courseacclog($what) : save message for course using &courselog().  Perform
                   10205: special processing for specific resource types (problems, exams, quizzes, etc).
                   10206: 
1.191     harris41 10207: =item *
                   10208: 
                   10209: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10210: as a PerlChildExitHandler
1.243     albertel 10211: 
                   10212: =back
                   10213: 
                   10214: =head2 Other
                   10215: 
                   10216: =over 4
                   10217: 
                   10218: =item *
                   10219: 
                   10220: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10221: 
                   10222: =back
                   10223: 
                   10224: =cut
1.877     foxr     10225: 

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