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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.982   ! raeburn     4: # $Id: lonnet.pm,v 1.981 2008/12/21 19:03:10 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)) {
1.981     raeburn   528: 	    if ($key=~/^\Q$delthis\E/) { 
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;
                   1234:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1235:     if (defined($cached)) {
                   1236:         if (ref($result) eq 'HASH') {
                   1237:             return %{$result};
                   1238:         }
                   1239:     }
                   1240:     my %domdefaults;
                   1241:     my %domconfig =
1.976     raeburn  1242:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943     raeburn  1243:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1244:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1245:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1246:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982   ! raeburn  1247:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
        !          1248:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'}
1.943     raeburn  1249:     } else {
                   1250:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1251:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1252:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1253:     }
1.976     raeburn  1254:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1255:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1256:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1257:         } else {
                   1258:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1259:         } 
                   1260:         my @usertools = ('aboutme','blog','portfolio');
                   1261:         foreach my $item (@usertools) {
                   1262:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1263:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1264:             }
                   1265:         }
                   1266:     }
1.943     raeburn  1267:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1268:                                   $cachetime);
                   1269:     return %domdefaults;
                   1270: }
                   1271: 
1.344     www      1272: # --------------------------------------------------- Assign a key to a student
                   1273: 
                   1274: sub assign_access_key {
1.364     www      1275: #
                   1276: # a valid key looks like uname:udom#comments
                   1277: # comments are being appended
                   1278: #
1.498     www      1279:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1280:     $kdom=
1.620     albertel 1281:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1282:     $knum=
1.620     albertel 1283:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1284:     $cdom=
1.620     albertel 1285:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1286:     $cnum=
1.620     albertel 1287:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1288:     $udom=$env{'user.name'} unless (defined($udom));
                   1289:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1290:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1291:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1292:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1293:                                                   # assigned to this person
                   1294:                                                   # - this should not happen,
1.345     www      1295:                                                   # unless something went wrong
                   1296:                                                   # the first time around
                   1297: # ready to assign
1.364     www      1298:         $logentry=$1.'; '.$logentry;
1.496     www      1299:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1300:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1301: # key now belongs to user
1.346     www      1302: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1303:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1304:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1305:                 return 'ok';
                   1306:             } else {
                   1307:                 return 
                   1308:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1309: 	    }
                   1310:         } else {
                   1311:             return 'error: Could not assign key, try again later.';
                   1312:         }
1.364     www      1313:     } elsif (!$existing{$ckey}) {
1.345     www      1314: # the key does not exist
                   1315: 	return 'error: The key does not exist';
                   1316:     } else {
                   1317: # the key is somebody else's
                   1318: 	return 'error: The key is already in use';
                   1319:     }
1.344     www      1320: }
                   1321: 
1.364     www      1322: # ------------------------------------------ put an additional comment on a key
                   1323: 
                   1324: sub comment_access_key {
                   1325: #
                   1326: # a valid key looks like uname:udom#comments
                   1327: # comments are being appended
                   1328: #
                   1329:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1330:     $cdom=
1.620     albertel 1331:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1332:     $cnum=
1.620     albertel 1333:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1334:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1335:     if ($existing{$ckey}) {
                   1336:         $existing{$ckey}.='; '.$logentry;
                   1337: # ready to assign
1.367     www      1338:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1339:                                                  $cdom,$cnum) eq 'ok') {
                   1340: 	    return 'ok';
                   1341:         } else {
                   1342: 	    return 'error: Count not store comment.';
                   1343:         }
                   1344:     } else {
                   1345: # the key does not exist
                   1346: 	return 'error: The key does not exist';
                   1347:     }
                   1348: }
                   1349: 
1.344     www      1350: # ------------------------------------------------------ Generate a set of keys
                   1351: 
                   1352: sub generate_access_keys {
1.364     www      1353:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1354:     $cdom=
1.620     albertel 1355:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1356:     $cnum=
1.620     albertel 1357:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1358:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1359:     unless (($cdom) && ($cnum)) { return 0; }
                   1360:     if ($number>10000) { return 0; }
                   1361:     sleep(2); # make sure don't get same seed twice
                   1362:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1363:     my $total=0;
                   1364:     for (my $i=1;$i<=$number;$i++) {
                   1365:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1366:                   sprintf("%lx",int(100000*rand)).'-'.
                   1367:                   sprintf("%lx",int(100000*rand));
                   1368:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1369:        $newkey=~s/0/h/g; # and also 0 and O
                   1370:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1371:        if ($existing{$newkey}) {
                   1372:            $i--;
                   1373:        } else {
1.364     www      1374: 	  if (&put('accesskeys',
                   1375:               { $newkey => '# generated '.localtime().
1.620     albertel 1376:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1377:                            '; '.$logentry },
                   1378: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1379:               $total++;
                   1380: 	  }
                   1381:        }
                   1382:     }
1.620     albertel 1383:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1384:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1385:     return $total;
                   1386: }
                   1387: 
                   1388: # ------------------------------------------------------- Validate an accesskey
                   1389: 
                   1390: sub validate_access_key {
                   1391:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1392:     $cdom=
1.620     albertel 1393:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1394:     $cnum=
1.620     albertel 1395:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1396:     $udom=$env{'user.domain'} unless (defined($udom));
                   1397:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1398:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1399:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1400: }
                   1401: 
                   1402: # ------------------------------------- Find the section of student in a course
1.652     albertel 1403: sub devalidate_getsection_cache {
                   1404:     my ($udom,$unam,$courseid)=@_;
                   1405:     my $hashid="$udom:$unam:$courseid";
                   1406:     &devalidate_cache_new('getsection',$hashid);
                   1407: }
1.298     matthew  1408: 
1.815     albertel 1409: sub courseid_to_courseurl {
                   1410:     my ($courseid) = @_;
                   1411:     #already url style courseid
                   1412:     return $courseid if ($courseid =~ m{^/});
                   1413: 
                   1414:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1415: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1416: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1417: 	return "/$cdom/$cnum";
                   1418:     }
                   1419: 
                   1420:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1421:     if (exists($courseinfo{'num'})) {
                   1422: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1423:     }
                   1424: 
                   1425:     return undef;
                   1426: }
                   1427: 
1.298     matthew  1428: sub getsection {
                   1429:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1430:     my $cachetime=1800;
1.551     albertel 1431: 
                   1432:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1433:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1434:     if (defined($cached)) { return $result; }
                   1435: 
1.298     matthew  1436:     my %Pending; 
                   1437:     my %Expired;
                   1438:     #
                   1439:     # Each role can either have not started yet (pending), be active, 
                   1440:     #    or have expired.
                   1441:     #
                   1442:     # If there is an active role, we are done.
                   1443:     #
                   1444:     # If there is more than one role which has not started yet, 
                   1445:     #     choose the one which will start sooner
                   1446:     # If there is one role which has not started yet, return it.
                   1447:     #
                   1448:     # If there is more than one expired role, choose the one which ended last.
                   1449:     # If there is a role which has expired, return it.
                   1450:     #
1.815     albertel 1451:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1452:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1453:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1454:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1455:         my $section=$1;
                   1456:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1457:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1458:         my $now=time;
1.548     albertel 1459:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1460:             $Expired{$end}=$section;
                   1461:             next;
                   1462:         }
1.548     albertel 1463:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1464:             $Pending{$start}=$section;
                   1465:             next;
                   1466:         }
1.599     albertel 1467:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1468:     }
                   1469:     #
                   1470:     # Presumedly there will be few matching roles from the above
                   1471:     # loop and the sorting time will be negligible.
                   1472:     if (scalar(keys(%Pending))) {
                   1473:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1474:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1475:     } 
                   1476:     if (scalar(keys(%Expired))) {
                   1477:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1478:         my $time = pop(@sorted);
1.599     albertel 1479:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1480:     }
1.599     albertel 1481:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1482: }
1.70      www      1483: 
1.599     albertel 1484: sub save_cache {
                   1485:     &purge_remembered();
1.722     albertel 1486:     #&Apache::loncommon::validate_page();
1.620     albertel 1487:     undef(%env);
1.780     albertel 1488:     undef($env_loaded);
1.599     albertel 1489: }
1.452     albertel 1490: 
1.599     albertel 1491: my $to_remember=-1;
                   1492: my %remembered;
                   1493: my %accessed;
                   1494: my $kicks=0;
                   1495: my $hits=0;
1.849     albertel 1496: sub make_key {
                   1497:     my ($name,$id) = @_;
1.872     albertel 1498:     if (length($id) > 65 
                   1499: 	&& length(&escape($id)) > 200) {
                   1500: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1501:     }
1.849     albertel 1502:     return &escape($name.':'.$id);
                   1503: }
                   1504: 
1.599     albertel 1505: sub devalidate_cache_new {
                   1506:     my ($name,$id,$debug) = @_;
                   1507:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1508:     $id=&make_key($name,$id);
1.599     albertel 1509:     $memcache->delete($id);
                   1510:     delete($remembered{$id});
                   1511:     delete($accessed{$id});
                   1512: }
                   1513: 
                   1514: sub is_cached_new {
                   1515:     my ($name,$id,$debug) = @_;
1.849     albertel 1516:     $id=&make_key($name,$id);
1.599     albertel 1517:     if (exists($remembered{$id})) {
                   1518: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1519: 	$accessed{$id}=[&gettimeofday()];
                   1520: 	$hits++;
                   1521: 	return ($remembered{$id},1);
                   1522:     }
                   1523:     my $value = $memcache->get($id);
                   1524:     if (!(defined($value))) {
                   1525: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1526: 	return (undef,undef);
1.416     albertel 1527:     }
1.599     albertel 1528:     if ($value eq '__undef__') {
                   1529: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1530: 	$value=undef;
                   1531:     }
                   1532:     &make_room($id,$value,$debug);
                   1533:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1534:     return ($value,1);
                   1535: }
                   1536: 
                   1537: sub do_cache_new {
                   1538:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1539:     $id=&make_key($name,$id);
1.599     albertel 1540:     my $setvalue=$value;
                   1541:     if (!defined($setvalue)) {
                   1542: 	$setvalue='__undef__';
                   1543:     }
1.623     albertel 1544:     if (!defined($time) ) {
                   1545: 	$time=600;
                   1546:     }
1.599     albertel 1547:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1548:     my $result = $memcache->set($id,$setvalue,$time);
                   1549:     if (! $result) {
1.872     albertel 1550: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1551: 	$memcache->disconnect_all();
1.872     albertel 1552:     }
1.600     albertel 1553:     # need to make a copy of $value
1.919     albertel 1554:     &make_room($id,$value,$debug);
1.599     albertel 1555:     return $value;
                   1556: }
                   1557: 
                   1558: sub make_room {
                   1559:     my ($id,$value,$debug)=@_;
1.919     albertel 1560: 
                   1561:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1562:                                     : $value;
1.599     albertel 1563:     if ($to_remember<0) { return; }
                   1564:     $accessed{$id}=[&gettimeofday()];
                   1565:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1566:     my $to_kick;
                   1567:     my $max_time=0;
                   1568:     foreach my $other (keys(%accessed)) {
                   1569: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1570: 	    $to_kick=$other;
                   1571: 	    $max_time=&tv_interval($accessed{$other});
                   1572: 	}
                   1573:     }
                   1574:     delete($remembered{$to_kick});
                   1575:     delete($accessed{$to_kick});
                   1576:     $kicks++;
                   1577:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1578:     return;
                   1579: }
                   1580: 
1.599     albertel 1581: sub purge_remembered {
1.604     albertel 1582:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1583:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1584:     undef(%remembered);
                   1585:     undef(%accessed);
1.428     albertel 1586: }
1.70      www      1587: # ------------------------------------- Read an entry from a user's environment
                   1588: 
                   1589: sub userenvironment {
                   1590:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1591:     my $items;
                   1592:     foreach my $item (@what) {
                   1593:         $items.=&escape($item).'&';
                   1594:     }
                   1595:     $items=~s/\&$//;
1.70      www      1596:     my %returnhash=();
                   1597:     my @answer=split(/\&/,
1.976     raeburn  1598:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1599:                       &homeserver($unam,$udom)));
                   1600:     my $i;
                   1601:     for ($i=0;$i<=$#what;$i++) {
                   1602: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1603:     }
                   1604:     return %returnhash;
1.1       albertel 1605: }
                   1606: 
1.617     albertel 1607: # ---------------------------------------------------------- Get a studentphoto
                   1608: sub studentphoto {
                   1609:     my ($udom,$unam,$ext) = @_;
                   1610:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1611:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1612:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1613:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1614:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1615:             } else {
                   1616:                 my ($result,$perm_reqd)=
1.707     albertel 1617: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1618:                 if ($result eq 'ok') {
                   1619:                     if (!($perm_reqd eq 'yes')) {
                   1620:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1621:                     }
                   1622:                 }
                   1623:             }
                   1624:         }
                   1625:     } else {
                   1626:         my ($result,$perm_reqd) = 
1.707     albertel 1627: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1628:         if ($result eq 'ok') {
                   1629:             if (!($perm_reqd eq 'yes')) {
                   1630:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1631:             }
                   1632:         }
                   1633:     }
                   1634:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1635: }
                   1636: 
                   1637: sub retrievestudentphoto {
                   1638:     my ($udom,$unam,$ext,$type) = @_;
                   1639:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1640:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1641:     if ($ret eq 'ok') {
                   1642:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1643:         if ($type eq 'thumbnail') {
                   1644:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1645:         }
                   1646:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1647:         return $tokenurl;
                   1648:     } else {
                   1649:         if ($type eq 'thumbnail') {
                   1650:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1651:         } else { 
                   1652:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1653:         }
1.617     albertel 1654:     }
                   1655: }
                   1656: 
1.263     www      1657: # -------------------------------------------------------------------- New chat
                   1658: 
                   1659: sub chatsend {
1.724     raeburn  1660:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1661:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1662:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1663:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1664:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1665: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1666: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1667: }
                   1668: 
                   1669: # ------------------------------------------ Find current version of a resource
                   1670: 
                   1671: sub getversion {
                   1672:     my $fname=&clutter(shift);
                   1673:     unless ($fname=~/^\/res\//) { return -1; }
                   1674:     return &currentversion(&filelocation('',$fname));
                   1675: }
                   1676: 
                   1677: sub currentversion {
                   1678:     my $fname=shift;
1.599     albertel 1679:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1680:     if (defined($cached)) { return $result; }
1.292     www      1681:     my $author=$fname;
                   1682:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1683:     my ($udom,$uname)=split(/\//,$author);
                   1684:     my $home=homeserver($uname,$udom);
                   1685:     if ($home eq 'no_host') { 
                   1686:         return -1; 
                   1687:     }
                   1688:     my $answer=reply("currentversion:$fname",$home);
                   1689:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1690: 	return -1;
                   1691:     }
1.599     albertel 1692:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1693: }
                   1694: 
1.1       albertel 1695: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1696: 
1.1       albertel 1697: sub subscribe {
                   1698:     my $fname=shift;
1.761     raeburn  1699:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1700:     $fname=~s/[\n\r]//g;
1.1       albertel 1701:     my $author=$fname;
                   1702:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1703:     my ($udom,$uname)=split(/\//,$author);
                   1704:     my $home=homeserver($uname,$udom);
1.335     albertel 1705:     if ($home eq 'no_host') {
                   1706:         return 'not_found';
1.1       albertel 1707:     }
                   1708:     my $answer=reply("sub:$fname",$home);
1.64      www      1709:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1710: 	$answer.=' by '.$home;
                   1711:     }
1.1       albertel 1712:     return $answer;
                   1713: }
                   1714:     
1.8       www      1715: # -------------------------------------------------------------- Replicate file
                   1716: 
                   1717: sub repcopy {
                   1718:     my $filename=shift;
1.23      www      1719:     $filename=~s/\/+/\//g;
1.607     raeburn  1720:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1721:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1722:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1723: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1724: 	return &repcopy_userfile($filename);
                   1725:     }
1.532     albertel 1726:     $filename=~s/[\n\r]//g;
1.8       www      1727:     my $transname="$filename.in.transfer";
1.828     www      1728: # FIXME: this should flock
1.607     raeburn  1729:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1730:     my $remoteurl=subscribe($filename);
1.64      www      1731:     if ($remoteurl =~ /^con_lost by/) {
                   1732: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1733:            return 'unavailable';
1.8       www      1734:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1735: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1736: 	   return 'not_found';
1.64      www      1737:     } elsif ($remoteurl =~ /^rejected by/) {
                   1738: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1739:            return 'forbidden';
1.20      www      1740:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1741:            return 'ok';
1.8       www      1742:     } else {
1.290     www      1743:         my $author=$filename;
                   1744:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1745:         my ($udom,$uname)=split(/\//,$author);
                   1746:         my $home=homeserver($uname,$udom);
                   1747:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1748:            my @parts=split(/\//,$filename);
                   1749:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1750:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1751:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1752: 	       return 'bad_request';
1.8       www      1753:            }
                   1754:            my $count;
                   1755:            for ($count=5;$count<$#parts;$count++) {
                   1756:                $path.="/$parts[$count]";
                   1757:                if ((-e $path)!=1) {
                   1758: 		   mkdir($path,0777);
                   1759:                }
                   1760:            }
                   1761:            my $ua=new LWP::UserAgent;
                   1762:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1763:            my $response=$ua->request($request,$transname);
                   1764:            if ($response->is_error()) {
                   1765: 	       unlink($transname);
                   1766:                my $message=$response->status_line;
1.672     albertel 1767:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1768:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1769:                return 'unavailable';
1.8       www      1770:            } else {
1.16      www      1771: 	       if ($remoteurl!~/\.meta$/) {
                   1772:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1773:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1774:                   if ($mresponse->is_error()) {
                   1775: 		      unlink($filename.'.meta');
                   1776:                       &logthis(
1.672     albertel 1777:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1778:                   }
                   1779: 	       }
1.8       www      1780:                rename($transname,$filename);
1.607     raeburn  1781:                return 'ok';
1.8       www      1782:            }
1.290     www      1783:        }
1.8       www      1784:     }
1.330     www      1785: }
                   1786: 
                   1787: # ------------------------------------------------ Get server side include body
                   1788: sub ssi_body {
1.381     albertel 1789:     my ($filelink,%form)=@_;
1.606     matthew  1790:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1791:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1792:     }
1.953     www      1793:     my $output='';
                   1794:     my $response;
1.980     raeburn  1795:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1796:        ($output,$response)=&externalssi($filelink);
1.953     www      1797:     } else {
                   1798:        ($output,$response)=&ssi($filelink,%form);
                   1799:     }
1.778     albertel 1800:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1801:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1802:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1803:     if (wantarray) {
                   1804:         return ($output, $response);
                   1805:     } else {
                   1806:         return $output;
                   1807:     }
1.8       www      1808: }
                   1809: 
1.15      www      1810: # --------------------------------------------------------- Server Side Include
                   1811: 
1.782     albertel 1812: sub absolute_url {
                   1813:     my ($host_name) = @_;
                   1814:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1815:     if ($host_name eq '') {
                   1816: 	$host_name = $ENV{'SERVER_NAME'};
                   1817:     }
                   1818:     return $protocol.$host_name;
                   1819: }
                   1820: 
1.942     foxr     1821: #
                   1822: #   Server side include.
                   1823: # Parameters:
                   1824: #  fn     Possibly encrypted resource name/id.
                   1825: #  form   Hash that describes how the rendering should be done
                   1826: #         and other things.
1.944     foxr     1827: # Returns:
1.950     raeburn  1828: #   Scalar context: The content of the response.
                   1829: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1830: #     
1.15      www      1831: sub ssi {
                   1832: 
1.944     foxr     1833:     my ($fn,%form)=@_;
1.15      www      1834:     my $ua=new LWP::UserAgent;
1.23      www      1835:     my $request;
1.711     albertel 1836: 
                   1837:     $form{'no_update_last_known'}=1;
1.895     albertel 1838:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1839:     if (%form) {
1.782     albertel 1840:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1841:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1842:     } else {
1.782     albertel 1843:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1844:     }
                   1845: 
1.15      www      1846:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1847:     my $response=$ua->request($request);
                   1848: 
1.944     foxr     1849:     if (wantarray) {
                   1850: 	return ($response->content, $response);
                   1851:     } else {
                   1852: 	return $response->content;
1.942     foxr     1853:     }
1.324     www      1854: }
                   1855: 
                   1856: sub externalssi {
                   1857:     my ($url)=@_;
                   1858:     my $ua=new LWP::UserAgent;
                   1859:     my $request=new HTTP::Request('GET',$url);
                   1860:     my $response=$ua->request($request);
1.954     raeburn  1861:     if (wantarray) {
                   1862:         return ($response->content, $response);
                   1863:     } else {
                   1864:         return $response->content;
                   1865:     }
1.15      www      1866: }
1.254     www      1867: 
1.492     albertel 1868: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1869: 
                   1870: sub allowuploaded {
                   1871:     my ($srcurl,$url)=@_;
                   1872:     $url=&clutter(&declutter($url));
                   1873:     my $dir=$url;
                   1874:     $dir=~s/\/[^\/]+$//;
                   1875:     my %httpref=();
                   1876:     my $httpurl=&hreflocation('',$url);
                   1877:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1878:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1879: }
1.477     raeburn  1880: 
1.478     albertel 1881: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1882: # input: action, courseID, current domain, intended
1.637     raeburn  1883: #        path to file, source of file, instruction to parse file for objects,
                   1884: #        ref to hash for embedded objects,
                   1885: #        ref to hash for codebase of java objects.
                   1886: #
1.485     raeburn  1887: # output: url to file (if action was uploaddoc), 
                   1888: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1889: #
1.478     albertel 1890: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1891: # course.
1.477     raeburn  1892: #
1.478     albertel 1893: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1894: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1895: #          course's home server.
1.477     raeburn  1896: #
1.478     albertel 1897: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1898: #          be copied from $source (current location) to 
                   1899: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1900: #         and will then be copied to
                   1901: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1902: #         course's home server.
1.485     raeburn  1903: #
1.481     raeburn  1904: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1905: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1906: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1907: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1908: #         in course's home server.
1.637     raeburn  1909: #
1.477     raeburn  1910: 
                   1911: sub process_coursefile {
1.638     albertel 1912:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1913:     my $fetchresult;
1.638     albertel 1914:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1915:     if ($action eq 'propagate') {
1.638     albertel 1916:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1917: 			     $home);
1.481     raeburn  1918:     } else {
1.477     raeburn  1919:         my $fpath = '';
                   1920:         my $fname = $file;
1.478     albertel 1921:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1922:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1923:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1924:         if ($action eq 'copy') {
                   1925:             if ($source eq '') {
                   1926:                 $fetchresult = 'no source file';
                   1927:                 return $fetchresult;
                   1928:             } else {
                   1929:                 my $destination = $filepath.'/'.$fname;
                   1930:                 rename($source,$destination);
                   1931:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1932:                                  $home);
1.481     raeburn  1933:             }
                   1934:         } elsif ($action eq 'uploaddoc') {
                   1935:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1936:             print $fh $env{'form.'.$source};
1.481     raeburn  1937:             close($fh);
1.637     raeburn  1938:             if ($parser eq 'parse') {
1.961     raeburn  1939:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1940:                 unless ($parse_result eq 'ok') {
                   1941:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1942:                 }
                   1943:             }
1.477     raeburn  1944:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1945:                                  $home);
1.481     raeburn  1946:             if ($fetchresult eq 'ok') {
                   1947:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1948:             } else {
                   1949:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1950:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1951:                 return '/adm/notfound.html';
                   1952:             }
1.477     raeburn  1953:         }
                   1954:     }
1.485     raeburn  1955:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1956:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1957:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1958:     }
                   1959:     return $fetchresult;
                   1960: }
                   1961: 
1.637     raeburn  1962: sub build_filepath {
                   1963:     my ($fpath) = @_;
                   1964:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1965:     unless ($fpath eq '') {
                   1966:         my @parts=split('/',$fpath);
                   1967:         foreach my $part (@parts) {
                   1968:             $filepath.= '/'.$part;
                   1969:             if ((-e $filepath)!=1) {
                   1970:                 mkdir($filepath,0777);
                   1971:             }
                   1972:         }
                   1973:     }
                   1974:     return $filepath;
                   1975: }
                   1976: 
                   1977: sub store_edited_file {
1.638     albertel 1978:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1979:     my $file = $primary_url;
                   1980:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1981:     my $fpath = '';
                   1982:     my $fname = $file;
                   1983:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1984:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1985:     my $filepath = &build_filepath($fpath);
                   1986:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1987:     print $fh $content;
                   1988:     close($fh);
1.638     albertel 1989:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1990:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1991: 			  $home);
1.637     raeburn  1992:     if ($$fetchresult eq 'ok') {
                   1993:         return '/uploaded/'.$fpath.'/'.$fname;
                   1994:     } else {
1.638     albertel 1995:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1996: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1997:         return '/adm/notfound.html';
                   1998:     }
                   1999: }
                   2000: 
1.531     albertel 2001: sub clean_filename {
1.831     albertel 2002:     my ($fname,$args)=@_;
1.315     www      2003: # Replace Windows backslashes by forward slashes
1.257     www      2004:     $fname=~s/\\/\//g;
1.831     albertel 2005:     if (!$args->{'keep_path'}) {
                   2006:         # Get rid of everything but the actual filename
                   2007: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2008:     }
1.315     www      2009: # Replace spaces by underscores
                   2010:     $fname=~s/\s+/\_/g;
                   2011: # Replace all other weird characters by nothing
1.831     albertel 2012:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2013: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2014: # numbers
                   2015:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2016:     return $fname;
                   2017: }
                   2018: 
1.977     amueller 2019: #Wrapper function for userphotoupload
                   2020: sub userphotoupload
                   2021: {
                   2022: 	my($formname,$subdir) = @_;
                   2023: 	$upload_photo_form = 1;
                   2024: 	return &userfileupload($formname,undef,$subdir);
                   2025: }
                   2026: 
1.608     albertel 2027: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2028: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2029: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2030: #        $coursedoc - if true up to the current course
                   2031: #                     if false
                   2032: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2033: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2034: #        $allfiles - reference to hash for embedded objects
                   2035: #        $codebase - reference to hash for codebase of java objects
                   2036: #        $desuname - username for permanent storage of uploaded file
                   2037: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2038: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2039: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2040: # 
1.686     albertel 2041: # output: url of file in userspace, or error: <message> 
                   2042: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2043: 
                   2044: 
1.531     albertel 2045: sub userfileupload {
1.860     raeburn  2046:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2047:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2048:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2049:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2050:     $fname=&clean_filename($fname);
1.315     www      2051: # See if there is anything left
1.257     www      2052:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2053:     chop($env{'form.'.$formname});
1.523     raeburn  2054:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2055:         my $now = time;
                   2056:         my $filepath = 'tmp/helprequests/'.$now;
                   2057:         my @parts=split(/\//,$filepath);
                   2058:         my $fullpath = $perlvar{'lonDaemons'};
                   2059:         for (my $i=0;$i<@parts;$i++) {
                   2060:             $fullpath .= '/'.$parts[$i];
                   2061:             if ((-e $fullpath)!=1) {
                   2062:                 mkdir($fullpath,0777);
                   2063:             }
                   2064:         }
                   2065:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2066:         print $fh $env{'form.'.$formname};
1.523     raeburn  2067:         close($fh);
1.741     raeburn  2068:         return $fullpath.'/'.$fname;
                   2069:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2070:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2071:                        '_'.$env{'user.domain'}.'/pending';
                   2072:         my @parts=split(/\//,$filepath);
                   2073:         my $fullpath = $perlvar{'lonDaemons'};
                   2074:         for (my $i=0;$i<@parts;$i++) {
                   2075:             $fullpath .= '/'.$parts[$i];
                   2076:             if ((-e $fullpath)!=1) {
                   2077:                 mkdir($fullpath,0777);
                   2078:             }
                   2079:         }
                   2080:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2081:         print $fh $env{'form.'.$formname};
                   2082:         close($fh);
                   2083:         return $fullpath.'/'.$fname;
1.523     raeburn  2084:     }
1.719     banghart 2085:     
1.258     www      2086: # Create the directory if not present
1.493     albertel 2087:     $fname="$subdir/$fname";
1.259     www      2088:     if ($coursedoc) {
1.638     albertel 2089: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2090: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2091:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2092:             return &finishuserfileupload($docuname,$docudom,
                   2093: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2094: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2095:         } else {
1.620     albertel 2096:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2097:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2098: 				       $fname,$formname,$parser,
                   2099: 				       $allfiles,$codebase);
1.481     raeburn  2100:         }
1.719     banghart 2101:     } elsif (defined($destuname)) {
                   2102:         my $docuname=$destuname;
                   2103:         my $docudom=$destudom;
1.860     raeburn  2104: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2105: 				     $parser,$allfiles,$codebase,
                   2106:                                      $thumbwidth,$thumbheight);
1.719     banghart 2107:         
1.259     www      2108:     } else {
1.638     albertel 2109:         my $docuname=$env{'user.name'};
                   2110:         my $docudom=$env{'user.domain'};
1.714     raeburn  2111:         if (exists($env{'form.group'})) {
                   2112:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2113:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2114:         }
1.860     raeburn  2115: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2116: 				     $parser,$allfiles,$codebase,
                   2117:                                      $thumbwidth,$thumbheight);
1.259     www      2118:     }
1.271     www      2119: }
                   2120: 
                   2121: sub finishuserfileupload {
1.860     raeburn  2122:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2123:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2124:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2125:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2126:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2127:     $file=$fname;
                   2128:     if ($fname=~m|/|) {
                   2129:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2130: 	$path.=$fnamepath.'/';
                   2131:     }
1.259     www      2132:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2133:     my $count;
                   2134:     for ($count=4;$count<=$#parts;$count++) {
                   2135:         $filepath.="/$parts[$count]";
                   2136:         if ((-e $filepath)!=1) {
                   2137: 	    mkdir($filepath,0777);
                   2138:         }
                   2139:     }
                   2140: # Save the file
                   2141:     {
1.701     albertel 2142: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2143: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2144: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2145: 	    return '/adm/notfound.html';
                   2146: 	}
                   2147: 	if (!print FH ($env{'form.'.$formname})) {
                   2148: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2149: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2150: 	    return '/adm/notfound.html';
                   2151: 	}
1.570     albertel 2152: 	close(FH);
1.977     amueller 2153: 	if($upload_photo_form==1)
                   2154: 	{
                   2155: 		my $ima = Image::Magick->new;                       
                   2156:             	$ima->Read($filepath.'/'.$file);
                   2157: 		if($ima->Get('width') > 300)
                   2158: 		{
                   2159: 			my $factor = $ima->Get('width')/300;
                   2160:              		$ima->Scale( width=>300, height=>$ima->Get('height')/$factor );
                   2161: 		}
                   2162: 		if($ima->Get('height') > 400)
                   2163:                 {
                   2164:                         my $factor = $ima->Get('height')/400;
                   2165:                         $ima->Scale( width=>$ima->Get('width')/$factor, height=>400);
                   2166:                 }
                   2167:  
                   2168: 		
                   2169: 		$ima->Write($filepath.'/'.$file);
                   2170: 		$upload_photo_form = 0;
                   2171: 	}
1.258     www      2172:     }
1.637     raeburn  2173:     if ($parser eq 'parse') {
1.961     raeburn  2174:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2175: 						   $codebase);
1.637     raeburn  2176:         unless ($parse_result eq 'ok') {
1.638     albertel 2177:             &logthis('Failed to parse '.$filepath.$file.
                   2178: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2179:         }
                   2180:     }
1.860     raeburn  2181:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2182:         my $input = $filepath.'/'.$file;
                   2183:         my $output = $filepath.'/'.'tn-'.$file;
                   2184:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2185:         system("convert -sample $thumbsize $input $output");
                   2186:         if (-e $filepath.'/'.'tn-'.$file) {
                   2187:             $fetchthumb  = 1; 
                   2188:         }
                   2189:     }
1.858     raeburn  2190:  
1.259     www      2191: # Notify homeserver to grep it
                   2192: #
1.638     albertel 2193:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2194:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2195:     if ($fetchresult eq 'ok') {
1.860     raeburn  2196:         if ($fetchthumb) {
                   2197:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2198:             if ($thumbresult ne 'ok') {
                   2199:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2200:                          $docuhome.': '.$thumbresult);
                   2201:             }
                   2202:         }
1.259     www      2203: #
1.258     www      2204: # Return the URL to it
1.494     albertel 2205:         return '/uploaded/'.$path.$file;
1.263     www      2206:     } else {
1.494     albertel 2207:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2208: 		 ': '.$fetchresult);
1.263     www      2209:         return '/adm/notfound.html';
1.858     raeburn  2210:     }
1.493     albertel 2211: }
                   2212: 
1.637     raeburn  2213: sub extract_embedded_items {
1.961     raeburn  2214:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2215:     my @state = ();
                   2216:     my %javafiles = (
                   2217:                       codebase => '',
                   2218:                       code => '',
                   2219:                       archive => ''
                   2220:                     );
                   2221:     my %mediafiles = (
                   2222:                       src => '',
                   2223:                       movie => '',
                   2224:                      );
1.648     raeburn  2225:     my $p;
                   2226:     if ($content) {
                   2227:         $p = HTML::LCParser->new($content);
                   2228:     } else {
1.961     raeburn  2229:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2230:     }
1.641     albertel 2231:     while (my $t=$p->get_token()) {
1.640     albertel 2232: 	if ($t->[0] eq 'S') {
                   2233: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2234: 	    push(@state, $tagname);
1.648     raeburn  2235:             if (lc($tagname) eq 'allow') {
                   2236:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2237:             }
1.640     albertel 2238: 	    if (lc($tagname) eq 'img') {
                   2239: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2240: 	    }
1.886     albertel 2241: 	    if (lc($tagname) eq 'a') {
                   2242: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2243: 	    }
1.645     raeburn  2244:             if (lc($tagname) eq 'script') {
                   2245:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2246:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2247:                 } else {
                   2248:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2249:                 }
                   2250:             }
                   2251:             if (lc($tagname) eq 'link') {
                   2252:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2253:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2254:                 }
                   2255:             }
1.640     albertel 2256: 	    if (lc($tagname) eq 'object' ||
                   2257: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2258: 		foreach my $item (keys(%javafiles)) {
                   2259: 		    $javafiles{$item} = '';
                   2260: 		}
                   2261: 	    }
                   2262: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2263: 		my $name = lc($attr->{'name'});
                   2264: 		foreach my $item (keys(%javafiles)) {
                   2265: 		    if ($name eq $item) {
                   2266: 			$javafiles{$item} = $attr->{'value'};
                   2267: 			last;
                   2268: 		    }
                   2269: 		}
                   2270: 		foreach my $item (keys(%mediafiles)) {
                   2271: 		    if ($name eq $item) {
                   2272: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2273: 			last;
                   2274: 		    }
                   2275: 		}
                   2276: 	    }
                   2277: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2278: 		foreach my $item (keys(%javafiles)) {
                   2279: 		    if ($attr->{$item}) {
                   2280: 			$javafiles{$item} = $attr->{$item};
                   2281: 			last;
                   2282: 		    }
                   2283: 		}
                   2284: 		foreach my $item (keys(%mediafiles)) {
                   2285: 		    if ($attr->{$item}) {
                   2286: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2287: 			last;
                   2288: 		    }
                   2289: 		}
                   2290: 	    }
                   2291: 	} elsif ($t->[0] eq 'E') {
                   2292: 	    my ($tagname) = ($t->[1]);
                   2293: 	    if ($javafiles{'codebase'} ne '') {
                   2294: 		$javafiles{'codebase'} .= '/';
                   2295: 	    }  
                   2296: 	    if (lc($tagname) eq 'applet' ||
                   2297: 		lc($tagname) eq 'object' ||
                   2298: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2299: 		) {
                   2300: 		foreach my $item (keys(%javafiles)) {
                   2301: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2302: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2303: 			&add_filetype($allfiles,$file,$item);
                   2304: 		    }
                   2305: 		}
                   2306: 	    } 
                   2307: 	    pop @state;
                   2308: 	}
                   2309:     }
1.637     raeburn  2310:     return 'ok';
                   2311: }
                   2312: 
1.639     albertel 2313: sub add_filetype {
                   2314:     my ($allfiles,$file,$type)=@_;
                   2315:     if (exists($allfiles->{$file})) {
                   2316: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2317: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2318: 	}
                   2319:     } else {
                   2320: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2321:     }
                   2322: }
                   2323: 
1.493     albertel 2324: sub removeuploadedurl {
                   2325:     my ($url)=@_;
                   2326:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2327:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2328: }
                   2329: 
                   2330: sub removeuserfile {
                   2331:     my ($docuname,$docudom,$fname)=@_;
                   2332:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2333:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2334:     if ($result eq 'ok') {
                   2335:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2336:             my $metafile = $fname.'.meta';
                   2337:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2338: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2339:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2340:             my $sqlresult = 
1.823     albertel 2341:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2342:                                         'portfolio_metadata',$group,
                   2343:                                         'delete');
1.798     raeburn  2344:         }
                   2345:     }
                   2346:     return $result;
1.257     www      2347: }
1.15      www      2348: 
1.530     albertel 2349: sub mkdiruserfile {
                   2350:     my ($docuname,$docudom,$dir)=@_;
                   2351:     my $home=&homeserver($docuname,$docudom);
                   2352:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2353: }
                   2354: 
1.531     albertel 2355: sub renameuserfile {
                   2356:     my ($docuname,$docudom,$old,$new)=@_;
                   2357:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2358:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2359:                         &escape("$old").':'.&escape("$new"),$home);
                   2360:     if ($result eq 'ok') {
                   2361:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2362:             my $oldmeta = $old.'.meta';
                   2363:             my $newmeta = $new.'.meta';
                   2364:             my $metaresult = 
                   2365:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2366: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2367:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2368:             my $sqlresult = 
1.823     albertel 2369:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2370:                                         'portfolio_metadata',$group,
                   2371:                                         'delete');
1.798     raeburn  2372:         }
                   2373:     }
                   2374:     return $result;
1.531     albertel 2375: }
                   2376: 
1.14      www      2377: # ------------------------------------------------------------------------- Log
                   2378: 
                   2379: sub log {
                   2380:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2381:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2382: }
                   2383: 
                   2384: # ------------------------------------------------------------------ Course Log
1.352     www      2385: #
                   2386: # This routine flushes several buffers of non-mission-critical nature
                   2387: #
1.157     www      2388: 
                   2389: sub flushcourselogs {
1.352     www      2390:     &logthis('Flushing log buffers');
                   2391: #
                   2392: # course logs
                   2393: # This is a log of all transactions in a course, which can be used
                   2394: # for data mining purposes
                   2395: #
                   2396: # It also collects the courseid database, which lists last transaction
                   2397: # times and course titles for all courseids
                   2398: #
                   2399:     my %courseidbuffer=();
1.921     raeburn  2400:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2401:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2402: 		          &escape($courselogs{$crsid}),
                   2403: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2404: 	    delete $courselogs{$crsid};
                   2405:         } else {
                   2406:             &logthis('Failed to flush log buffer for '.$crsid);
                   2407:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2408:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2409:                         " exceeded maximum size, deleting.</font>");
                   2410:                delete $courselogs{$crsid};
                   2411:             }
1.352     www      2412:         }
1.920     raeburn  2413:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2414:             'description' => $coursedescrbuf{$crsid},
                   2415:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2416:             'type'        => $coursetypebuf{$crsid},
                   2417:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2418:         };
1.191     harris41 2419:     }
1.352     www      2420: #
                   2421: # Write course id database (reverse lookup) to homeserver of courses 
                   2422: # Is used in pickcourse
                   2423: #
1.840     albertel 2424:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2425:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2426:                                     $courseidbuffer{$crs_home},
                   2427:                                     $crs_home,'timeonly');
1.352     www      2428:     }
                   2429: #
                   2430: # File accesses
                   2431: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2432: #
1.449     matthew  2433:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2434:         if ($entry =~ /___count$/) {
                   2435:             my ($dom,$name);
1.807     albertel 2436:             ($dom,$name,undef)=
1.811     albertel 2437: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2438:             if (! defined($dom) || $dom eq '' || 
                   2439:                 ! defined($name) || $name eq '') {
1.620     albertel 2440:                 my $cid = $env{'request.course.id'};
                   2441:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2442:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2443:             }
1.450     matthew  2444:             my $value = $accesshash{$entry};
                   2445:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2446:             my %temphash=($url => $value);
1.449     matthew  2447:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2448:             if ($result eq 'ok') {
                   2449:                 delete $accesshash{$entry};
                   2450:             } elsif ($result eq 'unknown_cmd') {
                   2451:                 # Target server has old code running on it.
1.450     matthew  2452:                 my %temphash=($entry => $value);
1.449     matthew  2453:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2454:                     delete $accesshash{$entry};
                   2455:                 }
                   2456:             }
                   2457:         } else {
1.811     albertel 2458:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2459:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2460:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2461:                 delete $accesshash{$entry};
                   2462:             }
1.185     www      2463:         }
1.191     harris41 2464:     }
1.352     www      2465: #
                   2466: # Roles
                   2467: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2468: #
1.800     albertel 2469:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2470:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2471: 	    split(/\:/,$entry);
                   2472:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2473:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2474:                 $rudom,$runame) eq 'ok') {
                   2475: 	    delete $userrolehash{$entry};
                   2476:         }
                   2477:     }
1.662     raeburn  2478: #
                   2479: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2480: #
                   2481:     my %domrolebuffer = ();
                   2482:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2483:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2484:         if ($domrolebuffer{$rudom}) {
                   2485:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2486:                       '='.&escape($domainrolehash{$entry});
                   2487:         } else {
                   2488:             $domrolebuffer{$rudom}.=&escape($entry).
                   2489:                       '='.&escape($domainrolehash{$entry});
                   2490:         }
                   2491:         delete $domainrolehash{$entry};
                   2492:     }
                   2493:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2494: 	my %servers = &get_servers($dom,'library');
                   2495: 	foreach my $tryserver (keys(%servers)) {
                   2496: 	    unless (&reply('domroleput:'.$dom.':'.
                   2497: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2498: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2499: 	    }
1.662     raeburn  2500:         }
                   2501:     }
1.186     www      2502:     $dumpcount++;
1.157     www      2503: }
                   2504: 
                   2505: sub courselog {
                   2506:     my $what=shift;
1.158     www      2507:     $what=time.':'.$what;
1.620     albertel 2508:     unless ($env{'request.course.id'}) { return ''; }
                   2509:     $coursedombuf{$env{'request.course.id'}}=
                   2510:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2511:     $coursenumbuf{$env{'request.course.id'}}=
                   2512:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2513:     $coursehombuf{$env{'request.course.id'}}=
                   2514:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2515:     $coursedescrbuf{$env{'request.course.id'}}=
                   2516:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2517:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2518:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2519:     $courseownerbuf{$env{'request.course.id'}}=
                   2520:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2521:     $coursetypebuf{$env{'request.course.id'}}=
                   2522:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2523:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2524: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2525:     } else {
1.620     albertel 2526: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2527:     }
1.620     albertel 2528:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2529: 	&flushcourselogs();
                   2530:     }
1.158     www      2531: }
                   2532: 
                   2533: sub courseacclog {
                   2534:     my $fnsymb=shift;
1.620     albertel 2535:     unless ($env{'request.course.id'}) { return ''; }
                   2536:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2537:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2538:         $what.=':POST';
1.583     matthew  2539:         # FIXME: Probably ought to escape things....
1.800     albertel 2540: 	foreach my $key (keys(%env)) {
                   2541:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2542:                 my $formitem = $1;
                   2543:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2544:                     $what.=':'.$formitem.'='.$env{$key};
                   2545:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2546:                     $what.=':'.$formitem.'='.$env{$key};
                   2547:                 }
1.158     www      2548:             }
1.191     harris41 2549:         }
1.583     matthew  2550:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2551:         # FIXME: We should not be depending on a form parameter that someone
                   2552:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2553:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2554:             $what.= ':POST';
                   2555:             # FIXME: Probably ought to escape things....
                   2556:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2557:                                  'crsdiscuss') {
1.620     albertel 2558:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2559:             }
                   2560:         }
1.158     www      2561:     }
                   2562:     &courselog($what);
1.149     www      2563: }
                   2564: 
1.185     www      2565: sub countacc {
                   2566:     my $url=&declutter(shift);
1.458     matthew  2567:     return if (! defined($url) || $url eq '');
1.620     albertel 2568:     unless ($env{'request.course.id'}) { return ''; }
                   2569:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2570:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2571:     $accesshash{$key}++;
1.185     www      2572: }
1.349     www      2573: 
1.361     www      2574: sub linklog {
                   2575:     my ($from,$to)=@_;
                   2576:     $from=&declutter($from);
                   2577:     $to=&declutter($to);
                   2578:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2579:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2580: }
                   2581:   
1.349     www      2582: sub userrolelog {
                   2583:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2584:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2585:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2586:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2587:         ($trole=~/^ta/)) {
1.350     www      2588:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2589:        $userrolehash
                   2590:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2591:                     =$tend.':'.$tstart;
1.662     raeburn  2592:     }
1.898     albertel 2593:     if (($env{'request.role'} =~ /dc\./) &&
                   2594: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2595: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2596: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2597:        $userrolehash
                   2598:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2599:                     =$tend.':'.$tstart;
                   2600:     }
1.662     raeburn  2601:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2602:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2603:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2604:         ($trole=~/^sc/)) {
                   2605:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2606:        $domainrolehash
                   2607:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2608:                     = $tend.':'.$tstart;
                   2609:     }
1.351     www      2610: }
                   2611: 
1.957     raeburn  2612: sub courserolelog {
                   2613:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2614:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2615:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2616:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2617:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2618:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2619:             my $cdom = $1;
                   2620:             my $cnum = $2;
                   2621:             my $sec = $3;
                   2622:             my $namespace = 'rolelog';
                   2623:             my %storehash = (
                   2624:                                role    => $trole,
                   2625:                                start   => $tstart,
                   2626:                                end     => $tend,
                   2627:                                selfenroll => $selfenroll,
                   2628:                                context    => $context,
                   2629:                             );
                   2630:             if ($trole eq 'gr') {
                   2631:                 $namespace = 'groupslog';
                   2632:                 $storehash{'group'} = $sec;
                   2633:             } else {
                   2634:                 $storehash{'section'} = $sec;
                   2635:             }
                   2636:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2637:         }
                   2638:     }
                   2639:     return;
                   2640: }
                   2641: 
1.351     www      2642: sub get_course_adv_roles {
1.948     raeburn  2643:     my ($cid,$codes) = @_;
1.620     albertel 2644:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2645:     my %coursehash=&coursedescription($cid);
1.470     www      2646:     my %nothide=();
1.800     albertel 2647:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2648:         if ($user !~ /:/) {
                   2649: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2650:         } else {
                   2651:             $nothide{$user}=1;
                   2652:         }
1.470     www      2653:     }
1.351     www      2654:     my %returnhash=();
                   2655:     my %dumphash=
                   2656:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2657:     my $now=time;
1.800     albertel 2658:     foreach my $entry (keys %dumphash) {
                   2659: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2660:         if (($tstart) && ($tstart<0)) { next; }
                   2661:         if (($tend) && ($tend<$now)) { next; }
                   2662:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2663:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2664: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2665: 	if ((&privileged($username,$domain)) && 
                   2666: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2667: 	if ($role eq 'cr') { next; }
1.948     raeburn  2668:         if ($codes) {
                   2669:             if ($section) { $role .= ':'.$section; }
                   2670:             if ($returnhash{$role}) {
                   2671:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2672:             } else {
                   2673:                 $returnhash{$role}=$username.':'.$domain;
                   2674:             }
1.351     www      2675:         } else {
1.948     raeburn  2676:             my $key=&plaintext($role);
1.973     bisitz   2677:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2678:             if ($returnhash{$key}) {
                   2679: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2680:             } else {
                   2681:                 $returnhash{$key}=$username.':'.$domain;
                   2682:             }
1.351     www      2683:         }
1.948     raeburn  2684:     }
1.400     www      2685:     return %returnhash;
                   2686: }
                   2687: 
                   2688: sub get_my_roles {
1.937     raeburn  2689:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2690:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2691:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2692:     my (%dumphash,%nothide);
1.858     raeburn  2693:     if ($context eq 'userroles') { 
                   2694:         %dumphash = &dump('roles',$udom,$uname);
                   2695:     } else {
                   2696:         %dumphash=
1.400     www      2697:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2698:         if ($hidepriv) {
                   2699:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2700:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2701:                 if ($user !~ /:/) {
                   2702:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2703:                 } else {
                   2704:                     $nothide{$user} = 1;
                   2705:                 }
                   2706:             }
                   2707:         }
1.858     raeburn  2708:     }
1.400     www      2709:     my %returnhash=();
                   2710:     my $now=time;
1.800     albertel 2711:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2712:         my ($role,$tend,$tstart);
                   2713:         if ($context eq 'userroles') {
                   2714: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2715:         } else {
                   2716:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2717:         }
1.400     www      2718:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2719:         my $status = 'active';
1.939     raeburn  2720:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2721:             $status = 'previous';
                   2722:         } 
                   2723:         if (($tstart) && ($now<$tstart)) {
                   2724:             $status = 'future';
                   2725:         }
                   2726:         if (ref($types) eq 'ARRAY') {
                   2727:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2728:                 next;
                   2729:             } 
                   2730:         } else {
                   2731:             if ($status ne 'active') {
                   2732:                 next;
                   2733:             }
                   2734:         }
1.867     raeburn  2735:         my ($rolecode,$username,$domain,$section,$area);
                   2736:         if ($context eq 'userroles') {
                   2737:             ($area,$rolecode) = split(/_/,$entry);
                   2738:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2739:         } else {
                   2740:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2741:         }
1.832     raeburn  2742:         if (ref($roledoms) eq 'ARRAY') {
                   2743:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2744:                 next;
                   2745:             }
                   2746:         }
                   2747:         if (ref($roles) eq 'ARRAY') {
                   2748:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2749:                 if ($role =~ /^cr\//) {
                   2750:                     if (!grep(/^cr$/,@{$roles})) {
                   2751:                         next;
                   2752:                     }
                   2753:                 } else {
                   2754:                     next;
                   2755:                 }
1.832     raeburn  2756:             }
1.867     raeburn  2757:         }
1.937     raeburn  2758:         if ($hidepriv) {
                   2759:             if ((&privileged($username,$domain)) &&
                   2760:                 (!$nothide{$username.':'.$domain})) { 
                   2761:                 next;
                   2762:             }
                   2763:         }
1.933     raeburn  2764:         if ($withsec) {
                   2765:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2766:                 $tstart.':'.$tend;
                   2767:         } else {
                   2768:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2769:         }
1.832     raeburn  2770:     }
1.373     www      2771:     return %returnhash;
1.399     www      2772: }
                   2773: 
                   2774: # ----------------------------------------------------- Frontpage Announcements
                   2775: #
                   2776: #
                   2777: 
                   2778: sub postannounce {
                   2779:     my ($server,$text)=@_;
1.844     albertel 2780:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2781:     unless ($text=~/\w/) { $text=''; }
                   2782:     return &reply('setannounce:'.&escape($text),$server);
                   2783: }
                   2784: 
                   2785: sub getannounce {
1.448     albertel 2786: 
                   2787:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2788: 	my $announcement='';
1.800     albertel 2789: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2790: 	close($fh);
1.399     www      2791: 	if ($announcement=~/\w/) { 
                   2792: 	    return 
                   2793:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2794:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2795: 	} else {
                   2796: 	    return '';
                   2797: 	}
                   2798:     } else {
                   2799: 	return '';
                   2800:     }
1.351     www      2801: }
1.353     www      2802: 
                   2803: # ---------------------------------------------------------- Course ID routines
                   2804: # Deal with domain's nohist_courseid.db files
                   2805: #
                   2806: 
                   2807: sub courseidput {
1.921     raeburn  2808:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2809:     my $outcome;
                   2810:     if ($caller eq 'timeonly') {
                   2811:         my $cids = '';
                   2812:         foreach my $item (keys(%$storehash)) {
                   2813:             $cids.=&escape($item).'&';
                   2814:         }
                   2815:         $cids=~s/\&$//;
                   2816:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2817:                           $coursehome);       
                   2818:     } else {
                   2819:         my $items = '';
                   2820:         foreach my $item (keys(%$storehash)) {
                   2821:             $items.= &escape($item).'='.
                   2822:                      &freeze_escape($$storehash{$item}).'&';
                   2823:         }
                   2824:         $items=~s/\&$//;
                   2825:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2826:                           $coursehome);
1.918     raeburn  2827:     }
                   2828:     if ($outcome eq 'unknown_cmd') {
                   2829:         my $what;
                   2830:         foreach my $cid (keys(%$storehash)) {
                   2831:             $what .= &escape($cid).'=';
1.921     raeburn  2832:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2833:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2834:             }
                   2835:             $what =~ s/\:$/&/;
                   2836:         }
                   2837:         $what =~ s/\&$//;  
                   2838:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2839:     } else {
                   2840:         return $outcome;
                   2841:     }
1.353     www      2842: }
                   2843: 
                   2844: sub courseiddump {
1.921     raeburn  2845:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2846:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2847:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2848:     my $as_hash = 1;
                   2849:     my %returnhash;
                   2850:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2851:     my %libserv = &all_library();
                   2852:     foreach my $tryserver (keys(%libserv)) {
                   2853:         if ( (  $hostidflag == 1 
                   2854: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2855: 	     || (!defined($hostidflag)) ) {
                   2856: 
1.918     raeburn  2857: 	    if (($domfilter eq '') ||
                   2858: 		(&host_domain($tryserver) eq $domfilter)) {
                   2859:                 my $rep = 
                   2860:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2861:                          $sincefilter.':'.&escape($descfilter).':'.
                   2862:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2863:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2864:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2865:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2866:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2867:                 my @pairs=split(/\&/,$rep);
                   2868:                 foreach my $item (@pairs) {
                   2869:                     my ($key,$value)=split(/\=/,$item,2);
                   2870:                     $key = &unescape($key);
                   2871:                     next if ($key =~ /^error: 2 /);
                   2872:                     my $result = &thaw_unescape($value);
                   2873:                     if (ref($result) eq 'HASH') {
                   2874:                         $returnhash{$key}=$result;
                   2875:                     } else {
1.921     raeburn  2876:                         my @responses = split(/:/,$value);
                   2877:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2878:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2879:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2880:                         }
                   2881:                     } 
1.353     www      2882:                 }
                   2883:             }
                   2884:         }
                   2885:     }
                   2886:     return %returnhash;
                   2887: }
                   2888: 
1.658     raeburn  2889: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2890: 
                   2891: sub dcmailput {
1.685     raeburn  2892:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2893:     my $status = &Apache::lonnet::critical(
1.740     www      2894:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2895:        &escape($message),$server);
1.662     raeburn  2896:     return $status;
                   2897: }
                   2898: 
1.658     raeburn  2899: sub dcmaildump {
                   2900:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2901:     my %returnhash=();
1.846     albertel 2902: 
                   2903:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2904:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2905:                                                          &escape($enddate).':';
                   2906: 	my @esc_senders=map { &escape($_)} @$senders;
                   2907: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2908: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2909:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2910:             if (($key) && ($value)) {
                   2911:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2912:             }
                   2913:         }
                   2914:     }
                   2915:     return %returnhash;
                   2916: }
1.662     raeburn  2917: # ---------------------------------------------------------- Domain roles
                   2918: 
                   2919: sub get_domain_roles {
                   2920:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2921:     if (undef($startdate) || $startdate eq '') {
                   2922:         $startdate = '.';
                   2923:     }
                   2924:     if (undef($enddate) || $enddate eq '') {
                   2925:         $enddate = '.';
                   2926:     }
1.922     raeburn  2927:     my $rolelist;
                   2928:     if (ref($roles) eq 'ARRAY') {
                   2929:         $rolelist = join(':',@{$roles});
                   2930:     }
1.662     raeburn  2931:     my %personnel = ();
1.841     albertel 2932: 
                   2933:     my %servers = &get_servers($dom,'library');
                   2934:     foreach my $tryserver (keys(%servers)) {
                   2935: 	%{$personnel{$tryserver}}=();
                   2936: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2937: 					    &escape($startdate).':'.
                   2938: 					    &escape($enddate).':'.
                   2939: 					    &escape($rolelist), $tryserver))) {
                   2940: 	    my ($key,$value) = split(/\=/,$line,2);
                   2941: 	    if (($key) && ($value)) {
                   2942: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2943: 	    }
                   2944: 	}
1.662     raeburn  2945:     }
                   2946:     return %personnel;
                   2947: }
1.658     raeburn  2948: 
1.149     www      2949: # ----------------------------------------------------------- Check out an item
                   2950: 
1.504     albertel 2951: sub get_first_access {
                   2952:     my ($type,$argsymb)=@_;
1.790     albertel 2953:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2954:     if ($argsymb) { $symb=$argsymb; }
                   2955:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2956:     if ($type eq 'course') {
                   2957: 	$res='course';
                   2958:     } elsif ($type eq 'map') {
1.588     albertel 2959: 	$res=&symbread($map);
                   2960:     } else {
                   2961: 	$res=$symb;
                   2962:     }
                   2963:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2964:     return $times{"$courseid\0$res"};
1.504     albertel 2965: }
                   2966: 
                   2967: sub set_first_access {
                   2968:     my ($type)=@_;
1.790     albertel 2969:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2970:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2971:     if ($type eq 'course') {
                   2972: 	$res='course';
                   2973:     } elsif ($type eq 'map') {
1.588     albertel 2974: 	$res=&symbread($map);
                   2975:     } else {
                   2976: 	$res=$symb;
                   2977:     }
                   2978:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2979:     if (!$firstaccess) {
1.588     albertel 2980: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2981:     }
                   2982:     return 'already_set';
1.504     albertel 2983: }
                   2984: 
1.149     www      2985: sub checkout {
                   2986:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2987:     my $now=time;
                   2988:     my $lonhost=$perlvar{'lonHostID'};
                   2989:     my $infostr=&escape(
1.234     www      2990:                  'CHECKOUTTOKEN&'.
1.149     www      2991:                  $tuname.'&'.
                   2992:                  $tudom.'&'.
                   2993:                  $tcrsid.'&'.
                   2994:                  $symb.'&'.
                   2995: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2996:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2997:     if ($token=~/^error\:/) { 
1.672     albertel 2998:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2999:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3000:                  "</font>");
                   3001:         return ''; 
                   3002:     }
                   3003: 
1.149     www      3004:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3005:     $token=~tr/a-z/A-Z/;
                   3006: 
1.153     www      3007:     my %infohash=('resource.0.outtoken' => $token,
                   3008:                   'resource.0.checkouttime' => $now,
                   3009:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3010: 
                   3011:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3012:        return '';
1.151     www      3013:     } else {
1.672     albertel 3014:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3015:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3016:                  "</font>");
1.149     www      3017:     }    
                   3018: 
                   3019:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3020:                          &escape('Checkout '.$infostr.' - '.
                   3021:                                                  $token)) ne 'ok') {
                   3022: 	return '';
1.151     www      3023:     } else {
1.672     albertel 3024:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3025:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3026:                  "</font>");
1.149     www      3027:     }
1.151     www      3028:     return $token;
1.149     www      3029: }
                   3030: 
                   3031: # ------------------------------------------------------------ Check in an item
                   3032: 
                   3033: sub checkin {
                   3034:     my $token=shift;
1.150     www      3035:     my $now=time;
                   3036:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3037:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3038:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3039:     $dtoken=~s/\W/\_/g;
1.234     www      3040:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3041:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3042: 
1.154     www      3043:     unless (($tuname) && ($tudom)) {
                   3044:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3045:         return '';
                   3046:     }
                   3047:     
                   3048:     unless (&allowed('mgr',$tcrsid)) {
                   3049:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3050:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3051:         return '';
                   3052:     }
                   3053: 
1.153     www      3054:     my %infohash=('resource.0.intoken' => $token,
                   3055:                   'resource.0.checkintime' => $now,
                   3056:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3057: 
                   3058:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3059:        return '';
                   3060:     }    
                   3061: 
                   3062:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3063:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3064: 	return '';
                   3065:     }
                   3066: 
                   3067:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3068: }
                   3069: 
                   3070: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3071: 
                   3072: sub expirespread {
                   3073:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3074:     my $cid=$env{'request.course.id'}; 
1.110     www      3075:     if ($cid) {
                   3076:        my $now=time;
                   3077:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3078:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3079:                             $env{'course.'.$cid.'.num'}.
1.110     www      3080: 	        	    ':nohist_expirationdates:'.
                   3081:                             &escape($key).'='.$now,
1.620     albertel 3082:                             $env{'course.'.$cid.'.home'})
1.110     www      3083:     }
                   3084:     return 'ok';
1.14      www      3085: }
                   3086: 
1.109     www      3087: # ----------------------------------------------------- Devalidate Spreadsheets
                   3088: 
                   3089: sub devalidate {
1.325     www      3090:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3091:     my $cid=$env{'request.course.id'}; 
1.109     www      3092:     if ($cid) {
1.391     matthew  3093:         # delete the stored spreadsheets for
                   3094:         # - the student level sheet of this user in course's homespace
                   3095:         # - the assessment level sheet for this resource 
                   3096:         #   for this user in user's homespace
1.553     albertel 3097: 	# - current conditional state info
1.325     www      3098: 	my $key=$uname.':'.$udom.':';
1.109     www      3099:         my $status=
1.299     matthew  3100: 	    &del('nohist_calculatedsheets',
1.391     matthew  3101: 		 [$key.'studentcalc:'],
1.620     albertel 3102: 		 $env{'course.'.$cid.'.domain'},
                   3103: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3104: 		.' '.
                   3105: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3106: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3107:         unless ($status eq 'ok ok') {
                   3108:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3109:                     $uname.' at '.$udom.' for '.
1.109     www      3110: 		    $symb.': '.$status);
1.133     albertel 3111:         }
1.553     albertel 3112: 	&delenv('user.state.'.$cid);
1.109     www      3113:     }
                   3114: }
                   3115: 
1.265     albertel 3116: sub get_scalar {
                   3117:     my ($string,$end) = @_;
                   3118:     my $value;
                   3119:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3120: 	$value = $1;
                   3121:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3122: 	$value = $1;
                   3123:     }
                   3124:     return &unescape($value);
                   3125: }
                   3126: 
                   3127: sub array2str {
                   3128:   my (@array) = @_;
                   3129:   my $result=&arrayref2str(\@array);
                   3130:   $result=~s/^__ARRAY_REF__//;
                   3131:   $result=~s/__END_ARRAY_REF__$//;
                   3132:   return $result;
                   3133: }
                   3134: 
1.204     albertel 3135: sub arrayref2str {
                   3136:   my ($arrayref) = @_;
1.265     albertel 3137:   my $result='__ARRAY_REF__';
1.204     albertel 3138:   foreach my $elem (@$arrayref) {
1.265     albertel 3139:     if(ref($elem) eq 'ARRAY') {
                   3140:       $result.=&arrayref2str($elem).'&';
                   3141:     } elsif(ref($elem) eq 'HASH') {
                   3142:       $result.=&hashref2str($elem).'&';
                   3143:     } elsif(ref($elem)) {
                   3144:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3145:     } else {
                   3146:       $result.=&escape($elem).'&';
                   3147:     }
                   3148:   }
                   3149:   $result=~s/\&$//;
1.265     albertel 3150:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3151:   return $result;
                   3152: }
                   3153: 
1.168     albertel 3154: sub hash2str {
1.204     albertel 3155:   my (%hash) = @_;
                   3156:   my $result=&hashref2str(\%hash);
1.265     albertel 3157:   $result=~s/^__HASH_REF__//;
                   3158:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3159:   return $result;
                   3160: }
                   3161: 
                   3162: sub hashref2str {
                   3163:   my ($hashref)=@_;
1.265     albertel 3164:   my $result='__HASH_REF__';
1.800     albertel 3165:   foreach my $key (sort(keys(%$hashref))) {
                   3166:     if (ref($key) eq 'ARRAY') {
                   3167:       $result.=&arrayref2str($key).'=';
                   3168:     } elsif (ref($key) eq 'HASH') {
                   3169:       $result.=&hashref2str($key).'=';
                   3170:     } elsif (ref($key)) {
1.265     albertel 3171:       $result.='=';
1.800     albertel 3172:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3173:     } else {
1.800     albertel 3174: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3175:     }
                   3176: 
1.800     albertel 3177:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3178:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3179:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3180:       $result.=&hashref2str($hashref->{$key}).'&';
                   3181:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3182:        $result.='&';
1.800     albertel 3183:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3184:     } else {
1.800     albertel 3185:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3186:     }
                   3187:   }
1.168     albertel 3188:   $result=~s/\&$//;
1.265     albertel 3189:   $result .= '__END_HASH_REF__';
1.168     albertel 3190:   return $result;
                   3191: }
                   3192: 
                   3193: sub str2hash {
1.265     albertel 3194:     my ($string)=@_;
                   3195:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3196:     return %$hash;
                   3197: }
                   3198: 
                   3199: sub str2hashref {
1.168     albertel 3200:   my ($string) = @_;
1.265     albertel 3201: 
                   3202:   my %hash;
                   3203: 
                   3204:   if($string !~ /^__HASH_REF__/) {
                   3205:       if (! ($string eq '' || !defined($string))) {
                   3206: 	  $hash{'error'}='Not hash reference';
                   3207:       }
                   3208:       return (\%hash, $string);
                   3209:   }
                   3210: 
                   3211:   $string =~ s/^__HASH_REF__//;
                   3212: 
                   3213:   while($string !~ /^__END_HASH_REF__/) {
                   3214:       #key
                   3215:       my $key='';
                   3216:       if($string =~ /^__HASH_REF__/) {
                   3217:           ($key, $string)=&str2hashref($string);
                   3218:           if(defined($key->{'error'})) {
                   3219:               $hash{'error'}='Bad data';
                   3220:               return (\%hash, $string);
                   3221:           }
                   3222:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3223:           ($key, $string)=&str2arrayref($string);
                   3224:           if($key->[0] eq 'Array reference error') {
                   3225:               $hash{'error'}='Bad data';
                   3226:               return (\%hash, $string);
                   3227:           }
                   3228:       } else {
                   3229:           $string =~ s/^(.*?)=//;
1.267     albertel 3230: 	  $key=&unescape($1);
1.265     albertel 3231:       }
                   3232:       $string =~ s/^=//;
                   3233: 
                   3234:       #value
                   3235:       my $value='';
                   3236:       if($string =~ /^__HASH_REF__/) {
                   3237:           ($value, $string)=&str2hashref($string);
                   3238:           if(defined($value->{'error'})) {
                   3239:               $hash{'error'}='Bad data';
                   3240:               return (\%hash, $string);
                   3241:           }
                   3242:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3243:           ($value, $string)=&str2arrayref($string);
                   3244:           if($value->[0] eq 'Array reference error') {
                   3245:               $hash{'error'}='Bad data';
                   3246:               return (\%hash, $string);
                   3247:           }
                   3248:       } else {
                   3249: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3250:       }
                   3251:       $string =~ s/^&//;
                   3252: 
                   3253:       $hash{$key}=$value;
1.204     albertel 3254:   }
1.265     albertel 3255: 
                   3256:   $string =~ s/^__END_HASH_REF__//;
                   3257: 
                   3258:   return (\%hash, $string);
1.204     albertel 3259: }
                   3260: 
                   3261: sub str2array {
1.265     albertel 3262:     my ($string)=@_;
                   3263:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3264:     return @$array;
                   3265: }
                   3266: 
                   3267: sub str2arrayref {
1.204     albertel 3268:   my ($string) = @_;
1.265     albertel 3269:   my @array;
                   3270: 
                   3271:   if($string !~ /^__ARRAY_REF__/) {
                   3272:       if (! ($string eq '' || !defined($string))) {
                   3273: 	  $array[0]='Array reference error';
                   3274:       }
                   3275:       return (\@array, $string);
                   3276:   }
                   3277: 
                   3278:   $string =~ s/^__ARRAY_REF__//;
                   3279: 
                   3280:   while($string !~ /^__END_ARRAY_REF__/) {
                   3281:       my $value='';
                   3282:       if($string =~ /^__HASH_REF__/) {
                   3283:           ($value, $string)=&str2hashref($string);
                   3284:           if(defined($value->{'error'})) {
                   3285:               $array[0] ='Array reference error';
                   3286:               return (\@array, $string);
                   3287:           }
                   3288:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3289:           ($value, $string)=&str2arrayref($string);
                   3290:           if($value->[0] eq 'Array reference error') {
                   3291:               $array[0] ='Array reference error';
                   3292:               return (\@array, $string);
                   3293:           }
                   3294:       } else {
                   3295: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3296:       }
                   3297:       $string =~ s/^&//;
                   3298: 
                   3299:       push(@array, $value);
1.191     harris41 3300:   }
1.265     albertel 3301: 
                   3302:   $string =~ s/^__END_ARRAY_REF__//;
                   3303: 
                   3304:   return (\@array, $string);
1.168     albertel 3305: }
                   3306: 
1.167     albertel 3307: # -------------------------------------------------------------------Temp Store
                   3308: 
1.168     albertel 3309: sub tmpreset {
                   3310:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3311:   if (!$symb) {
                   3312:     $symb=&symbread();
1.620     albertel 3313:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3314:   }
                   3315:   $symb=escape($symb);
                   3316: 
1.620     albertel 3317:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3318:   $namespace=~s/\//\_/g;
                   3319:   $namespace=~s/\W//g;
                   3320: 
1.620     albertel 3321:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3322:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3323:   if ($domain eq 'public' && $stuname eq 'public') {
                   3324:       $stuname=$ENV{'REMOTE_ADDR'};
                   3325:   }
1.168     albertel 3326:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3327:   my %hash;
                   3328:   if (tie(%hash,'GDBM_File',
                   3329: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3330: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3331:     foreach my $key (keys %hash) {
1.180     albertel 3332:       if ($key=~ /:$symb/) {
1.168     albertel 3333: 	delete($hash{$key});
                   3334:       }
                   3335:     }
                   3336:   }
                   3337: }
                   3338: 
1.167     albertel 3339: sub tmpstore {
1.168     albertel 3340:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3341: 
                   3342:   if (!$symb) {
                   3343:     $symb=&symbread();
1.620     albertel 3344:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3345:   }
                   3346:   $symb=escape($symb);
                   3347: 
                   3348:   if (!$namespace) {
                   3349:     # I don't think we would ever want to store this for a course.
                   3350:     # it seems this will only be used if we don't have a course.
1.620     albertel 3351:     #$namespace=$env{'request.course.id'};
1.168     albertel 3352:     #if (!$namespace) {
1.620     albertel 3353:       $namespace=$env{'request.state'};
1.168     albertel 3354:     #}
                   3355:   }
                   3356:   $namespace=~s/\//\_/g;
                   3357:   $namespace=~s/\W//g;
1.620     albertel 3358:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3359:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3360:   if ($domain eq 'public' && $stuname eq 'public') {
                   3361:       $stuname=$ENV{'REMOTE_ADDR'};
                   3362:   }
1.168     albertel 3363:   my $now=time;
                   3364:   my %hash;
                   3365:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3366:   if (tie(%hash,'GDBM_File',
                   3367: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3368: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3369:     $hash{"version:$symb"}++;
                   3370:     my $version=$hash{"version:$symb"};
                   3371:     my $allkeys=''; 
                   3372:     foreach my $key (keys(%$storehash)) {
                   3373:       $allkeys.=$key.':';
1.591     albertel 3374:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3375:     }
                   3376:     $hash{"$version:$symb:timestamp"}=$now;
                   3377:     $allkeys.='timestamp';
                   3378:     $hash{"$version:keys:$symb"}=$allkeys;
                   3379:     if (untie(%hash)) {
                   3380:       return 'ok';
                   3381:     } else {
                   3382:       return "error:$!";
                   3383:     }
                   3384:   } else {
                   3385:     return "error:$!";
                   3386:   }
                   3387: }
1.167     albertel 3388: 
1.168     albertel 3389: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3390: 
1.168     albertel 3391: sub tmprestore {
                   3392:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3393: 
1.168     albertel 3394:   if (!$symb) {
                   3395:     $symb=&symbread();
1.620     albertel 3396:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3397:   }
                   3398:   $symb=escape($symb);
                   3399: 
1.620     albertel 3400:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3401: 
1.620     albertel 3402:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3403:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3404:   if ($domain eq 'public' && $stuname eq 'public') {
                   3405:       $stuname=$ENV{'REMOTE_ADDR'};
                   3406:   }
1.168     albertel 3407:   my %returnhash;
                   3408:   $namespace=~s/\//\_/g;
                   3409:   $namespace=~s/\W//g;
                   3410:   my %hash;
                   3411:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3412:   if (tie(%hash,'GDBM_File',
                   3413: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3414: 	  &GDBM_READER(),0640)) {
1.168     albertel 3415:     my $version=$hash{"version:$symb"};
                   3416:     $returnhash{'version'}=$version;
                   3417:     my $scope;
                   3418:     for ($scope=1;$scope<=$version;$scope++) {
                   3419:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3420:       my @keys=split(/:/,$vkeys);
                   3421:       my $key;
                   3422:       $returnhash{"$scope:keys"}=$vkeys;
                   3423:       foreach $key (@keys) {
1.591     albertel 3424: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3425: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3426:       }
                   3427:     }
1.168     albertel 3428:     if (!(untie(%hash))) {
                   3429:       return "error:$!";
                   3430:     }
                   3431:   } else {
                   3432:     return "error:$!";
                   3433:   }
                   3434:   return %returnhash;
1.167     albertel 3435: }
                   3436: 
1.9       www      3437: # ----------------------------------------------------------------------- Store
                   3438: 
                   3439: sub store {
1.124     www      3440:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3441:     my $home='';
                   3442: 
1.168     albertel 3443:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3444: 
1.213     www      3445:     $symb=&symbclean($symb);
1.122     albertel 3446:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3447: 
1.620     albertel 3448:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3449:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3450: 
                   3451:     &devalidate($symb,$stuname,$domain);
1.109     www      3452: 
                   3453:     $symb=escape($symb);
1.187     www      3454:     if (!$namespace) { 
1.620     albertel 3455:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3456:           return ''; 
                   3457:        } 
                   3458:     }
1.620     albertel 3459:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3460: 
                   3461:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3462:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3463: 
1.12      www      3464:     my $namevalue='';
1.800     albertel 3465:     foreach my $key (keys(%$storehash)) {
                   3466:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3467:     }
1.12      www      3468:     $namevalue=~s/\&$//;
1.187     www      3469:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3470:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3471: }
                   3472: 
1.47      www      3473: # -------------------------------------------------------------- Critical Store
                   3474: 
                   3475: sub cstore {
1.124     www      3476:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3477:     my $home='';
                   3478: 
1.168     albertel 3479:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3480: 
1.213     www      3481:     $symb=&symbclean($symb);
1.122     albertel 3482:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3483: 
1.620     albertel 3484:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3485:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3486: 
                   3487:     &devalidate($symb,$stuname,$domain);
1.109     www      3488: 
                   3489:     $symb=escape($symb);
1.187     www      3490:     if (!$namespace) { 
1.620     albertel 3491:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3492:           return ''; 
                   3493:        } 
                   3494:     }
1.620     albertel 3495:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3496: 
                   3497:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3498:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3499: 
1.47      www      3500:     my $namevalue='';
1.800     albertel 3501:     foreach my $key (keys(%$storehash)) {
                   3502:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3503:     }
1.47      www      3504:     $namevalue=~s/\&$//;
1.187     www      3505:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3506:     return critical
                   3507:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3508: }
                   3509: 
1.9       www      3510: # --------------------------------------------------------------------- Restore
                   3511: 
                   3512: sub restore {
1.124     www      3513:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3514:     my $home='';
                   3515: 
1.168     albertel 3516:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3517: 
1.122     albertel 3518:     if (!$symb) {
                   3519:       unless ($symb=escape(&symbread())) { return ''; }
                   3520:     } else {
1.213     www      3521:       $symb=&escape(&symbclean($symb));
1.122     albertel 3522:     }
1.188     www      3523:     if (!$namespace) { 
1.620     albertel 3524:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3525:           return ''; 
                   3526:        } 
                   3527:     }
1.620     albertel 3528:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3529:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3530:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3531:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3532: 
1.12      www      3533:     my %returnhash=();
1.800     albertel 3534:     foreach my $line (split(/\&/,$answer)) {
                   3535: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3536:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3537:     }
1.75      www      3538:     my $version;
                   3539:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3540:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3541:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3542:        }
1.75      www      3543:     }
1.13      www      3544:     return %returnhash;
1.34      www      3545: }
                   3546: 
                   3547: # ---------------------------------------------------------- Course Description
                   3548: 
                   3549: sub coursedescription {
1.731     albertel 3550:     my ($courseid,$args)=@_;
1.34      www      3551:     $courseid=~s/^\///;
1.49      www      3552:     $courseid=~s/\_/\//g;
1.34      www      3553:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3554:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3555:     my $normalid=$cdomain.'_'.$cnum;
                   3556:     # need to always cache even if we get errors otherwise we keep 
                   3557:     # trying and trying and trying to get the course description.
                   3558:     my %envhash=();
                   3559:     my %returnhash=();
1.731     albertel 3560:     
                   3561:     my $expiretime=600;
                   3562:     if ($env{'request.course.id'} eq $normalid) {
                   3563: 	$expiretime=120;
                   3564:     }
                   3565: 
                   3566:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3567:     if (!$args->{'freshen_cache'}
                   3568: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3569: 	foreach my $key (keys(%env)) {
                   3570: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3571: 	    my ($setting) = $1;
                   3572: 	    $returnhash{$setting} = $env{$key};
                   3573: 	}
                   3574: 	return %returnhash;
                   3575:     }
                   3576: 
                   3577:     # get the data agin
                   3578:     if (!$args->{'one_time'}) {
                   3579: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3580:     }
1.811     albertel 3581: 
1.34      www      3582:     if ($chome ne 'no_host') {
1.302     albertel 3583:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3584:        if (!exists($returnhash{'con_lost'})) {
                   3585:            $returnhash{'home'}= $chome;
                   3586: 	   $returnhash{'domain'} = $cdomain;
                   3587: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3588:            if (!defined($returnhash{'type'})) {
                   3589:                $returnhash{'type'} = 'Course';
                   3590:            }
1.130     albertel 3591:            while (my ($name,$value) = each %returnhash) {
1.53      www      3592:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3593:            }
1.270     www      3594:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3595:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3596: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3597:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3598:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3599:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3600:        }
                   3601:     }
1.731     albertel 3602:     if (!$args->{'one_time'}) {
1.949     raeburn  3603: 	&appenv(\%envhash);
1.731     albertel 3604:     }
1.302     albertel 3605:     return %returnhash;
1.461     www      3606: }
                   3607: 
                   3608: # -------------------------------------------------See if a user is privileged
                   3609: 
                   3610: sub privileged {
                   3611:     my ($username,$domain)=@_;
                   3612:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3613: 			&homeserver($username,$domain));
                   3614:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3615:     my $now=time;
                   3616:     if ($rolesdump ne '') {
1.800     albertel 3617:         foreach my $entry (split(/&/,$rolesdump)) {
                   3618: 	    if ($entry!~/^rolesdef_/) {
                   3619: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3620: 		$area=~s/\_\w\w$//;
                   3621: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3622: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3623: 		    my $active=1;
                   3624: 		    if ($tend) {
                   3625: 			if ($tend<$now) { $active=0; }
                   3626: 		    }
                   3627: 		    if ($tstart) {
                   3628: 			if ($tstart>$now) { $active=0; }
                   3629: 		    }
                   3630: 		    if ($active) { return 1; }
                   3631: 		}
                   3632: 	    }
                   3633: 	}
                   3634:     }
                   3635:     return 0;
1.9       www      3636: }
1.1       albertel 3637: 
1.103     harris41 3638: # -------------------------------------------------------- Get user privileges
1.11      www      3639: 
                   3640: sub rolesinit {
                   3641:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3642:     my %userroles;
1.11      www      3643:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3644:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3645:     my %allroles=();
1.678     raeburn  3646:     my %allgroups=();   
1.11      www      3647:     my $now=time;
1.966     raeburn  3648:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3649:     my $group_privs;
1.11      www      3650: 
                   3651:     if ($rolesdump ne '') {
1.800     albertel 3652:         foreach my $entry (split(/&/,$rolesdump)) {
                   3653: 	  if ($entry!~/^rolesdef_/) {
                   3654:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3655: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3656:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3657: 	    if ($role=~/^cr/) { 
1.807     albertel 3658: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3659: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3660: 		    ($tend,$tstart)=split('_',$trest);
                   3661: 		} else {
                   3662: 		    $trole=$role;
                   3663: 		}
1.678     raeburn  3664:             } elsif ($role =~ m|^gr/|) {
                   3665:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3666:                 ($trole,$group_privs) = split(/\//,$trole);
                   3667:                 $group_privs = &unescape($group_privs);
1.587     albertel 3668: 	    } else {
                   3669: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3670: 	    }
1.743     albertel 3671: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3672: 					 $username);
                   3673: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3674:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3675:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3676:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3677: 		my $spec=$trole.'.'.$area;
                   3678: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3679: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3680:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3681:                 } elsif ($trole eq 'gr') {
                   3682:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3683: 		} else {
1.567     raeburn  3684:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3685: 		}
1.12      www      3686:             }
1.662     raeburn  3687:           }
1.191     harris41 3688:         }
1.743     albertel 3689:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3690:         $userroles{'user.adv'}    = $adv;
                   3691: 	$userroles{'user.author'} = $author;
1.620     albertel 3692:         $env{'user.adv'}=$adv;
1.11      www      3693:     }
1.743     albertel 3694:     return \%userroles;  
1.11      www      3695: }
                   3696: 
1.567     raeburn  3697: sub set_arearole {
                   3698:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3699: # log the associated role with the area
                   3700:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3701:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3702: }
                   3703: 
                   3704: sub custom_roleprivs {
                   3705:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3706:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3707:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3708:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3709:         my ($rdummy,$roledef)=
                   3710:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3711:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3712:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3713:             if (defined($syspriv)) {
                   3714:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3715:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3716:             }
                   3717:             if ($tdomain ne '') {
                   3718:                 if (defined($dompriv)) {
                   3719:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3720:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3721:                 }
                   3722:                 if (($trest ne '') && (defined($coursepriv))) {
                   3723:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3724:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3725:                 }
                   3726:             }
                   3727:         }
                   3728:     }
                   3729: }
                   3730: 
1.678     raeburn  3731: sub group_roleprivs {
                   3732:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3733:     my $access = 1;
                   3734:     my $now = time;
                   3735:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3736:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3737:     if ($access) {
1.811     albertel 3738:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3739:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3740:     }
                   3741: }
1.567     raeburn  3742: 
                   3743: sub standard_roleprivs {
                   3744:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3745:     if (defined($pr{$trole.':s'})) {
                   3746:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3747:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3748:     }
                   3749:     if ($tdomain ne '') {
                   3750:         if (defined($pr{$trole.':d'})) {
                   3751:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3752:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3753:         }
                   3754:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3755:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3756:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3757:         }
                   3758:     }
                   3759: }
                   3760: 
                   3761: sub set_userprivs {
1.678     raeburn  3762:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3763:     my $author=0;
                   3764:     my $adv=0;
1.678     raeburn  3765:     my %grouproles = ();
                   3766:     if (keys(%{$allgroups}) > 0) {
                   3767:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3768:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3769:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3770:                 $trole = $1;
                   3771:                 $area = $2;
1.681     raeburn  3772:                 $sec = $3;
                   3773:                 $extendedarea = $area.$sec;
                   3774:                 if (exists($$allgroups{$area})) {
                   3775:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3776:                         my $spec = $trole.'.'.$extendedarea;
                   3777:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3778:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3779:                     }
                   3780:                 }
                   3781:             }
                   3782:         }
                   3783:     }
1.800     albertel 3784:     foreach my $group (keys(%grouproles)) {
                   3785:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3786:     }
1.800     albertel 3787:     foreach my $role (keys(%{$allroles})) {
                   3788:         my %thesepriv;
1.941     raeburn  3789:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3790:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3791:             if ($item ne '') {
                   3792:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3793:                 if ($restrictions eq '') {
                   3794:                     $thesepriv{$privilege}='F';
                   3795:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3796:                     $thesepriv{$privilege}.=$restrictions;
                   3797:                 }
                   3798:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3799:             }
                   3800:         }
                   3801:         my $thesestr='';
1.800     albertel 3802:         foreach my $priv (keys(%thesepriv)) {
                   3803: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3804: 	}
                   3805:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3806:     }
                   3807:     return ($author,$adv);
                   3808: }
                   3809: 
1.12      www      3810: # --------------------------------------------------------------- get interface
                   3811: 
                   3812: sub get {
1.131     albertel 3813:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3814:    my $items='';
1.800     albertel 3815:    foreach my $item (@$storearr) {
                   3816:        $items.=&escape($item).'&';
1.191     harris41 3817:    }
1.12      www      3818:    $items=~s/\&$//;
1.620     albertel 3819:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3820:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3821:    my $uhome=&homeserver($uname,$udomain);
                   3822: 
1.133     albertel 3823:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3824:    my @pairs=split(/\&/,$rep);
1.273     albertel 3825:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3826:      return @pairs;
                   3827:    }
1.15      www      3828:    my %returnhash=();
1.42      www      3829:    my $i=0;
1.800     albertel 3830:    foreach my $item (@$storearr) {
                   3831:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3832:       $i++;
1.191     harris41 3833:    }
1.15      www      3834:    return %returnhash;
1.27      www      3835: }
                   3836: 
                   3837: # --------------------------------------------------------------- del interface
                   3838: 
                   3839: sub del {
1.133     albertel 3840:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3841:    my $items='';
1.800     albertel 3842:    foreach my $item (@$storearr) {
                   3843:        $items.=&escape($item).'&';
1.191     harris41 3844:    }
1.27      www      3845:    $items=~s/\&$//;
1.620     albertel 3846:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3847:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3848:    my $uhome=&homeserver($uname,$udomain);
                   3849: 
                   3850:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3851: }
                   3852: 
                   3853: # -------------------------------------------------------------- dump interface
                   3854: 
                   3855: sub dump {
1.755     albertel 3856:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3857:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3858:     if (!$uname) { $uname=$env{'user.name'}; }
                   3859:     my $uhome=&homeserver($uname,$udomain);
                   3860:     if ($regexp) {
                   3861: 	$regexp=&escape($regexp);
                   3862:     } else {
                   3863: 	$regexp='.';
                   3864:     }
                   3865:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3866:     my @pairs=split(/\&/,$rep);
                   3867:     my %returnhash=();
                   3868:     foreach my $item (@pairs) {
                   3869: 	my ($key,$value)=split(/=/,$item,2);
                   3870: 	$key = &unescape($key);
                   3871: 	next if ($key =~ /^error: 2 /);
                   3872: 	$returnhash{$key}=&thaw_unescape($value);
                   3873:     }
                   3874:     return %returnhash;
1.407     www      3875: }
                   3876: 
1.717     albertel 3877: # --------------------------------------------------------- dumpstore interface
                   3878: 
                   3879: sub dumpstore {
                   3880:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3881:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3882:    if (!$uname) { $uname=$env{'user.name'}; }
                   3883:    my $uhome=&homeserver($uname,$udomain);
                   3884:    if ($regexp) {
                   3885:        $regexp=&escape($regexp);
                   3886:    } else {
                   3887:        $regexp='.';
                   3888:    }
                   3889:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3890:    my @pairs=split(/\&/,$rep);
                   3891:    my %returnhash=();
                   3892:    foreach my $item (@pairs) {
                   3893:        my ($key,$value)=split(/=/,$item,2);
                   3894:        next if ($key =~ /^error: 2 /);
                   3895:        $returnhash{$key}=&thaw_unescape($value);
                   3896:    }
                   3897:    return %returnhash;
1.717     albertel 3898: }
                   3899: 
1.407     www      3900: # -------------------------------------------------------------- keys interface
                   3901: 
                   3902: sub getkeys {
                   3903:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3904:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3905:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3906:    my $uhome=&homeserver($uname,$udomain);
                   3907:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3908:    my @keyarray=();
1.800     albertel 3909:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3910:       next if ($key =~ /^error: 2 /);
1.800     albertel 3911:       push(@keyarray,&unescape($key));
1.407     www      3912:    }
                   3913:    return @keyarray;
1.318     matthew  3914: }
                   3915: 
1.319     matthew  3916: # --------------------------------------------------------------- currentdump
                   3917: sub currentdump {
1.328     matthew  3918:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3919:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3920:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3921:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3922:    my $uhome = &homeserver($sname,$sdom);
                   3923:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3924:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3925:    #
1.318     matthew  3926:    my %returnhash=();
1.319     matthew  3927:    #
                   3928:    if ($rep eq "unknown_cmd") { 
                   3929:        # an old lond will not know currentdump
                   3930:        # Do a dump and make it look like a currentdump
1.822     albertel 3931:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3932:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3933:        my %hash = @tmp;
                   3934:        @tmp=();
1.424     matthew  3935:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3936:    } else {
                   3937:        my @pairs=split(/\&/,$rep);
1.800     albertel 3938:        foreach my $pair (@pairs) {
                   3939:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3940:            my ($symb,$param) = split(/:/,$key);
                   3941:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3942:                                                         &thaw_unescape($value);
1.319     matthew  3943:        }
1.191     harris41 3944:    }
1.12      www      3945:    return %returnhash;
1.424     matthew  3946: }
                   3947: 
                   3948: sub convert_dump_to_currentdump{
                   3949:     my %hash = %{shift()};
                   3950:     my %returnhash;
                   3951:     # Code ripped from lond, essentially.  The only difference
                   3952:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3953:     # we might run in to problems with parameter names =~ /^v\./
                   3954:     while (my ($key,$value) = each(%hash)) {
                   3955:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3956: 	$symb  = &unescape($symb);
                   3957: 	$param = &unescape($param);
1.424     matthew  3958:         next if ($v eq 'version' || $symb eq 'keys');
                   3959:         next if (exists($returnhash{$symb}) &&
                   3960:                  exists($returnhash{$symb}->{$param}) &&
                   3961:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3962:         $returnhash{$symb}->{$param}=$value;
                   3963:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3964:     }
                   3965:     #
                   3966:     # Remove all of the keys in the hashes which keep track of
                   3967:     # the version of the parameter.
                   3968:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3969:         # use a foreach because we are going to delete from the hash.
                   3970:         foreach my $key (keys(%$param_hash)) {
                   3971:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3972:         }
                   3973:     }
                   3974:     return \%returnhash;
1.12      www      3975: }
                   3976: 
1.627     albertel 3977: # ------------------------------------------------------ critical inc interface
                   3978: 
                   3979: sub cinc {
                   3980:     return &inc(@_,'critical');
                   3981: }
                   3982: 
1.449     matthew  3983: # --------------------------------------------------------------- inc interface
                   3984: 
                   3985: sub inc {
1.627     albertel 3986:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3987:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3988:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3989:     my $uhome=&homeserver($uname,$udomain);
                   3990:     my $items='';
                   3991:     if (! ref($store)) {
                   3992:         # got a single value, so use that instead
                   3993:         $items = &escape($store).'=&';
                   3994:     } elsif (ref($store) eq 'SCALAR') {
                   3995:         $items = &escape($$store).'=&';        
                   3996:     } elsif (ref($store) eq 'ARRAY') {
                   3997:         $items = join('=&',map {&escape($_);} @{$store});
                   3998:     } elsif (ref($store) eq 'HASH') {
                   3999:         while (my($key,$value) = each(%{$store})) {
                   4000:             $items.= &escape($key).'='.&escape($value).'&';
                   4001:         }
                   4002:     }
                   4003:     $items=~s/\&$//;
1.627     albertel 4004:     if ($critical) {
                   4005: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4006:     } else {
                   4007: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4008:     }
1.449     matthew  4009: }
                   4010: 
1.12      www      4011: # --------------------------------------------------------------- put interface
                   4012: 
                   4013: sub put {
1.134     albertel 4014:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4015:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4016:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4017:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4018:    my $items='';
1.800     albertel 4019:    foreach my $item (keys(%$storehash)) {
                   4020:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4021:    }
1.12      www      4022:    $items=~s/\&$//;
1.134     albertel 4023:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4024: }
                   4025: 
1.631     albertel 4026: # ------------------------------------------------------------ newput interface
                   4027: 
                   4028: sub newput {
                   4029:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4030:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4031:    if (!$uname) { $uname=$env{'user.name'}; }
                   4032:    my $uhome=&homeserver($uname,$udomain);
                   4033:    my $items='';
                   4034:    foreach my $key (keys(%$storehash)) {
                   4035:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4036:    }
                   4037:    $items=~s/\&$//;
                   4038:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4039: }
                   4040: 
                   4041: # ---------------------------------------------------------  putstore interface
                   4042: 
1.524     raeburn  4043: sub putstore {
1.715     albertel 4044:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4045:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4046:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4047:    my $uhome=&homeserver($uname,$udomain);
                   4048:    my $items='';
1.715     albertel 4049:    foreach my $key (keys(%$storehash)) {
                   4050:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4051:    }
1.715     albertel 4052:    $items=~s/\&$//;
1.716     albertel 4053:    my $esc_symb=&escape($symb);
                   4054:    my $esc_v=&escape($version);
1.715     albertel 4055:    my $reply =
1.716     albertel 4056:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4057: 	      $uhome);
                   4058:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4059:        # gfall back to way things use to be done
1.715     albertel 4060:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4061: 			    $uname);
1.524     raeburn  4062:    }
1.715     albertel 4063:    return $reply;
                   4064: }
                   4065: 
                   4066: sub old_putstore {
1.716     albertel 4067:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4068:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4069:     if (!$uname) { $uname=$env{'user.name'}; }
                   4070:     my $uhome=&homeserver($uname,$udomain);
                   4071:     my %newstorehash;
1.800     albertel 4072:     foreach my $item (keys(%$storehash)) {
                   4073: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4074: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4075:     }
                   4076:     my $items='';
                   4077:     my %allitems = ();
1.800     albertel 4078:     foreach my $item (keys(%newstorehash)) {
                   4079: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4080: 	    my $key = $1.':keys:'.$2;
                   4081: 	    $allitems{$key} .= $3.':';
                   4082: 	}
1.800     albertel 4083: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4084:     }
1.800     albertel 4085:     foreach my $item (keys(%allitems)) {
                   4086: 	$allitems{$item} =~ s/\:$//;
                   4087: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4088:     }
                   4089:     $items=~s/\&$//;
                   4090:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4091: }
                   4092: 
1.47      www      4093: # ------------------------------------------------------ critical put interface
                   4094: 
                   4095: sub cput {
1.134     albertel 4096:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4097:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4098:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4099:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4100:    my $items='';
1.800     albertel 4101:    foreach my $item (keys(%$storehash)) {
                   4102:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4103:    }
1.47      www      4104:    $items=~s/\&$//;
1.134     albertel 4105:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4106: }
                   4107: 
                   4108: # -------------------------------------------------------------- eget interface
                   4109: 
                   4110: sub eget {
1.133     albertel 4111:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4112:    my $items='';
1.800     albertel 4113:    foreach my $item (@$storearr) {
                   4114:        $items.=&escape($item).'&';
1.191     harris41 4115:    }
1.12      www      4116:    $items=~s/\&$//;
1.620     albertel 4117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4118:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4119:    my $uhome=&homeserver($uname,$udomain);
                   4120:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4121:    my @pairs=split(/\&/,$rep);
                   4122:    my %returnhash=();
1.42      www      4123:    my $i=0;
1.800     albertel 4124:    foreach my $item (@$storearr) {
                   4125:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4126:       $i++;
1.191     harris41 4127:    }
1.12      www      4128:    return %returnhash;
                   4129: }
                   4130: 
1.667     albertel 4131: # ------------------------------------------------------------ tmpput interface
                   4132: sub tmpput {
1.802     raeburn  4133:     my ($storehash,$server,$context)=@_;
1.667     albertel 4134:     my $items='';
1.800     albertel 4135:     foreach my $item (keys(%$storehash)) {
                   4136: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4137:     }
                   4138:     $items=~s/\&$//;
1.802     raeburn  4139:     if (defined($context)) {
                   4140:         $items .= ':'.&escape($context);
                   4141:     }
1.667     albertel 4142:     return &reply("tmpput:$items",$server);
                   4143: }
                   4144: 
                   4145: # ------------------------------------------------------------ tmpget interface
                   4146: sub tmpget {
1.688     albertel 4147:     my ($token,$server)=@_;
                   4148:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4149:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4150:     my %returnhash;
                   4151:     foreach my $item (split(/\&/,$rep)) {
                   4152: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4153:         next if ($key =~ /^error: 2 /);
1.667     albertel 4154: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4155:     }
                   4156:     return %returnhash;
                   4157: }
                   4158: 
1.688     albertel 4159: # ------------------------------------------------------------ tmpget interface
                   4160: sub tmpdel {
                   4161:     my ($token,$server)=@_;
                   4162:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4163:     return &reply("tmpdel:$token",$server);
                   4164: }
                   4165: 
1.765     albertel 4166: # -------------------------------------------------- portfolio access checking
                   4167: 
                   4168: sub portfolio_access {
1.766     albertel 4169:     my ($requrl) = @_;
1.765     albertel 4170:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4171:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4172:     if ($result) {
                   4173:         my %setters;
                   4174:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4175:             my ($startblock,$endblock) =
                   4176:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4177:             if ($startblock && $endblock) {
                   4178:                 return 'B';
                   4179:             }
                   4180:         } else {
                   4181:             my ($startblock,$endblock) =
                   4182:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4183:             if ($startblock && $endblock) {
                   4184:                 return 'B';
                   4185:             }
                   4186:         }
                   4187:     }
1.765     albertel 4188:     if ($result eq 'ok') {
1.766     albertel 4189:        return 'F';
1.765     albertel 4190:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4191:        return 'A';
1.765     albertel 4192:     }
1.766     albertel 4193:     return '';
1.765     albertel 4194: }
                   4195: 
                   4196: sub get_portfolio_access {
1.767     albertel 4197:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4198: 
                   4199:     if (!ref($access_hash)) {
                   4200: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4201: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4202: 						   $file_name);
                   4203: 	$access_hash = $access_controls{$file_name};
                   4204:     }
                   4205: 
1.765     albertel 4206:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4207:     my $now = time;
                   4208:     if (ref($access_hash) eq 'HASH') {
                   4209:         foreach my $key (keys(%{$access_hash})) {
                   4210:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4211:             if ($start > $now) {
                   4212:                 next;
                   4213:             }
                   4214:             if ($end && $end<$now) {
                   4215:                 next;
                   4216:             }
                   4217:             if ($scope eq 'public') {
                   4218:                 $public = $key;
                   4219:                 last;
                   4220:             } elsif ($scope eq 'guest') {
                   4221:                 $guest = $key;
                   4222:             } elsif ($scope eq 'domains') {
                   4223:                 push(@domains,$key);
                   4224:             } elsif ($scope eq 'users') {
                   4225:                 push(@users,$key);
                   4226:             } elsif ($scope eq 'course') {
                   4227:                 push(@courses,$key);
                   4228:             } elsif ($scope eq 'group') {
                   4229:                 push(@groups,$key);
                   4230:             }
                   4231:         }
                   4232:         if ($public) {
                   4233:             return 'ok';
                   4234:         }
                   4235:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4236:             if ($guest) {
                   4237:                 return $guest;
                   4238:             }
                   4239:         } else {
                   4240:             if (@domains > 0) {
                   4241:                 foreach my $domkey (@domains) {
                   4242:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4243:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4244:                             return 'ok';
                   4245:                         }
                   4246:                     }
                   4247:                 }
                   4248:             }
                   4249:             if (@users > 0) {
                   4250:                 foreach my $userkey (@users) {
1.865     raeburn  4251:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4252:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4253:                             if (ref($item) eq 'HASH') {
                   4254:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4255:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4256:                                     return 'ok';
                   4257:                                 }
                   4258:                             }
                   4259:                         }
                   4260:                     } 
1.765     albertel 4261:                 }
                   4262:             }
                   4263:             my %roleshash;
                   4264:             my @courses_and_groups = @courses;
                   4265:             push(@courses_and_groups,@groups); 
                   4266:             if (@courses_and_groups > 0) {
                   4267:                 my (%allgroups,%allroles); 
                   4268:                 my ($start,$end,$role,$sec,$group);
                   4269:                 foreach my $envkey (%env) {
1.811     albertel 4270:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4271:                         my $cid = $2.'_'.$3; 
                   4272:                         if ($1 eq 'gr') {
                   4273:                             $group = $4;
                   4274:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4275:                         } else {
                   4276:                             if ($4 eq '') {
                   4277:                                 $sec = 'none';
                   4278:                             } else {
                   4279:                                 $sec = $4;
                   4280:                             }
                   4281:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4282:                         }
1.811     albertel 4283:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4284:                         my $cid = $2.'_'.$3;
                   4285:                         if ($4 eq '') {
                   4286:                             $sec = 'none';
                   4287:                         } else {
                   4288:                             $sec = $4;
                   4289:                         }
                   4290:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4291:                     }
                   4292:                 }
                   4293:                 if (keys(%allroles) == 0) {
                   4294:                     return;
                   4295:                 }
                   4296:                 foreach my $key (@courses_and_groups) {
                   4297:                     my %content = %{$$access_hash{$key}};
                   4298:                     my $cnum = $content{'number'};
                   4299:                     my $cdom = $content{'domain'};
                   4300:                     my $cid = $cdom.'_'.$cnum;
                   4301:                     if (!exists($allroles{$cid})) {
                   4302:                         next;
                   4303:                     }    
                   4304:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4305:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4306:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4307:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4308:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4309:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4310:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4311:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4312:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4313:                                         if (grep/^all$/,@sections) {
                   4314:                                             return 'ok';
                   4315:                                         } else {
                   4316:                                             if (grep/^$sec$/,@sections) {
                   4317:                                                 return 'ok';
                   4318:                                             }
                   4319:                                         }
                   4320:                                     }
                   4321:                                 }
                   4322:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4323:                                     if (grep/^none$/,@groups) {
                   4324:                                         return 'ok';
                   4325:                                     }
                   4326:                                 } else {
                   4327:                                     if (grep/^all$/,@groups) {
                   4328:                                         return 'ok';
                   4329:                                     } 
                   4330:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4331:                                         if (grep/^$group$/,@groups) {
                   4332:                                             return 'ok';
                   4333:                                         }
                   4334:                                     }
                   4335:                                 } 
                   4336:                             }
                   4337:                         }
                   4338:                     }
                   4339:                 }
                   4340:             }
                   4341:             if ($guest) {
                   4342:                 return $guest;
                   4343:             }
                   4344:         }
                   4345:     }
                   4346:     return;
                   4347: }
                   4348: 
                   4349: sub course_group_datechecker {
                   4350:     my ($dates,$now,$status) = @_;
                   4351:     my ($start,$end) = split(/\./,$dates);
                   4352:     if (!$start && !$end) {
                   4353:         return 'ok';
                   4354:     }
                   4355:     if (grep/^active$/,@{$status}) {
                   4356:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4357:             return 'ok';
                   4358:         }
                   4359:     }
                   4360:     if (grep/^previous$/,@{$status}) {
                   4361:         if ($end > $now ) {
                   4362:             return 'ok';
                   4363:         }
                   4364:     }
                   4365:     if (grep/^future$/,@{$status}) {
                   4366:         if ($start > $now) {
                   4367:             return 'ok';
                   4368:         }
                   4369:     }
                   4370:     return; 
                   4371: }
                   4372: 
                   4373: sub parse_portfolio_url {
                   4374:     my ($url) = @_;
                   4375: 
                   4376:     my ($type,$udom,$unum,$group,$file_name);
                   4377:     
1.823     albertel 4378:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4379: 	$type = 1;
                   4380:         $udom = $1;
                   4381:         $unum = $2;
                   4382:         $file_name = $3;
1.823     albertel 4383:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4384: 	$type = 2;
                   4385:         $udom = $1;
                   4386:         $unum = $2;
                   4387:         $group = $3;
                   4388:         $file_name = $3.'/'.$4;
                   4389:     }
                   4390:     if (wantarray) {
                   4391: 	return ($type,$udom,$unum,$file_name,$group);
                   4392:     }
                   4393:     return $type;
                   4394: }
                   4395: 
                   4396: sub is_portfolio_url {
                   4397:     my ($url) = @_;
                   4398:     return scalar(&parse_portfolio_url($url));
                   4399: }
                   4400: 
1.798     raeburn  4401: sub is_portfolio_file {
                   4402:     my ($file) = @_;
1.820     raeburn  4403:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4404:         return 1;
                   4405:     }
                   4406:     return;
                   4407: }
                   4408: 
1.976     raeburn  4409: sub usertools_access {
1.978     raeburn  4410:     my ($uname,$udom,$tool,$action) = @_;
1.976     raeburn  4411:     my $access;
                   4412:     my %tools = (
                   4413:                   aboutme   => 1,
                   4414:                   blog      => 1,
                   4415:                   portfolio => 1,
                   4416:                 );
                   4417:     return if (!defined($tools{$tool}));
                   4418: 
                   4419:     if ((!defined($udom)) || (!defined($uname))) {
                   4420:         $udom = $env{'user.domain'};
                   4421:         $uname = $env{'user.name'};
                   4422:     }
                   4423: 
1.978     raeburn  4424:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4425:         if ($action ne 'reload') {
                   4426:             return $env{'environment.availabletools.'.$tool};
                   4427:         } 
1.976     raeburn  4428:     }
                   4429: 
                   4430:     my ($toolstatus,$inststatus);
                   4431: 
                   4432:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4433:         $toolstatus = $env{'environment.tools.'.$tool};
                   4434:         $inststatus = $env{'environment.inststatus'};
                   4435:     } else {
                   4436:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
                   4437:         $toolstatus = $userenv{'tools.'.$tool};
                   4438:         $inststatus = $userenv{'inststatus'};
                   4439:     }
                   4440: 
                   4441:     if ($toolstatus ne '') {
                   4442:         if ($toolstatus) {
                   4443:             $access = 1;
                   4444:         } else {
                   4445:             $access = 0;
                   4446:         }
                   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:                 return $access;
                   4461:             }
                   4462:         }
                   4463:         if ($inststatus ne '') {
                   4464:             my ($hasaccess,$hasnoaccess);
                   4465:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4466:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4467:                     if ($domdef{$tool}{$affiliation}) {
                   4468:                         $hasaccess = 1;
                   4469:                     } else {
                   4470:                         $hasnoaccess = 1;
                   4471:                     }
                   4472:                 }
                   4473:             }
                   4474:             if ($hasaccess || $hasnoaccess) {
                   4475:                 if ($hasaccess) {
                   4476:                     $access = 1;
                   4477:                 } elsif ($hasnoaccess) {
                   4478:                     $access = 0; 
                   4479:                 }
                   4480:                 return $access;
                   4481:             }
                   4482:         } else {
                   4483:             if ($domdef{$tool}{'default'} ne '') {
                   4484:                 if ($domdef{$tool}{'default'}) {
                   4485:                     $access = 1;
                   4486:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4487:                     $access = 0;
                   4488:                 }
                   4489:                 return $access;
                   4490:             }
                   4491:         }
                   4492:     } else {
                   4493:         $access = 1;
                   4494:         return $access;
                   4495:     }
                   4496: }
                   4497: 
                   4498: sub is_advanced_user {
                   4499:     my ($udom,$uname) = @_;
                   4500:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4501:     my %allroles;
                   4502:     my $is_adv;
                   4503:     foreach my $role (keys(%roleshash)) {
                   4504:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4505:         my $area = '/'.$tdomain.'/'.$trest;
                   4506:         if ($sec ne '') {
                   4507:             $area .= '/'.$sec;
                   4508:         }
                   4509:         if (($area ne '') && ($trole ne '')) {
                   4510:             my $spec=$trole.'.'.$area;
                   4511:             if ($trole =~ /^cr\//) {
                   4512:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4513:             } elsif ($trole ne 'gr') {
                   4514:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4515:             }
                   4516:         }
                   4517:     }
                   4518:     foreach my $role (keys(%allroles)) {
                   4519:         last if ($is_adv);
                   4520:         foreach my $item (split(/:/,$allroles{$role})) {
                   4521:             if ($item ne '') {
                   4522:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4523:                 if ($privilege eq 'adv') {
                   4524:                     $is_adv = 1;
                   4525:                     last;
                   4526:                 }
                   4527:             }
                   4528:         }
                   4529:     }
                   4530:     return $is_adv;
                   4531: }
1.798     raeburn  4532: 
1.341     www      4533: # ---------------------------------------------- Custom access rule evaluation
                   4534: 
                   4535: sub customaccess {
                   4536:     my ($priv,$uri)=@_;
1.807     albertel 4537:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4538:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4539:     $udom = &LONCAPA::clean_domain($udom);
                   4540:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4541:     my $access=0;
1.800     albertel 4542:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4543: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4544: 	if ($type eq 'user') {
                   4545: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4546: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4547: 		if ($tdom) {
                   4548: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4549: 		}
1.896     albertel 4550: 		if ($tuname) {
                   4551: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4552: 		}
                   4553: 		$access=($effect eq 'allow');
                   4554: 		last;
                   4555: 	    }
                   4556: 	} else {
                   4557: 	    if ($role) {
                   4558: 		if ($role ne $urole) { next; }
                   4559: 	    }
                   4560: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4561: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4562: 		if ($tdom) {
                   4563: 		    if ($tdom ne $udom) { next; }
                   4564: 		}
                   4565: 		if ($tcrs) {
                   4566: 		    if ($tcrs ne $ucrs) { next; }
                   4567: 		}
                   4568: 		if ($tsec) {
                   4569: 		    if ($tsec ne $usec) { next; }
                   4570: 		}
                   4571: 		$access=($effect eq 'allow');
                   4572: 		last;
                   4573: 	    }
                   4574: 	    if ($realm eq '' && $role eq '') {
                   4575: 		$access=($effect eq 'allow');
                   4576: 	    }
1.402     bowersj2 4577: 	}
1.341     www      4578:     }
                   4579:     return $access;
                   4580: }
                   4581: 
1.103     harris41 4582: # ------------------------------------------------- Check for a user privilege
1.12      www      4583: 
                   4584: sub allowed {
1.810     raeburn  4585:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4586:     my $ver_orguri=$uri;
1.439     www      4587:     $uri=&deversion($uri);
1.152     www      4588:     my $orguri=$uri;
1.52      www      4589:     $uri=&declutter($uri);
1.809     raeburn  4590: 
1.810     raeburn  4591:     if ($priv eq 'evb') {
                   4592: # Evade communication block restrictions for specified role in a course
                   4593:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4594:             return $1;
                   4595:         } else {
                   4596:             return;
                   4597:         }
                   4598:     }
                   4599: 
1.620     albertel 4600:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4601: # Free bre access to adm and meta resources
1.775     albertel 4602:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4603: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4604: 	&& ($priv eq 'bre')) {
1.14      www      4605: 	return 'F';
1.159     www      4606:     }
                   4607: 
1.545     banghart 4608: # Free bre access to user's own portfolio contents
1.714     raeburn  4609:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4610:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4611: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4612:         my %setters;
                   4613:         my ($startblock,$endblock) = 
                   4614:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4615:         if ($startblock && $endblock) {
                   4616:             return 'B';
                   4617:         } else {
                   4618:             return 'F';
                   4619:         }
1.545     banghart 4620:     }
                   4621: 
1.762     raeburn  4622: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4623:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4624:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4625:         if (exists($env{'request.course.id'})) {
                   4626:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4627:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4628:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4629:                 my $courseprivid=$env{'request.course.id'};
                   4630:                 $courseprivid=~s/\_/\//;
                   4631:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4632:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4633:                     return $1; 
1.762     raeburn  4634:                 } else {
                   4635:                     if ($env{'request.course.sec'}) {
                   4636:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4637:                     }
                   4638:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4639:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4640:                         return $2;
                   4641:                     }
1.714     raeburn  4642:                 }
                   4643:             }
                   4644:         }
                   4645:     }
                   4646: 
1.159     www      4647: # Free bre to public access
                   4648: 
                   4649:     if ($priv eq 'bre') {
1.238     www      4650:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4651: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4652:            return 'F'; 
                   4653:         }
1.238     www      4654:         if ($copyright eq 'priv') {
                   4655:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4656: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4657: 		return '';
                   4658:             }
                   4659:         }
                   4660:         if ($copyright eq 'domain') {
                   4661:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4662: 	    unless (($env{'user.domain'} eq $1) ||
                   4663:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4664: 		return '';
                   4665:             }
1.262     matthew  4666:         }
1.620     albertel 4667:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4668:             # Library role, so allow browsing of resources in this domain.
                   4669:             return 'F';
1.238     www      4670:         }
1.341     www      4671:         if ($copyright eq 'custom') {
                   4672: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4673:         }
1.14      www      4674:     }
1.264     matthew  4675:     # Domain coordinator is trying to create a course
1.620     albertel 4676:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4677:         # uri is the requested domain in this case.
                   4678:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4679:         # a role of dc for the domain in question.
1.620     albertel 4680:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4681:     }
1.29      www      4682: 
1.52      www      4683:     my $thisallowed='';
                   4684:     my $statecond=0;
                   4685:     my $courseprivid='';
                   4686: 
                   4687: # Course
                   4688: 
1.620     albertel 4689:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4690:        $thisallowed.=$1;
                   4691:     }
1.29      www      4692: 
1.52      www      4693: # Domain
                   4694: 
1.620     albertel 4695:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4696:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4697:        $thisallowed.=$1;
                   4698:     }
1.52      www      4699: 
                   4700: # Course: uri itself is a course
1.66      www      4701:     my $courseuri=$uri;
                   4702:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4703:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4704: 
1.620     albertel 4705:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4706:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4707:        $thisallowed.=$1;
                   4708:     }
1.29      www      4709: 
1.665     albertel 4710: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4711: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4712:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4713: 	$thisallowed='';
1.671     raeburn  4714:         my ($match)=&is_on_map($uri);
                   4715:         if ($match) {
                   4716:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4717:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4718:                 $thisallowed.=$1;
                   4719:             }
                   4720:         } else {
1.705     albertel 4721:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4722:             if ($refuri) {
                   4723:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4724:                     $thisallowed='F';
1.671     raeburn  4725:                 } else {
                   4726:                     $refuri=&declutter($refuri);
                   4727:                     my ($match) = &is_on_map($refuri);
                   4728:                     if ($match) {
                   4729:                         $thisallowed='F';
                   4730:                     }
1.669     raeburn  4731:                 }
1.671     raeburn  4732:             }
                   4733:         }
1.314     www      4734:     }
1.492     albertel 4735: 
1.766     albertel 4736:     if ($priv eq 'bre'
                   4737: 	&& $thisallowed ne 'F' 
                   4738: 	&& $thisallowed ne '2'
                   4739: 	&& &is_portfolio_url($uri)) {
                   4740: 	$thisallowed = &portfolio_access($uri);
                   4741:     }
                   4742:     
1.52      www      4743: # Full access at system, domain or course-wide level? Exit.
1.29      www      4744:     if ($thisallowed=~/F/) {
                   4745: 	return 'F';
                   4746:     }
                   4747: 
1.52      www      4748: # If this is generating or modifying users, exit with special codes
1.29      www      4749: 
1.643     www      4750:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4751: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4752: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4753: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4754: 	    unless ($auname) { return $thisallowed; }
                   4755: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4756: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4757: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4758: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4759: 	}
1.52      www      4760: 	return $thisallowed;
                   4761:     }
                   4762: #
1.103     harris41 4763: # Gathered so far: system, domain and course wide privileges
1.52      www      4764: #
                   4765: # Course: See if uri or referer is an individual resource that is part of 
                   4766: # the course
                   4767: 
1.620     albertel 4768:     if ($env{'request.course.id'}) {
1.232     www      4769: 
1.620     albertel 4770:        $courseprivid=$env{'request.course.id'};
                   4771:        if ($env{'request.course.sec'}) {
                   4772:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4773:        }
                   4774:        $courseprivid=~s/\_/\//;
                   4775:        my $checkreferer=1;
1.232     www      4776:        my ($match,$cond)=&is_on_map($uri);
                   4777:        if ($match) {
                   4778:            $statecond=$cond;
1.620     albertel 4779:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4780:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4781:                $thisallowed.=$1;
                   4782:                $checkreferer=0;
                   4783:            }
1.29      www      4784:        }
1.83      www      4785:        
1.148     www      4786:        if ($checkreferer) {
1.620     albertel 4787: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4788:             unless ($refuri) {
1.800     albertel 4789:                 foreach my $key (keys(%env)) {
                   4790: 		    if ($key=~/^httpref\..*\*/) {
                   4791: 			my $pattern=$key;
1.156     www      4792:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4793:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4794:                         $pattern=~s/\//\\\//g;
1.152     www      4795:                         if ($orguri=~/$pattern/) {
1.800     albertel 4796: 			    $refuri=$env{$key};
1.148     www      4797:                         }
                   4798:                     }
1.191     harris41 4799:                 }
1.148     www      4800:             }
1.232     www      4801: 
1.148     www      4802:          if ($refuri) { 
1.152     www      4803: 	  $refuri=&declutter($refuri);
1.232     www      4804:           my ($match,$cond)=&is_on_map($refuri);
                   4805:             if ($match) {
                   4806:               my $refstatecond=$cond;
1.620     albertel 4807:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4808:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4809:                   $thisallowed.=$1;
1.53      www      4810:                   $uri=$refuri;
                   4811:                   $statecond=$refstatecond;
1.52      www      4812:               }
                   4813:           }
1.148     www      4814:         }
1.29      www      4815:        }
1.52      www      4816:    }
1.29      www      4817: 
1.52      www      4818: #
1.103     harris41 4819: # Gathered now: all privileges that could apply, and condition number
1.52      www      4820: # 
                   4821: #
                   4822: # Full or no access?
                   4823: #
1.29      www      4824: 
1.52      www      4825:     if ($thisallowed=~/F/) {
                   4826: 	return 'F';
                   4827:     }
1.29      www      4828: 
1.52      www      4829:     unless ($thisallowed) {
                   4830:         return '';
                   4831:     }
1.29      www      4832: 
1.52      www      4833: # Restrictions exist, deal with them
                   4834: #
                   4835: #   C:according to course preferences
                   4836: #   R:according to resource settings
                   4837: #   L:unless locked
                   4838: #   X:according to user session state
                   4839: #
                   4840: 
                   4841: # Possibly locked functionality, check all courses
1.54      www      4842: # Locks might take effect only after 10 minutes cache expiration for other
                   4843: # courses, and 2 minutes for current course
1.52      www      4844: 
                   4845:     my $envkey;
                   4846:     if ($thisallowed=~/L/) {
1.620     albertel 4847:         foreach $envkey (keys %env) {
1.54      www      4848:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4849:                my $courseid=$2;
                   4850:                my $roleid=$1.'.'.$2;
1.92      www      4851:                $courseid=~s/^\///;
1.54      www      4852:                my $expiretime=600;
1.620     albertel 4853:                if ($env{'request.role'} eq $roleid) {
1.54      www      4854: 		  $expiretime=120;
                   4855:                }
                   4856: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4857:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4858:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4859: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4860:                }
1.620     albertel 4861:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4862:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4863: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4864:                        &log($env{'user.domain'},$env{'user.name'},
                   4865:                             $env{'user.home'},
1.57      www      4866:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4867:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4868:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4869: 		       return '';
                   4870:                    }
                   4871:                }
1.620     albertel 4872:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4873:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4874: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4875:                        &log($env{'user.domain'},$env{'user.name'},
                   4876:                             $env{'user.home'},
1.57      www      4877:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4878:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4879:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4880: 		       return '';
                   4881:                    }
                   4882:                }
                   4883: 	   }
1.29      www      4884:        }
1.52      www      4885:     }
                   4886:    
                   4887: #
                   4888: # Rest of the restrictions depend on selected course
                   4889: #
                   4890: 
1.620     albertel 4891:     unless ($env{'request.course.id'}) {
1.766     albertel 4892: 	if ($thisallowed eq 'A') {
                   4893: 	    return 'A';
1.814     raeburn  4894:         } elsif ($thisallowed eq 'B') {
                   4895:             return 'B';
1.766     albertel 4896: 	} else {
                   4897: 	    return '1';
                   4898: 	}
1.52      www      4899:     }
1.29      www      4900: 
1.52      www      4901: #
                   4902: # Now user is definitely in a course
                   4903: #
1.53      www      4904: 
                   4905: 
                   4906: # Course preferences
                   4907: 
                   4908:    if ($thisallowed=~/C/) {
1.620     albertel 4909:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4910:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4911:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4912: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4913: 	   if ($priv ne 'pch') { 
                   4914: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4915: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4916: 			$env{'request.course.id'});
                   4917: 	   }
1.237     www      4918:            return '';
                   4919:        }
                   4920: 
1.620     albertel 4921:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4922: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4923: 	   if ($priv ne 'pch') { 
                   4924: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4925: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4926: 			$env{'request.course.id'});
                   4927: 	   }
1.54      www      4928:            return '';
                   4929:        }
1.53      www      4930:    }
                   4931: 
                   4932: # Resource preferences
                   4933: 
                   4934:    if ($thisallowed=~/R/) {
1.620     albertel 4935:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4936:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4937: 	   if ($priv ne 'pch') { 
                   4938: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4939: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4940: 	   }
                   4941: 	   return '';
1.54      www      4942:        }
1.53      www      4943:    }
1.30      www      4944: 
1.246     www      4945: # Restricted by state or randomout?
1.30      www      4946: 
1.52      www      4947:    if ($thisallowed=~/X/) {
1.620     albertel 4948:       if ($env{'acc.randomout'}) {
1.579     albertel 4949: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4950:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4951:             return ''; 
                   4952:          }
1.247     www      4953:       }
                   4954:       if (&condval($statecond)) {
1.52      www      4955: 	 return '2';
                   4956:       } else {
                   4957:          return '';
                   4958:       }
                   4959:    }
1.30      www      4960: 
1.766     albertel 4961:     if ($thisallowed eq 'A') {
                   4962: 	return 'A';
1.814     raeburn  4963:     } elsif ($thisallowed eq 'B') {
                   4964:         return 'B';
1.766     albertel 4965:     }
1.52      www      4966:    return 'F';
1.232     www      4967: }
                   4968: 
1.710     albertel 4969: sub split_uri_for_cond {
                   4970:     my $uri=&deversion(&declutter(shift));
                   4971:     my @uriparts=split(/\//,$uri);
                   4972:     my $filename=pop(@uriparts);
                   4973:     my $pathname=join('/',@uriparts);
                   4974:     return ($pathname,$filename);
                   4975: }
1.232     www      4976: # --------------------------------------------------- Is a resource on the map?
                   4977: 
                   4978: sub is_on_map {
1.710     albertel 4979:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4980:     #Trying to find the conditional for the file
1.620     albertel 4981:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4982: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4983:     if ($match) {
1.289     bowersj2 4984: 	return (1,$1);
                   4985:     } else {
1.434     www      4986: 	return (0,0);
1.289     bowersj2 4987:     }
1.12      www      4988: }
                   4989: 
1.427     www      4990: # --------------------------------------------------------- Get symb from alias
                   4991: 
                   4992: sub get_symb_from_alias {
                   4993:     my $symb=shift;
                   4994:     my ($map,$resid,$url)=&decode_symb($symb);
                   4995: # Already is a symb
                   4996:     if ($url) { return $symb; }
                   4997: # Must be an alias
                   4998:     my $aliassymb='';
                   4999:     my %bighash;
1.620     albertel 5000:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5001:                             &GDBM_READER(),0640)) {
                   5002:         my $rid=$bighash{'mapalias_'.$symb};
                   5003: 	if ($rid) {
                   5004: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5005: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5006: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5007: 	}
                   5008:         untie %bighash;
                   5009:     }
                   5010:     return $aliassymb;
                   5011: }
                   5012: 
1.12      www      5013: # ----------------------------------------------------------------- Define Role
                   5014: 
                   5015: sub definerole {
                   5016:   if (allowed('mcr','/')) {
                   5017:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5018:     foreach my $role (split(':',$sysrole)) {
                   5019: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5020:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5021:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5022: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5023:                return "refused:s:$crole&$cqual"; 
                   5024:             }
                   5025:         }
1.191     harris41 5026:     }
1.800     albertel 5027:     foreach my $role (split(':',$domrole)) {
                   5028: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5029:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5030:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5031: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5032:                return "refused:d:$crole&$cqual"; 
                   5033:             }
                   5034:         }
1.191     harris41 5035:     }
1.800     albertel 5036:     foreach my $role (split(':',$courole)) {
                   5037: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5038:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5039:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5040: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5041:                return "refused:c:$crole&$cqual"; 
                   5042:             }
                   5043:         }
1.191     harris41 5044:     }
1.620     albertel 5045:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5046:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5047: 	        "rolesdef_$rolename=".
                   5048:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5049:     return reply($command,$env{'user.home'});
1.12      www      5050:   } else {
                   5051:     return 'refused';
                   5052:   }
1.105     harris41 5053: }
                   5054: 
                   5055: # ---------------- Make a metadata query against the network of library servers
                   5056: 
                   5057: sub metadata_query {
1.244     matthew  5058:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5059:     my %rhash;
1.845     albertel 5060:     my %libserv = &all_library();
1.244     matthew  5061:     my @server_list = (defined($server_array) ? @$server_array
                   5062:                                               : keys(%libserv) );
                   5063:     for my $server (@server_list) {
1.118     harris41 5064: 	unless ($custom or $customshow) {
                   5065: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5066: 	    $rhash{$server}=$reply;
                   5067: 	}
                   5068: 	else {
                   5069: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5070: 			     &escape($custom).':'.&escape($customshow),
                   5071: 			     $server);
                   5072: 	    $rhash{$server}=$reply;
                   5073: 	}
1.112     harris41 5074:     }
1.118     harris41 5075:     return \%rhash;
1.240     www      5076: }
                   5077: 
                   5078: # ----------------------------------------- Send log queries and wait for reply
                   5079: 
                   5080: sub log_query {
                   5081:     my ($uname,$udom,$query,%filters)=@_;
                   5082:     my $uhome=&homeserver($uname,$udom);
                   5083:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5084:     my $uhost=&hostname($uhome);
1.800     albertel 5085:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5086:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5087:                        $uhome);
1.479     albertel 5088:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5089:     return get_query_reply($queryid);
                   5090: }
                   5091: 
1.818     raeburn  5092: # -------------------------- Update MySQL table for portfolio file
                   5093: 
                   5094: sub update_portfolio_table {
1.821     raeburn  5095:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5096:     if ($group ne '') {
                   5097:         $file_name =~s /^\Q$group\E//;
                   5098:     }
1.818     raeburn  5099:     my $homeserver = &homeserver($uname,$udom);
                   5100:     my $queryid=
1.821     raeburn  5101:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5102:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5103:     my $reply = &get_query_reply($queryid);
                   5104:     return $reply;
                   5105: }
                   5106: 
1.899     raeburn  5107: # -------------------------- Update MySQL allusers table
                   5108: 
                   5109: sub update_allusers_table {
                   5110:     my ($uname,$udom,$names) = @_;
                   5111:     my $homeserver = &homeserver($uname,$udom);
                   5112:     my $queryid=
                   5113:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5114:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5115:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5116:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5117:                'generation='.&escape($names->{'generation'}).'%%'.
                   5118:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5119:                'id='.&escape($names->{'id'}),$homeserver);
                   5120:     my $reply = &get_query_reply($queryid);
                   5121:     return $reply;
                   5122: }
                   5123: 
1.508     raeburn  5124: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5125: 
                   5126: sub fetch_enrollment_query {
1.511     raeburn  5127:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5128:     my $homeserver;
1.547     raeburn  5129:     my $maxtries = 1;
1.508     raeburn  5130:     if ($context eq 'automated') {
                   5131:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5132:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5133:     } else {
                   5134:         $homeserver = &homeserver($cnum,$dom);
                   5135:     }
1.838     albertel 5136:     my $host=&hostname($homeserver);
1.506     raeburn  5137:     my $cmd = '';
1.800     albertel 5138:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5139:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5140:     }
                   5141:     $cmd =~ s/%%$//;
                   5142:     $cmd = &escape($cmd);
                   5143:     my $query = 'fetchenrollment';
1.620     albertel 5144:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5145:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5146:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5147:         return 'error: '.$queryid;
                   5148:     }
1.506     raeburn  5149:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5150:     my $tries = 1;
                   5151:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5152:         $reply = &get_query_reply($queryid);
                   5153:         $tries ++;
                   5154:     }
1.526     raeburn  5155:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5156:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5157:     } else {
1.901     albertel 5158:         my @responses = split(/:/,$reply);
1.515     raeburn  5159:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5160:             foreach my $line (@responses) {
                   5161:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5162:                 $$replyref{$key} = $value;
                   5163:             }
                   5164:         } else {
1.506     raeburn  5165:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5166:             foreach my $line (@responses) {
                   5167:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5168:                 $$replyref{$key} = $value;
                   5169:                 if ($value > 0) {
1.800     albertel 5170:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5171:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5172:                         my $destname = $pathname.'/'.$filename;
                   5173:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5174:                         if ($xml_classlist =~ /^error/) {
                   5175:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5176:                         } else {
1.506     raeburn  5177:                             if ( open(FILE,">$destname") ) {
                   5178:                                 print FILE &unescape($xml_classlist);
                   5179:                                 close(FILE);
1.526     raeburn  5180:                             } else {
                   5181:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5182:                             }
                   5183:                         }
                   5184:                     }
                   5185:                 }
                   5186:             }
                   5187:         }
                   5188:         return 'ok';
                   5189:     }
                   5190:     return 'error';
                   5191: }
                   5192: 
1.242     www      5193: sub get_query_reply {
                   5194:     my $queryid=shift;
1.240     www      5195:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5196:     my $reply='';
                   5197:     for (1..100) {
                   5198: 	sleep 2;
                   5199:         if (-e $replyfile.'.end') {
1.448     albertel 5200: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5201: 		$reply = join('',<$fh>);
                   5202: 		close($fh);
1.240     www      5203: 	   } else { return 'error: reply_file_error'; }
1.242     www      5204:            return &unescape($reply);
                   5205: 	}
1.240     www      5206:     }
1.242     www      5207:     return 'timeout:'.$queryid;
1.240     www      5208: }
                   5209: 
                   5210: sub courselog_query {
1.241     www      5211: #
                   5212: # possible filters:
                   5213: # url: url or symb
                   5214: # username
                   5215: # domain
                   5216: # action: view, submit, grade
                   5217: # start: timestamp
                   5218: # end: timestamp
                   5219: #
1.240     www      5220:     my (%filters)=@_;
1.620     albertel 5221:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5222:     if ($filters{'url'}) {
                   5223: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5224:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5225:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5226:     }
1.620     albertel 5227:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5228:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5229:     return &log_query($cname,$cdom,'courselog',%filters);
                   5230: }
                   5231: 
                   5232: sub userlog_query {
1.858     raeburn  5233: #
                   5234: # possible filters:
                   5235: # action: log check role
                   5236: # start: timestamp
                   5237: # end: timestamp
                   5238: #
1.240     www      5239:     my ($uname,$udom,%filters)=@_;
                   5240:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5241: }
                   5242: 
1.506     raeburn  5243: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5244: 
                   5245: sub auto_run {
1.508     raeburn  5246:     my ($cnum,$cdom) = @_;
1.876     raeburn  5247:     my $response = 0;
                   5248:     my $settings;
                   5249:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5250:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5251:         $settings = $domconfig{'autoenroll'};
                   5252:         if ($settings->{'run'} eq '1') {
                   5253:             $response = 1;
                   5254:         }
                   5255:     } else {
1.934     raeburn  5256:         my $homeserver;
                   5257:         if (&is_course($cdom,$cnum)) {
                   5258:             $homeserver = &homeserver($cnum,$cdom);
                   5259:         } else {
                   5260:             $homeserver = &domain($cdom,'primary');
                   5261:         }
                   5262:         if ($homeserver ne 'no_host') {
                   5263:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5264:         }
1.876     raeburn  5265:     }
1.506     raeburn  5266:     return $response;
                   5267: }
1.776     albertel 5268: 
1.506     raeburn  5269: sub auto_get_sections {
1.508     raeburn  5270:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5271:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5272:     my @secs = ();
1.511     raeburn  5273:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5274:     unless ($response eq 'refused') {
1.901     albertel 5275:         @secs = split(/:/,$response);
1.506     raeburn  5276:     }
                   5277:     return @secs;
                   5278: }
1.776     albertel 5279: 
1.506     raeburn  5280: sub auto_new_course {
1.508     raeburn  5281:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5282:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5283:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5284:     return $response;
                   5285: }
1.776     albertel 5286: 
1.506     raeburn  5287: sub auto_validate_courseID {
1.508     raeburn  5288:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5289:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5290:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5291:     return $response;
                   5292: }
1.776     albertel 5293: 
1.506     raeburn  5294: sub auto_create_password {
1.873     raeburn  5295:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5296:     my ($homeserver,$response);
1.506     raeburn  5297:     my $create_passwd = 0;
                   5298:     my $authchk = '';
1.873     raeburn  5299:     if ($udom =~ /^$match_domain$/) {
                   5300:         $homeserver = &domain($udom,'primary');
                   5301:     }
                   5302:     if ($homeserver eq '') {
                   5303:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5304:             $homeserver = &homeserver($cnum,$cdom);
                   5305:         }
                   5306:     }
                   5307:     if ($homeserver eq '') {
                   5308:         $authchk = 'nodomain';
1.506     raeburn  5309:     } else {
1.873     raeburn  5310:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5311:         if ($response eq 'refused') {
                   5312:             $authchk = 'refused';
                   5313:         } else {
1.901     albertel 5314:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5315:         }
1.506     raeburn  5316:     }
                   5317:     return ($authparam,$create_passwd,$authchk);
                   5318: }
                   5319: 
1.706     raeburn  5320: sub auto_photo_permission {
                   5321:     my ($cnum,$cdom,$students) = @_;
                   5322:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5323:     my ($outcome,$perm_reqd,$conditions) = 
                   5324: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5325:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5326: 	return (undef,undef);
                   5327:     }
1.706     raeburn  5328:     return ($outcome,$perm_reqd,$conditions);
                   5329: }
                   5330: 
                   5331: sub auto_checkphotos {
                   5332:     my ($uname,$udom,$pid) = @_;
                   5333:     my $homeserver = &homeserver($uname,$udom);
                   5334:     my ($result,$resulttype);
                   5335:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5336: 				   &escape($uname).':'.&escape($pid),
                   5337: 				   $homeserver));
1.709     albertel 5338:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5339: 	return (undef,undef);
                   5340:     }
1.706     raeburn  5341:     if ($outcome) {
                   5342:         ($result,$resulttype) = split(/:/,$outcome);
                   5343:     } 
                   5344:     return ($result,$resulttype);
                   5345: }
                   5346: 
                   5347: sub auto_photochoice {
                   5348:     my ($cnum,$cdom) = @_;
                   5349:     my $homeserver = &homeserver($cnum,$cdom);
                   5350:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5351: 						       &escape($cdom),
                   5352: 						       $homeserver)));
1.709     albertel 5353:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5354: 	return (undef,undef);
                   5355:     }
1.706     raeburn  5356:     return ($update,$comment);
                   5357: }
                   5358: 
                   5359: sub auto_photoupdate {
                   5360:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5361:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5362:     my $host=&hostname($homeserver);
1.706     raeburn  5363:     my $cmd = '';
                   5364:     my $maxtries = 1;
1.800     albertel 5365:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5366:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5367:     }
                   5368:     $cmd =~ s/%%$//;
                   5369:     $cmd = &escape($cmd);
                   5370:     my $query = 'institutionalphotos';
                   5371:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5372:     unless ($queryid=~/^\Q$host\E\_/) {
                   5373:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5374:         return 'error: '.$queryid;
                   5375:     }
                   5376:     my $reply = &get_query_reply($queryid);
                   5377:     my $tries = 1;
                   5378:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5379:         $reply = &get_query_reply($queryid);
                   5380:         $tries ++;
                   5381:     }
                   5382:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5383:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5384:     } else {
                   5385:         my @responses = split(/:/,$reply);
                   5386:         my $outcome = shift(@responses); 
                   5387:         foreach my $item (@responses) {
                   5388:             my ($key,$value) = split(/=/,$item);
                   5389:             $$photo{$key} = $value;
                   5390:         }
                   5391:         return $outcome;
                   5392:     }
                   5393:     return 'error';
                   5394: }
                   5395: 
1.521     raeburn  5396: sub auto_instcode_format {
1.793     albertel 5397:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5398: 	$cat_order) = @_;
1.521     raeburn  5399:     my $courses = '';
1.772     raeburn  5400:     my @homeservers;
1.521     raeburn  5401:     if ($caller eq 'global') {
1.841     albertel 5402: 	my %servers = &get_servers($codedom,'library');
                   5403: 	foreach my $tryserver (keys(%servers)) {
                   5404: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5405: 		push(@homeservers,$tryserver);
                   5406: 	    }
1.584     raeburn  5407:         }
1.521     raeburn  5408:     } else {
1.772     raeburn  5409:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5410:     }
1.793     albertel 5411:     foreach my $code (keys(%{$instcodes})) {
                   5412:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5413:     }
                   5414:     chop($courses);
1.772     raeburn  5415:     my $ok_response = 0;
                   5416:     my $response;
                   5417:     while (@homeservers > 0 && $ok_response == 0) {
                   5418:         my $server = shift(@homeservers); 
                   5419:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5420:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5421:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5422: 		split(/:/,$response);
1.772     raeburn  5423:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5424:             push(@{$codetitles},&str2array($codetitles_str));
                   5425:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5426:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5427:             $ok_response = 1;
                   5428:         }
                   5429:     }
                   5430:     if ($ok_response) {
1.521     raeburn  5431:         return 'ok';
1.772     raeburn  5432:     } else {
                   5433:         return $response;
1.521     raeburn  5434:     }
                   5435: }
                   5436: 
1.792     raeburn  5437: sub auto_instcode_defaults {
                   5438:     my ($domain,$returnhash,$code_order) = @_;
                   5439:     my @homeservers;
1.841     albertel 5440: 
                   5441:     my %servers = &get_servers($domain,'library');
                   5442:     foreach my $tryserver (keys(%servers)) {
                   5443: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5444: 	    push(@homeservers,$tryserver);
                   5445: 	}
1.792     raeburn  5446:     }
1.841     albertel 5447: 
1.792     raeburn  5448:     my $response;
1.841     albertel 5449:     foreach my $server (@homeservers) {
1.792     raeburn  5450:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5451:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5452: 	
                   5453: 	foreach my $pair (split(/\&/,$response)) {
                   5454: 	    my ($name,$value)=split(/\=/,$pair);
                   5455: 	    if ($name eq 'code_order') {
                   5456: 		@{$code_order} = split(/\&/,&unescape($value));
                   5457: 	    } else {
                   5458: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5459: 	    }
                   5460: 	}
                   5461: 	return 'ok';
1.792     raeburn  5462:     }
1.841     albertel 5463: 
                   5464:     return $response;
1.792     raeburn  5465: } 
                   5466: 
1.777     albertel 5467: sub auto_validate_class_sec {
1.918     raeburn  5468:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5469:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5470:     my $ownerlist;
                   5471:     if (ref($owners) eq 'ARRAY') {
                   5472:         $ownerlist = join(',',@{$owners});
                   5473:     } else {
                   5474:         $ownerlist = $owners;
                   5475:     }
1.773     raeburn  5476:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5477:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5478:     return $response;
                   5479: }
                   5480: 
1.679     raeburn  5481: # ------------------------------------------------------- Course Group routines
                   5482: 
                   5483: sub get_coursegroups {
1.809     raeburn  5484:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5485:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5486: }
                   5487: 
1.679     raeburn  5488: sub modify_coursegroup {
                   5489:     my ($cdom,$cnum,$groupsettings) = @_;
                   5490:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5491: }
                   5492: 
1.809     raeburn  5493: sub toggle_coursegroup_status {
                   5494:     my ($cdom,$cnum,$group,$action) = @_;
                   5495:     my ($from_namespace,$to_namespace);
                   5496:     if ($action eq 'delete') {
                   5497:         $from_namespace = 'coursegroups';
                   5498:         $to_namespace = 'deleted_groups';
                   5499:     } else {
                   5500:         $from_namespace = 'deleted_groups';
                   5501:         $to_namespace = 'coursegroups';
                   5502:     }
                   5503:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5504:     if (my $tmp = &error(%curr_group)) {
                   5505:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5506:         return ('read error',$tmp);
                   5507:     } else {
                   5508:         my %savedsettings = %curr_group; 
1.809     raeburn  5509:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5510:         my $deloutcome;
                   5511:         if ($result eq 'ok') {
1.809     raeburn  5512:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5513:         } else {
                   5514:             return ('write error',$result);
                   5515:         }
                   5516:         if ($deloutcome eq 'ok') {
                   5517:             return 'ok';
                   5518:         } else {
                   5519:             return ('delete error',$deloutcome);
                   5520:         }
                   5521:     }
                   5522: }
                   5523: 
1.679     raeburn  5524: sub modify_group_roles {
1.957     raeburn  5525:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5526:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5527:     my $role = 'gr/'.&escape($userprivs);
                   5528:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5529:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5530:     if ($result eq 'ok') {
                   5531:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5532:     }
1.679     raeburn  5533:     return $result;
                   5534: }
                   5535: 
                   5536: sub modify_coursegroup_membership {
                   5537:     my ($cdom,$cnum,$membership) = @_;
                   5538:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5539:     return $result;
                   5540: }
                   5541: 
1.682     raeburn  5542: sub get_active_groups {
                   5543:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5544:     my $now = time;
                   5545:     my %groups = ();
                   5546:     foreach my $key (keys(%env)) {
1.811     albertel 5547:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5548:             my ($start,$end) = split(/\./,$env{$key});
                   5549:             if (($end!=0) && ($end<$now)) { next; }
                   5550:             if (($start!=0) && ($start>$now)) { next; }
                   5551:             if ($1 eq $cdom && $2 eq $cnum) {
                   5552:                 $groups{$3} = $env{$key} ;
                   5553:             }
                   5554:         }
                   5555:     }
                   5556:     return %groups;
                   5557: }
                   5558: 
1.683     raeburn  5559: sub get_group_membership {
                   5560:     my ($cdom,$cnum,$group) = @_;
                   5561:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5562: }
                   5563: 
                   5564: sub get_users_groups {
                   5565:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5566:     my @usersgroups;
1.683     raeburn  5567:     my $cachetime=1800;
                   5568: 
                   5569:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5570:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5571:     if (defined($cached)) {
1.734     albertel 5572:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5573:     } else {  
                   5574:         $grouplist = '';
1.816     raeburn  5575:         my $courseurl = &courseid_to_courseurl($courseid);
                   5576:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5577:         my $access_end = $env{'course.'.$courseid.
                   5578:                               '.default_enrollment_end_date'};
                   5579:         my $now = time;
                   5580:         foreach my $key (keys(%roleshash)) {
                   5581:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5582:                 my $group = $1;
                   5583:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5584:                     my $start = $2;
                   5585:                     my $end = $1;
                   5586:                     if ($start == -1) { next; } # deleted from group
                   5587:                     if (($start!=0) && ($start>$now)) { next; }
                   5588:                     if (($end!=0) && ($end<$now)) {
                   5589:                         if ($access_end && $access_end < $now) {
                   5590:                             if ($access_end - $end < 86400) {
                   5591:                                 push(@usersgroups,$group);
1.733     raeburn  5592:                             }
                   5593:                         }
1.817     raeburn  5594:                         next;
1.733     raeburn  5595:                     }
1.817     raeburn  5596:                     push(@usersgroups,$group);
1.683     raeburn  5597:                 }
                   5598:             }
                   5599:         }
1.817     raeburn  5600:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5601:         $grouplist = join(':',@usersgroups);
                   5602:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5603:     }
1.733     raeburn  5604:     return @usersgroups;
1.683     raeburn  5605: }
                   5606: 
                   5607: sub devalidate_getgroups_cache {
                   5608:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5609:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5610: 
1.683     raeburn  5611:     my $hashid="$udom:$uname:$courseid";
                   5612:     &devalidate_cache_new('getgroups',$hashid);
                   5613: }
                   5614: 
1.12      www      5615: # ------------------------------------------------------------------ Plain Text
                   5616: 
                   5617: sub plaintext {
1.742     raeburn  5618:     my ($short,$type,$cid) = @_;
1.758     albertel 5619:     if ($short =~ /^cr/) {
                   5620: 	return (split('/',$short))[-1];
                   5621:     }
1.742     raeburn  5622:     if (!defined($cid)) {
                   5623:         $cid = $env{'request.course.id'};
                   5624:     }
                   5625:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5626:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5627:                                           '.plaintext'});
                   5628:     }
                   5629:     my %rolenames = (
                   5630:                       Course => 'std',
                   5631:                       Group => 'alt1',
                   5632:                     );
                   5633:     if (defined($type) && 
                   5634:          defined($rolenames{$type}) && 
                   5635:          defined($prp{$short}{$rolenames{$type}})) {
                   5636:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5637:     } else {
                   5638:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5639:     }
1.12      www      5640: }
                   5641: 
                   5642: # ----------------------------------------------------------------- Assign Role
                   5643: 
                   5644: sub assignrole {
1.957     raeburn  5645:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5646:         $context)=@_;
1.21      www      5647:     my $mrole;
                   5648:     if ($role =~ /^cr\//) {
1.393     www      5649:         my $cwosec=$url;
1.811     albertel 5650:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5651: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5652:            &logthis('Refused custom assignrole: '.
                   5653:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5654: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5655:            return 'refused'; 
                   5656:         }
1.21      www      5657:         $mrole='cr';
1.678     raeburn  5658:     } elsif ($role =~ /^gr\//) {
                   5659:         my $cwogrp=$url;
1.811     albertel 5660:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5661:         unless (&allowed('mdg',$cwogrp)) {
                   5662:             &logthis('Refused group assignrole: '.
                   5663:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5664:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5665:             return 'refused';
                   5666:         }
                   5667:         $mrole='gr';
1.21      www      5668:     } else {
1.82      www      5669:         my $cwosec=$url;
1.811     albertel 5670:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5671:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5672:             my $refused;
                   5673:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5674:                 if (!(&allowed('c'.$role,$url))) {
                   5675:                     $refused = 1;
                   5676:                 }
                   5677:             } else {
                   5678:                 $refused = 1;
                   5679:             }
1.947     raeburn  5680:             if ($refused) {
                   5681:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5682:                     $refused = '';
                   5683:                 } else {
                   5684:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5685:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5686: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5687:                     return 'refused';
                   5688:                 }
1.932     raeburn  5689:             }
1.104     www      5690:         }
1.21      www      5691:         $mrole=$role;
                   5692:     }
1.620     albertel 5693:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5694:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5695:     if ($end) { $command.='_'.$end; }
1.21      www      5696:     if ($start) {
                   5697: 	if ($end) { 
1.81      www      5698:            $command.='_'.$start; 
1.21      www      5699:         } else {
1.81      www      5700:            $command.='_0_'.$start;
1.21      www      5701:         }
                   5702:     }
1.739     raeburn  5703:     my $origstart = $start;
                   5704:     my $origend = $end;
1.957     raeburn  5705:     my $delflag;
1.357     www      5706: # actually delete
                   5707:     if ($deleteflag) {
1.373     www      5708: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5709: # modify command to delete the role
1.620     albertel 5710:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5711:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5712: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5713: # set start and finish to negative values for userrolelog
                   5714:            $start=-1;
                   5715:            $end=-1;
1.957     raeburn  5716:            $delflag = 1;
1.357     www      5717:         }
                   5718:     }
                   5719: # send command
1.349     www      5720:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5721: # log new user role if status is ok
1.349     www      5722:     if ($answer eq 'ok') {
1.663     raeburn  5723: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5724: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5725:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5726:         unless ($role =~ /^gr/) {
                   5727:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5728:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5729:         }
1.349     www      5730:     }
                   5731:     return $answer;
1.169     harris41 5732: }
                   5733: 
                   5734: # -------------------------------------------------- Modify user authentication
1.197     www      5735: # Overrides without validation
                   5736: 
1.169     harris41 5737: sub modifyuserauth {
                   5738:     my ($udom,$uname,$umode,$upass)=@_;
                   5739:     my $uhome=&homeserver($uname,$udom);
1.197     www      5740:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5741:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5742:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5743:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5744:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5745: 		     &escape($upass),$uhome);
1.620     albertel 5746:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5747:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5748:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5749:     &log($udom,,$uname,$uhome,
1.620     albertel 5750:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5751:                                      $env{'user.name'}.', '.$umode.
1.197     www      5752:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5753:     unless ($reply eq 'ok') {
1.197     www      5754:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5755: 	return 'error: '.$reply;
                   5756:     }   
1.170     harris41 5757:     return 'ok';
1.80      www      5758: }
                   5759: 
1.81      www      5760: # --------------------------------------------------------------- Modify a user
1.80      www      5761: 
1.81      www      5762: sub modifyuser {
1.206     matthew  5763:     my ($udom,    $uname, $uid,
                   5764:         $umode,   $upass, $first,
                   5765:         $middle,  $last,  $gene,
1.963     raeburn  5766:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5767:     $udom= &LONCAPA::clean_domain($udom);
                   5768:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5769:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5770:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5771: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5772:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5773:                                      ' desiredhome not specified'). 
1.620     albertel 5774:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5775:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5776:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5777: # ----------------------------------------------------------------- Create User
1.406     albertel 5778:     if (($uhome eq 'no_host') && 
                   5779: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5780:         my $unhome='';
1.844     albertel 5781:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5782:             $unhome = $desiredhome;
1.620     albertel 5783: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5784: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5785:         } else { # load balancing routine for determining $unhome
1.81      www      5786:             my $loadm=10000000;
1.841     albertel 5787: 	    my %servers = &get_servers($udom,'library');
                   5788: 	    foreach my $tryserver (keys(%servers)) {
                   5789: 		my $answer=reply('load',$tryserver);
                   5790: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5791: 		    $loadm=$answer;
                   5792: 		    $unhome=$tryserver;
                   5793: 		}
1.80      www      5794: 	    }
                   5795:         }
                   5796:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5797: 	    return 'error: unable to find a home server for '.$uname.
                   5798:                    ' in domain '.$udom;
1.80      www      5799:         }
                   5800:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5801:                          &escape($upass),$unhome);
                   5802: 	unless ($reply eq 'ok') {
                   5803:             return 'error: '.$reply;
                   5804:         }   
1.230     stredwic 5805:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5806:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5807: 	    return 'error: unable verify users home machine.';
1.80      www      5808:         }
1.209     matthew  5809:     }   # End of creation of new user
1.80      www      5810: # ---------------------------------------------------------------------- Add ID
                   5811:     if ($uid) {
                   5812:        $uid=~tr/A-Z/a-z/;
                   5813:        my %uidhash=&idrget($udom,$uname);
1.196     www      5814:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5815:          && (!$forceid)) {
1.80      www      5816: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5817: 	      return 'error: user id "'.$uid.'" does not match '.
                   5818:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5819:           }
                   5820:        } else {
                   5821: 	  &idput($udom,($uname => $uid));
                   5822:        }
                   5823:     }
                   5824: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5825:     my @tmp=&get('environment',
1.899     raeburn  5826: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5827:                     'permanentemail','inststatus'],
1.134     albertel 5828: 		   $udom,$uname);
1.313     matthew  5829:     my %names;
                   5830:     if ($tmp[0] =~ m/^error:.*/) { 
                   5831:         %names=(); 
                   5832:     } else {
                   5833:         %names = @tmp;
                   5834:     }
1.388     www      5835: #
                   5836: # Make sure to not trash student environment if instructor does not bother
                   5837: # to supply name and email information
                   5838: #
                   5839:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5840:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5841:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5842:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5843:     if ($email) {
                   5844:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5845:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5846:     }
1.899     raeburn  5847:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5848:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5849:     my $reply = &put('environment', \%names, $udom,$uname);
                   5850:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5851:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5852:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5853:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5854:                  $umode.', '.$first.', '.$middle.', '.
                   5855: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5856:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5857:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5858:     } else {
                   5859:         $logmsg .= ' during self creation';
                   5860:     }
                   5861:     &logthis($logmsg);
1.134     albertel 5862:     return 'ok';
1.80      www      5863: }
                   5864: 
1.81      www      5865: # -------------------------------------------------------------- Modify student
1.80      www      5866: 
1.81      www      5867: sub modifystudent {
                   5868:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5869:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5870:         $selfenroll,$context)=@_;
1.455     albertel 5871:     if (!$cid) {
1.620     albertel 5872: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5873: 	    return 'not_in_class';
                   5874: 	}
1.80      www      5875:     }
                   5876: # --------------------------------------------------------------- Make the user
1.81      www      5877:     my $reply=&modifyuser
1.209     matthew  5878: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5879:          $desiredhome,$email);
1.80      www      5880:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5881:     # This will cause &modify_student_enrollment to get the uid from the
                   5882:     # students environment
                   5883:     $uid = undef if (!$forceid);
1.455     albertel 5884:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5885: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5886:     return $reply;
                   5887: }
                   5888: 
                   5889: sub modify_student_enrollment {
1.957     raeburn  5890:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5891:     my ($cdom,$cnum,$chome);
                   5892:     if (!$cid) {
1.620     albertel 5893: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5894: 	    return 'not_in_class';
                   5895: 	}
1.620     albertel 5896: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5897: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5898:     } else {
                   5899: 	($cdom,$cnum)=split(/_/,$cid);
                   5900:     }
1.620     albertel 5901:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5902:     if (!$chome) {
1.457     raeburn  5903: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5904:     }
1.455     albertel 5905:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5906:     # Make sure the user exists
1.81      www      5907:     my $uhome=&homeserver($uname,$udom);
                   5908:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5909: 	return 'error: no such user';
                   5910:     }
1.297     matthew  5911:     # Get student data if we were not given enough information
                   5912:     if (!defined($first)  || $first  eq '' || 
                   5913:         !defined($last)   || $last   eq '' || 
                   5914:         !defined($uid)    || $uid    eq '' || 
                   5915:         !defined($middle) || $middle eq '' || 
                   5916:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5917:         # They did not supply us with enough data to enroll the student, so
                   5918:         # we need to pick up more information.
1.297     matthew  5919:         my %tmp = &get('environment',
1.294     matthew  5920:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5921:                        ,$udom,$uname);
                   5922: 
1.800     albertel 5923:         #foreach my $key (keys(%tmp)) {
                   5924:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5925:         #}
1.294     matthew  5926:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5927:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5928:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5929:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5930:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5931:     }
1.556     albertel 5932:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5933:     my $reply=cput('classlist',
                   5934: 		   {"$uname:$udom" => 
1.515     raeburn  5935: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5936: 		   $cdom,$cnum);
1.81      www      5937:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5938: 	return 'error: '.$reply;
1.652     albertel 5939:     } else {
                   5940: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5941:     }
1.297     matthew  5942:     # Add student role to user
1.83      www      5943:     my $uurl='/'.$cid;
1.81      www      5944:     $uurl=~s/\_/\//g;
                   5945:     if ($usec) {
                   5946: 	$uurl.='/'.$usec;
                   5947:     }
1.957     raeburn  5948:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5949: }
                   5950: 
1.556     albertel 5951: sub format_name {
                   5952:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5953:     my $name;
                   5954:     if ($first ne 'lastname') {
                   5955: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5956:     } else {
                   5957: 	if ($lastname=~/\S/) {
                   5958: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5959: 	    $name=~s/\s+,/,/;
                   5960: 	} else {
                   5961: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5962: 	}
                   5963:     }
                   5964:     $name=~s/^\s+//;
                   5965:     $name=~s/\s+$//;
                   5966:     $name=~s/\s+/ /g;
                   5967:     return $name;
                   5968: }
                   5969: 
1.84      www      5970: # ------------------------------------------------- Write to course preferences
                   5971: 
                   5972: sub writecoursepref {
                   5973:     my ($courseid,%prefs)=@_;
                   5974:     $courseid=~s/^\///;
                   5975:     $courseid=~s/\_/\//g;
                   5976:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5977:     my $chome=homeserver($cnum,$cdomain);
                   5978:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5979: 	return 'error: no such course';
                   5980:     }
                   5981:     my $cstring='';
1.800     albertel 5982:     foreach my $pref (keys(%prefs)) {
                   5983: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5984:     }
1.84      www      5985:     $cstring=~s/\&$//;
                   5986:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5987: }
                   5988: 
                   5989: # ---------------------------------------------------------- Make/modify course
                   5990: 
                   5991: sub createcourse {
1.741     raeburn  5992:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5993:         $course_owner,$crstype)=@_;
1.84      www      5994:     $url=&declutter($url);
                   5995:     my $cid='';
1.264     matthew  5996:     unless (&allowed('ccc',$udom)) {
1.84      www      5997:         return 'refused';
                   5998:     }
                   5999: # ------------------------------------------------------------------- Create ID
1.674     www      6000:    my $uname=int(1+rand(9)).
                   6001:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6002:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6003:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6004: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6005:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6006:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6007:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6008:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6009:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6010:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6011:            return 'error: unable to generate unique course-ID';
                   6012:        } 
                   6013:    }
1.264     matthew  6014: # ------------------------------------------------ Check supplied server name
1.620     albertel 6015:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6016:     if (! &is_library($course_server)) {
1.264     matthew  6017:         return 'error:bad server name '.$course_server;
                   6018:     }
1.84      www      6019: # ------------------------------------------------------------- Make the course
                   6020:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6021:                       $course_server);
1.84      www      6022:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6023:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6024:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6025: 	return 'error: no such course';
                   6026:     }
1.271     www      6027: # ----------------------------------------------------------------- Course made
1.516     raeburn  6028: # log existence
1.918     raeburn  6029:     my $newcourse = {
                   6030:                     $udom.'_'.$uname => {
1.921     raeburn  6031:                                      description => $description,
                   6032:                                      inst_code   => $inst_code,
                   6033:                                      owner       => $course_owner,
                   6034:                                      type        => $crstype,
1.918     raeburn  6035:                                                 },
                   6036:                     };
1.921     raeburn  6037:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6038: # set toplevel url
1.271     www      6039:     my $topurl=$url;
                   6040:     unless ($nonstandard) {
                   6041: # ------------------------------------------ For standard courses, make top url
                   6042:         my $mapurl=&clutter($url);
1.278     www      6043:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6044:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6045: <map>
                   6046: <resource id="1" type="start"></resource>
                   6047: <resource id="2" src="$mapurl"></resource>
                   6048: <resource id="3" type="finish"></resource>
                   6049: <link index="1" from="1" to="2"></link>
                   6050: <link index="2" from="2" to="3"></link>
                   6051: </map>
                   6052: ENDINITMAP
                   6053:         $topurl=&declutter(
1.638     albertel 6054:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6055:                           );
                   6056:     }
                   6057: # ----------------------------------------------------------- Write preferences
1.84      www      6058:     &writecoursepref($udom.'_'.$uname,
                   6059:                      ('description' => $description,
1.271     www      6060:                       'url'         => $topurl));
1.84      www      6061:     return '/'.$udom.'/'.$uname;
                   6062: }
                   6063: 
1.813     albertel 6064: sub is_course {
                   6065:     my ($cdom,$cnum) = @_;
                   6066:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6067: 				undef,'.');
1.813     albertel 6068:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6069:         return 1;
                   6070:     }
                   6071:     return 0;
                   6072: }
                   6073: 
1.21      www      6074: # ---------------------------------------------------------- Assign Custom Role
                   6075: 
                   6076: sub assigncustomrole {
1.957     raeburn  6077:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6078:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6079:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6080: }
                   6081: 
                   6082: # ----------------------------------------------------------------- Revoke Role
                   6083: 
                   6084: sub revokerole {
1.957     raeburn  6085:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6086:     my $now=time;
1.965     raeburn  6087:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6088: }
                   6089: 
                   6090: # ---------------------------------------------------------- Revoke Custom Role
                   6091: 
                   6092: sub revokecustomrole {
1.957     raeburn  6093:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6094:     my $now=time;
1.357     www      6095:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6096:            $deleteflag,$selfenroll,$context);
1.17      www      6097: }
                   6098: 
1.533     banghart 6099: # ------------------------------------------------------------ Disk usage
1.535     albertel 6100: sub diskusage {
1.955     raeburn  6101:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6102:     $directorypath =~ s/\/$//;
                   6103:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6104:                        .&escape($getpropath).':'.&escape($uname).':'
                   6105:                        .&escape($udom),homeserver($uname,$udom));
                   6106:     if ($listing eq 'unknown_cmd') {
                   6107:         if ($getpropath) {
                   6108:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6109:         }
                   6110:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6111:     }
1.514     albertel 6112:     return $listing;
1.512     banghart 6113: }
                   6114: 
1.566     banghart 6115: sub is_locked {
                   6116:     my ($file_name, $domain, $user) = @_;
                   6117:     my @check;
                   6118:     my $is_locked;
                   6119:     push @check, $file_name;
1.613     albertel 6120:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6121: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6122:     my ($tmp)=keys(%locked);
                   6123:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6124:     
1.566     banghart 6125:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6126:         $is_locked = 'false';
                   6127:         foreach my $entry (@{$locked{$file_name}}) {
                   6128:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6129:                $is_locked = 'true';
                   6130:                last;
1.745     raeburn  6131:            }
                   6132:        }
1.566     banghart 6133:     } else {
                   6134:         $is_locked = 'false';
                   6135:     }
                   6136: }
                   6137: 
1.759     albertel 6138: sub declutter_portfile {
                   6139:     my ($file) = @_;
1.833     albertel 6140:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6141:     return $file;
                   6142: }
                   6143: 
1.559     banghart 6144: # ------------------------------------------------------------- Mark as Read Only
                   6145: 
                   6146: sub mark_as_readonly {
                   6147:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6148:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6149:     my ($tmp)=keys(%current_permissions);
                   6150:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6151:     foreach my $file (@{$files}) {
1.759     albertel 6152: 	$file = &declutter_portfile($file);
1.561     banghart 6153:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6154:     }
1.613     albertel 6155:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6156:     return;
                   6157: }
                   6158: 
1.572     banghart 6159: # ------------------------------------------------------------Save Selected Files
                   6160: 
                   6161: sub save_selected_files {
                   6162:     my ($user, $path, @files) = @_;
                   6163:     my $filename = $user."savedfiles";
1.573     banghart 6164:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6165:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6166:     foreach my $file (@files) {
1.620     albertel 6167:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6168:     }
                   6169:     foreach my $file (@other_files) {
1.574     banghart 6170:         print (OUT $file."\n");
1.572     banghart 6171:     }
1.574     banghart 6172:     close (OUT);
1.572     banghart 6173:     return 'ok';
                   6174: }
                   6175: 
1.574     banghart 6176: sub clear_selected_files {
                   6177:     my ($user) = @_;
                   6178:     my $filename = $user."savedfiles";
                   6179:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6180:     print (OUT undef);
                   6181:     close (OUT);
                   6182:     return ("ok");    
                   6183: }
                   6184: 
1.572     banghart 6185: sub files_in_path {
                   6186:     my ($user, $path) = @_;
                   6187:     my $filename = $user."savedfiles";
                   6188:     my %return_files;
1.574     banghart 6189:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6190:     while (my $line_in = <IN>) {
1.574     banghart 6191:         chomp ($line_in);
                   6192:         my @paths_and_file = split (m!/!, $line_in);
                   6193:         my $file_part = pop (@paths_and_file);
                   6194:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6195:         $path_part.='/';
                   6196:         my $path_and_file = $path_part.$file_part;
                   6197:         if ($path_part eq $path) {
                   6198:             $return_files{$file_part}= 'selected';
                   6199:         }
                   6200:     }
1.574     banghart 6201:     close (IN);
                   6202:     return (\%return_files);
1.572     banghart 6203: }
                   6204: 
                   6205: # called in portfolio select mode, to show files selected NOT in current directory
                   6206: sub files_not_in_path {
                   6207:     my ($user, $path) = @_;
                   6208:     my $filename = $user."savedfiles";
                   6209:     my @return_files;
                   6210:     my $path_part;
1.800     albertel 6211:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6212:     while (my $line = <IN>) {
1.572     banghart 6213:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6214:         my @paths_and_file = split(m|/|, $line);
                   6215:         my $file_part = pop(@paths_and_file);
                   6216:         chomp($file_part);
                   6217:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6218:         $path_part .= '/';
                   6219:         my $path_and_file = $path_part.$file_part;
                   6220:         if ($path_part ne $path) {
1.800     albertel 6221:             push(@return_files, ($path_and_file));
1.572     banghart 6222:         }
                   6223:     }
1.800     albertel 6224:     close(OUT);
1.574     banghart 6225:     return (@return_files);
1.572     banghart 6226: }
                   6227: 
1.745     raeburn  6228: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6229: 
1.745     raeburn  6230: sub get_portfile_permissions {
                   6231:     my ($domain,$user) = @_;
1.613     albertel 6232:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6233:     my ($tmp)=keys(%current_permissions);
                   6234:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6235:     return \%current_permissions;
                   6236: }
                   6237: 
                   6238: #---------------------------------------------Get portfolio file access controls
                   6239: 
1.749     raeburn  6240: sub get_access_controls {
1.745     raeburn  6241:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6242:     my %access;
                   6243:     my $real_file = $file;
                   6244:     $file =~ s/\.meta$//;
1.745     raeburn  6245:     if (defined($file)) {
1.749     raeburn  6246:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6247:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6248:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6249:             }
                   6250:         }
1.745     raeburn  6251:     } else {
1.749     raeburn  6252:         foreach my $key (keys(%{$current_permissions})) {
                   6253:             if ($key =~ /\0accesscontrol$/) {
                   6254:                 if (defined($group)) {
                   6255:                     if ($key !~ m-^\Q$group\E/-) {
                   6256:                         next;
                   6257:                     }
                   6258:                 }
                   6259:                 my ($fullpath) = split(/\0/,$key);
                   6260:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6261:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6262:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6263:                     }
                   6264:                 }
                   6265:             }
                   6266:         }
                   6267:     }
                   6268:     return %access;
                   6269: }
                   6270: 
                   6271: sub modify_access_controls {
                   6272:     my ($file_name,$changes,$domain,$user)=@_;
                   6273:     my ($outcome,$deloutcome);
                   6274:     my %store_permissions;
                   6275:     my %new_values;
                   6276:     my %new_control;
                   6277:     my %translation;
                   6278:     my @deletions = ();
                   6279:     my $now = time;
                   6280:     if (exists($$changes{'activate'})) {
                   6281:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6282:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6283:             my $numnew = scalar(@newitems);
                   6284:             for (my $i=0; $i<$numnew; $i++) {
                   6285:                 my $newkey = $newitems[$i];
                   6286:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6287:                 if ($newkey =~ /^\d+:/) { 
                   6288:                     $newkey =~ s/^(\d+)/$newid/;
                   6289:                     $translation{$1} = $newid;
                   6290:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6291:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6292:                     $translation{$1} = $newid;
                   6293:                 }
1.749     raeburn  6294:                 $new_values{$file_name."\0".$newkey} = 
                   6295:                                           $$changes{'activate'}{$newitems[$i]};
                   6296:                 $new_control{$newkey} = $now;
                   6297:             }
                   6298:         }
                   6299:     }
                   6300:     my %todelete;
                   6301:     my %changed_items;
                   6302:     foreach my $action ('delete','update') {
                   6303:         if (exists($$changes{$action})) {
                   6304:             if (ref($$changes{$action}) eq 'HASH') {
                   6305:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6306:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6307:                     if ($action eq 'delete') { 
                   6308:                         $todelete{$itemnum} = 1;
                   6309:                     } else {
                   6310:                         $changed_items{$itemnum} = $key;
                   6311:                     }
                   6312:                 }
1.745     raeburn  6313:             }
                   6314:         }
1.749     raeburn  6315:     }
                   6316:     # get lock on access controls for file.
                   6317:     my $lockhash = {
                   6318:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6319:                                                        ':'.$env{'user.domain'},
                   6320:                    }; 
                   6321:     my $tries = 0;
                   6322:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6323:    
                   6324:     while (($gotlock ne 'ok') && $tries <3) {
                   6325:         $tries ++;
                   6326:         sleep 1;
                   6327:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6328:     }
                   6329:     if ($gotlock eq 'ok') {
                   6330:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6331:         my ($tmp)=keys(%curr_permissions);
                   6332:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6333:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6334:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6335:             if (ref($curr_controls) eq 'HASH') {
                   6336:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6337:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6338:                     if (defined($todelete{$itemnum})) {
                   6339:                         push(@deletions,$file_name."\0".$control_item);
                   6340:                     } else {
                   6341:                         if (defined($changed_items{$itemnum})) {
                   6342:                             $new_control{$changed_items{$itemnum}} = $now;
                   6343:                             push(@deletions,$file_name."\0".$control_item);
                   6344:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6345:                         } else {
                   6346:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6347:                         }
                   6348:                     }
1.745     raeburn  6349:                 }
                   6350:             }
                   6351:         }
1.970     raeburn  6352:         my ($group);
                   6353:         if (&is_course($domain,$user)) {
                   6354:             ($group,my $file) = split(/\//,$file_name,2);
                   6355:         }
1.749     raeburn  6356:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6357:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6358:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6359:         #  remove lock
                   6360:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6361:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6362:         my $sqlresult =
1.970     raeburn  6363:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6364:                                     $group);
1.749     raeburn  6365:     } else {
                   6366:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6367:     }
1.749     raeburn  6368:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6369: }
                   6370: 
1.827     raeburn  6371: sub make_public_indefinitely {
                   6372:     my ($requrl) = @_;
                   6373:     my $now = time;
                   6374:     my $action = 'activate';
                   6375:     my $aclnum = 0;
                   6376:     if (&is_portfolio_url($requrl)) {
                   6377:         my (undef,$udom,$unum,$file_name,$group) =
                   6378:             &parse_portfolio_url($requrl);
                   6379:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6380:         my %access_controls = &get_access_controls($current_perms,
                   6381:                                                    $group,$file_name);
                   6382:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6383:             my ($num,$scope,$end,$start) = 
                   6384:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6385:             if ($scope eq 'public') {
                   6386:                 if ($start <= $now && $end == 0) {
                   6387:                     $action = 'none';
                   6388:                 } else {
                   6389:                     $action = 'update';
                   6390:                     $aclnum = $num;
                   6391:                 }
                   6392:                 last;
                   6393:             }
                   6394:         }
                   6395:         if ($action eq 'none') {
                   6396:              return 'ok';
                   6397:         } else {
                   6398:             my %changes;
                   6399:             my $newend = 0;
                   6400:             my $newstart = $now;
                   6401:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6402:             $changes{$action}{$newkey} = {
                   6403:                 type => 'public',
                   6404:                 time => {
                   6405:                     start => $newstart,
                   6406:                     end   => $newend,
                   6407:                 },
                   6408:             };
                   6409:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6410:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6411:             return $outcome;
                   6412:         }
                   6413:     } else {
                   6414:         return 'invalid';
                   6415:     }
                   6416: }
                   6417: 
1.745     raeburn  6418: #------------------------------------------------------Get Marked as Read Only
                   6419: 
                   6420: sub get_marked_as_readonly {
                   6421:     my ($domain,$user,$what,$group) = @_;
                   6422:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6423:     my @readonly_files;
1.629     banghart 6424:     my $cmp1=$what;
                   6425:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6426:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6427:         if (defined($group)) {
                   6428:             if ($file_name !~ m-^\Q$group\E/-) {
                   6429:                 next;
                   6430:             }
                   6431:         }
1.561     banghart 6432:         if (ref($value) eq "ARRAY"){
                   6433:             foreach my $stored_what (@{$value}) {
1.629     banghart 6434:                 my $cmp2=$stored_what;
1.759     albertel 6435:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6436:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6437:                 }
1.629     banghart 6438:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6439:                     push(@readonly_files, $file_name);
1.745     raeburn  6440:                     last;
1.563     banghart 6441:                 } elsif (!defined($what)) {
                   6442:                     push(@readonly_files, $file_name);
1.745     raeburn  6443:                     last;
1.561     banghart 6444:                 }
                   6445:             }
1.745     raeburn  6446:         }
1.561     banghart 6447:     }
                   6448:     return @readonly_files;
                   6449: }
1.577     banghart 6450: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6451: 
1.577     banghart 6452: sub get_marked_as_readonly_hash {
1.745     raeburn  6453:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6454:     my %readonly_files;
1.745     raeburn  6455:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6456:         if (defined($group)) {
                   6457:             if ($file_name !~ m-^\Q$group\E/-) {
                   6458:                 next;
                   6459:             }
                   6460:         }
1.577     banghart 6461:         if (ref($value) eq "ARRAY"){
                   6462:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6463:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6464:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6465:                         if ($lock_descriptor eq 'graded') {
                   6466:                             $readonly_files{$file_name} = 'graded';
                   6467:                         } elsif ($lock_descriptor eq 'handback') {
                   6468:                             $readonly_files{$file_name} = 'handback';
                   6469:                         } else {
                   6470:                             if (!exists($readonly_files{$file_name})) {
                   6471:                                 $readonly_files{$file_name} = 'locked';
                   6472:                             }
                   6473:                         }
1.745     raeburn  6474:                     }
1.750     banghart 6475:                 } 
1.577     banghart 6476:             }
                   6477:         } 
                   6478:     }
                   6479:     return %readonly_files;
                   6480: }
1.559     banghart 6481: # ------------------------------------------------------------ Unmark as Read Only
                   6482: 
                   6483: sub unmark_as_readonly {
1.629     banghart 6484:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6485:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6486:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6487:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6488:     my $symb_crs = $what;
                   6489:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6490:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6491:     my ($tmp)=keys(%current_permissions);
                   6492:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6493:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6494:     foreach my $file (@readonly_files) {
1.759     albertel 6495: 	my $clean_file = &declutter_portfile($file);
                   6496: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6497: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6498:         my @new_locks;
                   6499:         my @del_keys;
                   6500:         if (ref($current_locks) eq "ARRAY"){
                   6501:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6502:                 my $compare=$locker;
1.749     raeburn  6503:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6504:                     $compare=join('',@{$locker});
1.746     raeburn  6505:                     if ($compare ne $symb_crs) {
                   6506:                         push(@new_locks, $locker);
                   6507:                     }
1.563     banghart 6508:                 }
                   6509:             }
1.650     albertel 6510:             if (scalar(@new_locks) > 0) {
1.563     banghart 6511:                 $current_permissions{$file} = \@new_locks;
                   6512:             } else {
                   6513:                 push(@del_keys, $file);
1.613     albertel 6514:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6515:                 delete($current_permissions{$file});
1.563     banghart 6516:             }
                   6517:         }
1.561     banghart 6518:     }
1.613     albertel 6519:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6520:     return;
                   6521: }
1.512     banghart 6522: 
1.17      www      6523: # ------------------------------------------------------------ Directory lister
                   6524: 
                   6525: sub dirlist {
1.955     raeburn  6526:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6527:     $uri=~s/^\///;
                   6528:     $uri=~s/\/$//;
1.253     stredwic 6529:     my ($udom, $uname);
1.955     raeburn  6530:     if ($getuserdir) {
1.253     stredwic 6531:         $udom = $userdomain;
                   6532:         $uname = $username;
1.955     raeburn  6533:     } else {
                   6534:         (undef,$udom,$uname)=split(/\//,$uri);
                   6535:         if(defined($userdomain)) {
                   6536:             $udom = $userdomain;
                   6537:         }
                   6538:         if(defined($username)) {
                   6539:             $uname = $username;
                   6540:         }
1.253     stredwic 6541:     }
1.955     raeburn  6542:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6543: 
1.955     raeburn  6544:     $dirRoot = $perlvar{'lonDocRoot'};
                   6545:     if (defined($getpropath)) {
                   6546:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6547:         $dirRoot =~ s/\/$//;
1.955     raeburn  6548:     } elsif (defined($getuserdir)) {
                   6549:         my $subdir=$uname.'__';
                   6550:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6551:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6552:                    ."/$udom/$subdir/$uname";
                   6553:     } elsif (defined($alternateRoot)) {
                   6554:         $dirRoot = $alternateRoot;
1.751     banghart 6555:     }
1.253     stredwic 6556: 
                   6557:     if($udom) {
                   6558:         if($uname) {
1.955     raeburn  6559:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6560:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6561:                               .':'.&escape($uname).':'.&escape($udom),
                   6562:                               &homeserver($uname,$udom));
                   6563:             if ($listing eq 'unknown_cmd') {
                   6564:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6565:                                   &homeserver($uname,$udom));
                   6566:             } else {
                   6567:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6568:             }
1.605     matthew  6569:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6570:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6571: 				  &homeserver($uname,$udom));
1.605     matthew  6572:                 @listing_results = split(/:/,$listing);
                   6573:             } else {
                   6574:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6575:             }
                   6576:             return @listing_results;
1.955     raeburn  6577:         } elsif(!$alternateRoot) {
1.800     albertel 6578:             my %allusers;
1.841     albertel 6579: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6580:  	    foreach my $tryserver (keys(%servers)) {
                   6581:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6582:                                   &escape($udom),$tryserver);
                   6583:                 if ($listing eq 'unknown_cmd') {
                   6584: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6585: 				      $udom, $tryserver);
                   6586:                 } else {
                   6587:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6588:                 }
1.841     albertel 6589: 		if ($listing eq 'unknown_cmd') {
                   6590: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6591: 				      $udom, $tryserver);
                   6592: 		    @listing_results = split(/:/,$listing);
                   6593: 		} else {
                   6594: 		    @listing_results =
                   6595: 			map { &unescape($_); } split(/:/,$listing);
                   6596: 		}
                   6597: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6598: 		    $listing_results[0] ne 'empty'       &&
                   6599: 		    $listing_results[0] ne 'con_lost') {
                   6600: 		    foreach my $line (@listing_results) {
                   6601: 			my ($entry) = split(/&/,$line,2);
                   6602: 			$allusers{$entry} = 1;
                   6603: 		    }
                   6604: 		}
1.253     stredwic 6605:             }
                   6606:             my $alluserstr='';
1.800     albertel 6607:             foreach my $user (sort(keys(%allusers))) {
                   6608:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6609:             }
                   6610:             $alluserstr=~s/:$//;
                   6611:             return split(/:/,$alluserstr);
                   6612:         } else {
1.800     albertel 6613:             return ('missing user name');
1.253     stredwic 6614:         }
1.955     raeburn  6615:     } elsif(!defined($getpropath)) {
1.841     albertel 6616:         my @all_domains = sort(&all_domains());
1.955     raeburn  6617:         foreach my $domain (@all_domains) {
                   6618:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6619:         }
                   6620:         return @all_domains;
                   6621:     } else {
1.800     albertel 6622:         return ('missing domain');
1.275     stredwic 6623:     }
                   6624: }
                   6625: 
                   6626: # --------------------------------------------- GetFileTimestamp
                   6627: # This function utilizes dirlist and returns the date stamp for
                   6628: # when it was last modified.  It will also return an error of -1
                   6629: # if an error occurs
                   6630: 
                   6631: sub GetFileTimestamp {
1.955     raeburn  6632:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6633:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6634:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6635:     my ($fileStat) = 
                   6636:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6637:                                  undef,$getuserdir);
1.275     stredwic 6638:     my @stats = split('&', $fileStat);
                   6639:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6640:         # @stats contains first the filename, then the stat output
                   6641:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6642:     } else {
                   6643:         return -1;
1.253     stredwic 6644:     }
1.26      www      6645: }
                   6646: 
1.712     albertel 6647: sub stat_file {
                   6648:     my ($uri) = @_;
1.787     albertel 6649:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6650: 
1.955     raeburn  6651:     my ($udom,$uname,$file);
1.712     albertel 6652:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6653: 	($udom,$uname,$file) =
1.811     albertel 6654: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6655: 	$file = 'userfiles/'.$file;
                   6656:     }
                   6657:     if ($uri =~ m-^/res/-) {
                   6658: 	($udom,$uname) = 
1.807     albertel 6659: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6660: 	$file = $uri;
                   6661:     }
                   6662: 
                   6663:     if (!$udom || !$uname || !$file) {
                   6664: 	# unable to handle the uri
                   6665: 	return ();
                   6666:     }
1.956     raeburn  6667:     my $getpropath;
                   6668:     if ($file =~ /^userfiles\//) {
                   6669:         $getpropath = 1;
                   6670:     }
1.955     raeburn  6671:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6672:     my @stats = split('&', $result);
1.721     banghart 6673:     
1.712     albertel 6674:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6675: 	shift(@stats); #filename is first
                   6676: 	return @stats;
                   6677:     }
                   6678:     return ();
                   6679: }
                   6680: 
1.26      www      6681: # -------------------------------------------------------- Value of a Condition
                   6682: 
1.713     albertel 6683: # gets the value of a specific preevaluated condition
                   6684: #    stored in the string  $env{user.state.<cid>}
                   6685: # or looks up a condition reference in the bighash and if if hasn't
                   6686: # already been evaluated recurses into docondval to get the value of
                   6687: # the condition, then memoizing it to 
                   6688: #   $env{user.state.<cid>.<condition>}
1.40      www      6689: sub directcondval {
                   6690:     my $number=shift;
1.620     albertel 6691:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6692: 	&Apache::lonuserstate::evalstate();
                   6693:     }
1.713     albertel 6694:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6695: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6696:     } elsif ($number =~ /^_/) {
                   6697: 	my $sub_condition;
                   6698: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6699: 		&GDBM_READER(),0640)) {
                   6700: 	    $sub_condition=$bighash{'conditions'.$number};
                   6701: 	    untie(%bighash);
                   6702: 	}
                   6703: 	my $value = &docondval($sub_condition);
1.949     raeburn  6704: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6705: 	return $value;
                   6706:     }
1.620     albertel 6707:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6708:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6709:     } else {
                   6710:        return 2;
                   6711:     }
                   6712: }
                   6713: 
1.713     albertel 6714: # get the collection of conditions for this resource
1.26      www      6715: sub condval {
                   6716:     my $condidx=shift;
1.54      www      6717:     my $allpathcond='';
1.713     albertel 6718:     foreach my $cond (split(/\|/,$condidx)) {
                   6719: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6720: 	    $allpathcond.=
                   6721: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6722: 	}
1.191     harris41 6723:     }
1.54      www      6724:     $allpathcond=~s/\|$//;
1.713     albertel 6725:     return &docondval($allpathcond);
                   6726: }
                   6727: 
                   6728: #evaluates an expression of conditions
                   6729: sub docondval {
                   6730:     my ($allpathcond) = @_;
                   6731:     my $result=0;
                   6732:     if ($env{'request.course.id'}
                   6733: 	&& defined($allpathcond)) {
                   6734: 	my $operand='|';
                   6735: 	my @stack;
                   6736: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6737: 	    if ($chunk eq '(') {
                   6738: 		push @stack,($operand,$result);
                   6739: 	    } elsif ($chunk eq ')') {
                   6740: 		my $before=pop @stack;
                   6741: 		if (pop @stack eq '&') {
                   6742: 		    $result=$result>$before?$before:$result;
                   6743: 		} else {
                   6744: 		    $result=$result>$before?$result:$before;
                   6745: 		}
                   6746: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6747: 		$operand=$chunk;
                   6748: 	    } else {
                   6749: 		my $new=directcondval($chunk);
                   6750: 		if ($operand eq '&') {
                   6751: 		    $result=$result>$new?$new:$result;
                   6752: 		} else {
                   6753: 		    $result=$result>$new?$result:$new;
                   6754: 		}
                   6755: 	    }
                   6756: 	}
1.26      www      6757:     }
                   6758:     return $result;
1.421     albertel 6759: }
                   6760: 
                   6761: # ---------------------------------------------------- Devalidate courseresdata
                   6762: 
                   6763: sub devalidatecourseresdata {
                   6764:     my ($coursenum,$coursedomain)=@_;
                   6765:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6766:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6767: }
                   6768: 
1.763     www      6769: 
1.200     www      6770: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6771: #
                   6772: #  Parameters:
                   6773: #      $coursenum    - Number of the course.
                   6774: #      $coursedomain - Domain at which the course was created.
                   6775: #  Returns:
                   6776: #     A hash of the course parameters along (I think) with timestamps
                   6777: #     and version info.
1.877     foxr     6778: 
1.624     albertel 6779: sub get_courseresdata {
                   6780:     my ($coursenum,$coursedomain)=@_;
1.200     www      6781:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6782:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6783:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6784:     my %dumpreply;
1.417     albertel 6785:     unless (defined($cached)) {
1.624     albertel 6786: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6787: 	$result=\%dumpreply;
1.251     albertel 6788: 	my ($tmp) = keys(%dumpreply);
                   6789: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6790: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6791: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6792: 	    return $tmp;
1.416     albertel 6793: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6794: 	    $result=undef;
1.599     albertel 6795: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6796: 	}
                   6797:     }
1.624     albertel 6798:     return $result;
                   6799: }
                   6800: 
1.633     albertel 6801: sub devalidateuserresdata {
                   6802:     my ($uname,$udom)=@_;
                   6803:     my $hashid="$udom:$uname";
                   6804:     &devalidate_cache_new('userres',$hashid);
                   6805: }
                   6806: 
1.624     albertel 6807: sub get_userresdata {
                   6808:     my ($uname,$udom)=@_;
                   6809:     #most student don\'t have any data set, check if there is some data
                   6810:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6811: 
                   6812:     my $hashid="$udom:$uname";
                   6813:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6814:     if (!defined($cached)) {
                   6815: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6816: 	$result=\%resourcedata;
                   6817: 	&do_cache_new('userres',$hashid,$result,600);
                   6818:     }
                   6819:     my ($tmp)=keys(%$result);
                   6820:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6821: 	return $result;
                   6822:     }
                   6823:     #error 2 occurs when the .db doesn't exist
                   6824:     if ($tmp!~/error: 2 /) {
1.672     albertel 6825: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6826: 		 " Trying to get resource data for ".
                   6827: 		 $uname." at ".$udom.": ".
                   6828: 		 $tmp."</font>");
                   6829:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6830: 	#&EXT_cache_set($udom,$uname);
                   6831: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6832: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6833:     }
                   6834:     return $tmp;
                   6835: }
1.879     foxr     6836: #----------------------------------------------- resdata - return resource data
                   6837: #  Purpose:
                   6838: #    Return resource data for either users or for a course.
                   6839: #  Parameters:
                   6840: #     $name      - Course/user name.
                   6841: #     $domain    - Name of the domain the user/course is registered on.
                   6842: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6843: #     @which     - Array of names of resources desired.
                   6844: #  Returns:
                   6845: #     The value of the first reasource in @which that is found in the
                   6846: #     resource hash.
                   6847: #  Exceptional Conditions:
                   6848: #     If the $type passed in is not valid (not the string 'course' or 
                   6849: #     'user', an undefined  reference is returned.
                   6850: #     If none of the resources are found, an undef is returned
1.624     albertel 6851: sub resdata {
                   6852:     my ($name,$domain,$type,@which)=@_;
                   6853:     my $result;
                   6854:     if ($type eq 'course') {
                   6855: 	$result=&get_courseresdata($name,$domain);
                   6856:     } elsif ($type eq 'user') {
                   6857: 	$result=&get_userresdata($name,$domain);
                   6858:     }
                   6859:     if (!ref($result)) { return $result; }    
1.251     albertel 6860:     foreach my $item (@which) {
1.927     albertel 6861: 	if (defined($result->{$item->[0]})) {
                   6862: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6863: 	}
1.250     albertel 6864:     }
1.291     albertel 6865:     return undef;
1.200     www      6866: }
                   6867: 
1.379     matthew  6868: #
                   6869: # EXT resource caching routines
                   6870: #
                   6871: 
                   6872: sub clear_EXT_cache_status {
1.383     albertel 6873:     &delenv('cache.EXT.');
1.379     matthew  6874: }
                   6875: 
                   6876: sub EXT_cache_status {
                   6877:     my ($target_domain,$target_user) = @_;
1.383     albertel 6878:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6879:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6880:         # We know already the user has no data
                   6881:         return 1;
                   6882:     } else {
                   6883:         return 0;
                   6884:     }
                   6885: }
                   6886: 
                   6887: sub EXT_cache_set {
                   6888:     my ($target_domain,$target_user) = @_;
1.383     albertel 6889:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6890:     #&appenv({$cachename => time});
1.379     matthew  6891: }
                   6892: 
1.28      www      6893: # --------------------------------------------------------- Value of a Variable
1.58      www      6894: sub EXT {
1.715     albertel 6895: 
1.395     albertel 6896:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6897:     unless ($varname) { return ''; }
1.218     albertel 6898:     #get real user name/domain, courseid and symb
                   6899:     my $courseid;
1.359     albertel 6900:     my $publicuser;
1.427     www      6901:     if ($symbparm) {
                   6902: 	$symbparm=&get_symb_from_alias($symbparm);
                   6903:     }
1.218     albertel 6904:     if (!($uname && $udom)) {
1.790     albertel 6905:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6906:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6907:     } else {
1.620     albertel 6908: 	$courseid=$env{'request.course.id'};
1.218     albertel 6909:     }
1.48      www      6910:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6911:     my $rest;
1.320     albertel 6912:     if (defined($therest[0])) {
1.48      www      6913:        $rest=join('.',@therest);
                   6914:     } else {
                   6915:        $rest='';
                   6916:     }
1.320     albertel 6917: 
1.57      www      6918:     my $qualifierrest=$qualifier;
                   6919:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6920:     my $spacequalifierrest=$space;
                   6921:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6922:     if ($realm eq 'user') {
1.48      www      6923: # --------------------------------------------------------------- user.resource
                   6924: 	if ($space eq 'resource') {
1.651     albertel 6925: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6926: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6927: 		 &&
1.744     albertel 6928: 		 ($symbparm eq &symbread()) ) {	
                   6929: 		# if we are in the middle of processing the resource the
                   6930: 		# get the value we are planning on committing
                   6931:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6932:                     return $Apache::lonhomework::results{$qualifierrest};
                   6933:                 } else {
                   6934:                     return $Apache::lonhomework::history{$qualifierrest};
                   6935:                 }
1.335     albertel 6936: 	    } else {
1.359     albertel 6937: 		my %restored;
1.620     albertel 6938: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6939: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6940: 		} else {
                   6941: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6942: 		}
1.335     albertel 6943: 		return $restored{$qualifierrest};
                   6944: 	    }
1.48      www      6945: # ----------------------------------------------------------------- user.access
                   6946:         } elsif ($space eq 'access') {
1.218     albertel 6947: 	    # FIXME - not supporting calls for a specific user
1.48      www      6948:             return &allowed($qualifier,$rest);
                   6949: # ------------------------------------------ user.preferences, user.environment
                   6950:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6951: 	    if (($uname eq $env{'user.name'}) &&
                   6952: 		($udom eq $env{'user.domain'})) {
                   6953: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6954: 	    } else {
1.359     albertel 6955: 		my %returnhash;
                   6956: 		if (!$publicuser) {
                   6957: 		    %returnhash=&userenvironment($udom,$uname,
                   6958: 						 $qualifierrest);
                   6959: 		}
1.218     albertel 6960: 		return $returnhash{$qualifierrest};
                   6961: 	    }
1.48      www      6962: # ----------------------------------------------------------------- user.course
                   6963:         } elsif ($space eq 'course') {
1.218     albertel 6964: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6965:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6966: # ------------------------------------------------------------------- user.role
                   6967:         } elsif ($space eq 'role') {
1.218     albertel 6968: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6969:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6970:             if ($qualifier eq 'value') {
                   6971: 		return $role;
                   6972:             } elsif ($qualifier eq 'extent') {
                   6973:                 return $where;
                   6974:             }
                   6975: # ----------------------------------------------------------------- user.domain
                   6976:         } elsif ($space eq 'domain') {
1.218     albertel 6977:             return $udom;
1.48      www      6978: # ------------------------------------------------------------------- user.name
                   6979:         } elsif ($space eq 'name') {
1.218     albertel 6980:             return $uname;
1.48      www      6981: # ---------------------------------------------------- Any other user namespace
1.29      www      6982:         } else {
1.359     albertel 6983: 	    my %reply;
                   6984: 	    if (!$publicuser) {
                   6985: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6986: 	    }
                   6987: 	    return $reply{$qualifierrest};
1.48      www      6988:         }
1.236     www      6989:     } elsif ($realm eq 'query') {
                   6990: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6991:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6992: 						[$spacequalifierrest]);
1.620     albertel 6993: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6994:    } elsif ($realm eq 'request') {
1.48      www      6995: # ------------------------------------------------------------- request.browser
                   6996:         if ($space eq 'browser') {
1.430     www      6997: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6998: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6999: 		    return 1;
                   7000: 		} else {
                   7001: 		    return 0;
                   7002: 		}
                   7003: 	    } else {
1.620     albertel 7004: 		return $env{'browser.'.$qualifier};
1.430     www      7005: 	    }
1.57      www      7006: # ------------------------------------------------------------ request.filename
                   7007:         } else {
1.620     albertel 7008:             return $env{'request.'.$spacequalifierrest};
1.29      www      7009:         }
1.28      www      7010:     } elsif ($realm eq 'course') {
1.48      www      7011: # ---------------------------------------------------------- course.description
1.620     albertel 7012:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7013:     } elsif ($realm eq 'resource') {
1.165     www      7014: 
1.620     albertel 7015: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7016: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7017: 	}
1.693     albertel 7018: 
                   7019: 	if ($space eq 'title') {
                   7020: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7021: 	    return &gettitle($symbparm);
                   7022: 	}
                   7023: 	
                   7024: 	if ($space eq 'map') {
                   7025: 	    my ($map) = &decode_symb($symbparm);
                   7026: 	    return &symbread($map);
                   7027: 	}
1.905     albertel 7028: 	if ($space eq 'filename') {
                   7029: 	    if ($symbparm) {
                   7030: 		return &clutter((&decode_symb($symbparm))[2]);
                   7031: 	    }
                   7032: 	    return &hreflocation('',$env{'request.filename'});
                   7033: 	}
1.693     albertel 7034: 
                   7035: 	my ($section, $group, @groups);
1.593     albertel 7036: 	my ($courselevelm,$courselevel);
1.539     albertel 7037: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7038: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7039: 
1.218     albertel 7040: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7041: 
1.60      www      7042: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7043: 	    my $symbp=$symbparm;
1.735     albertel 7044: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7045: 
                   7046: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7047: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7048: 
1.620     albertel 7049: 	    if (($env{'user.name'} eq $uname) &&
                   7050: 		($env{'user.domain'} eq $udom)) {
                   7051: 		$section=$env{'request.course.sec'};
1.733     raeburn  7052:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7053:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7054: 	    } else {
1.539     albertel 7055: 		if (! defined($usection)) {
1.551     albertel 7056: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7057: 		} else {
                   7058: 		    $section = $usection;
                   7059: 		}
1.733     raeburn  7060:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7061: 	    }
                   7062: 
                   7063: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7064: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7065: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7066: 
1.593     albertel 7067: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7068: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7069: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7070: 
1.60      www      7071: # ----------------------------------------------------------- first, check user
1.624     albertel 7072: 
                   7073: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7074: 				       ([$courselevelr,'resource'],
                   7075: 					[$courselevelm,'map'     ],
                   7076: 					[$courselevel, 'course'  ]));
1.931     albertel 7077: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7078: 
1.594     albertel 7079: # ------------------------------------------------ second, check some of course
1.684     raeburn  7080:             my $coursereply;
1.691     raeburn  7081:             if (@groups > 0) {
                   7082:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7083:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7084:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7085:             }
1.96      www      7086: 
1.684     raeburn  7087: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7088: 				  $env{'course.'.$courseid.'.domain'},
                   7089: 				  'course',
                   7090: 				  ([$seclevelr,   'resource'],
                   7091: 				   [$seclevelm,   'map'     ],
                   7092: 				   [$seclevel,    'course'  ],
                   7093: 				   [$courselevelr,'resource']));
                   7094: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7095: 
1.60      www      7096: # ------------------------------------------------------ third, check map parms
1.218     albertel 7097: 	    my %parmhash=();
                   7098: 	    my $thisparm='';
                   7099: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7100: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7101: 		    &GDBM_READER(),0640)) {
1.218     albertel 7102: 		$thisparm=$parmhash{$symbparm};
                   7103: 		untie(%parmhash);
                   7104: 	    }
1.927     albertel 7105: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7106: 	}
1.594     albertel 7107: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7108: 
1.218     albertel 7109: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7110: 	my $filename;
                   7111: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7112: 	if ($symbparm) {
1.409     www      7113: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7114: 	} else {
1.620     albertel 7115: 	    $filename=$env{'request.filename'};
1.282     albertel 7116: 	}
                   7117: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7118: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7119: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7120: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7121: 
1.927     albertel 7122: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7123: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7124: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7125: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7126: 				     $env{'course.'.$courseid.'.domain'},
                   7127: 				     'course',
1.927     albertel 7128: 				     ([$courselevelm,'map'   ],
                   7129: 				      [$courselevel, 'course']));
                   7130: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7131: 	}
1.145     www      7132: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7133: 	unless ($space eq '0') {
1.336     albertel 7134: 	    my @parts=split(/_/,$space);
                   7135: 	    my $id=pop(@parts);
                   7136: 	    my $part=join('_',@parts);
                   7137: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7138: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7139: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7140: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7141: 	}
1.395     albertel 7142: 	if ($recurse) { return undef; }
                   7143: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7144: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7145: # ---------------------------------------------------- Any other user namespace
                   7146:     } elsif ($realm eq 'environment') {
                   7147: # ----------------------------------------------------------------- environment
1.620     albertel 7148: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7149: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7150: 	} else {
1.770     albertel 7151: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7152: 		return '';
                   7153: 	    }
1.219     albertel 7154: 	    my %returnhash=&userenvironment($udom,$uname,
                   7155: 					    $spacequalifierrest);
                   7156: 	    return $returnhash{$spacequalifierrest};
                   7157: 	}
1.28      www      7158:     } elsif ($realm eq 'system') {
1.48      www      7159: # ----------------------------------------------------------------- system.time
                   7160: 	if ($space eq 'time') {
                   7161: 	    return time;
                   7162:         }
1.696     albertel 7163:     } elsif ($realm eq 'server') {
                   7164: # ----------------------------------------------------------------- system.time
                   7165: 	if ($space eq 'name') {
                   7166: 	    return $ENV{'SERVER_NAME'};
                   7167:         }
1.28      www      7168:     }
1.48      www      7169:     return '';
1.61      www      7170: }
                   7171: 
1.927     albertel 7172: sub get_reply {
                   7173:     my ($reply_value) = @_;
1.940     raeburn  7174:     if (ref($reply_value) eq 'ARRAY') {
                   7175:         if (wantarray) {
                   7176: 	    return @$reply_value;
                   7177:         }
                   7178:         return $reply_value->[0];
                   7179:     } else {
                   7180:         return $reply_value;
1.927     albertel 7181:     }
                   7182: }
                   7183: 
1.691     raeburn  7184: sub check_group_parms {
                   7185:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7186:     my @groupitems = ();
                   7187:     my $resultitem;
1.927     albertel 7188:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7189:     foreach my $group (@{$groups}) {
                   7190:         foreach my $level (@levels) {
1.927     albertel 7191:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7192:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7193:         }
                   7194:     }
                   7195:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7196:                             $env{'course.'.$courseid.'.domain'},
                   7197:                                      'course',@groupitems);
                   7198:     return $coursereply;
                   7199: }
                   7200: 
                   7201: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7202:     my ($courseid,@groups) = @_;
                   7203:     @groups = sort(@groups);
1.691     raeburn  7204:     return @groups;
                   7205: }
                   7206: 
1.395     albertel 7207: sub packages_tab_default {
                   7208:     my ($uri,$varname)=@_;
                   7209:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7210: 
                   7211:     my (@extension,@specifics,$do_default);
                   7212:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7213: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7214: 	if ($pack_type eq 'default') {
                   7215: 	    $do_default=1;
                   7216: 	} elsif ($pack_type eq 'extension') {
                   7217: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7218: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7219: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7220: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7221: 	}
                   7222:     }
                   7223:     # first look for a package that matches the requested part id
                   7224:     foreach my $package (@specifics) {
                   7225: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7226: 	next if ($pack_part ne $part);
                   7227: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7228: 	    return $packagetab{"$pack_type&$name&default"};
                   7229: 	}
                   7230:     }
                   7231:     # look for any possible matching non extension_ package
                   7232:     foreach my $package (@specifics) {
                   7233: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7234: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7235: 	    return $packagetab{"$pack_type&$name&default"};
                   7236: 	}
1.585     albertel 7237: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7238: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7239: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7240: 	}
                   7241:     }
1.738     albertel 7242:     # look for any posible extension_ match
                   7243:     foreach my $package (@extension) {
                   7244: 	my ($package,$pack_type)=@{$package};
                   7245: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7246: 	    return $packagetab{"$pack_type&$name&default"};
                   7247: 	}
                   7248: 	if (defined($packagetab{$package."&$name&default"})) {
                   7249: 	    return $packagetab{$package."&$name&default"};
                   7250: 	}
                   7251:     }
                   7252:     # look for a global default setting
                   7253:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7254: 	return $packagetab{"default&$name&default"};
                   7255:     }
1.395     albertel 7256:     return undef;
                   7257: }
                   7258: 
1.334     albertel 7259: sub add_prefix_and_part {
                   7260:     my ($prefix,$part)=@_;
                   7261:     my $keyroot;
                   7262:     if (defined($prefix) && $prefix !~ /^__/) {
                   7263: 	# prefix that has a part already
                   7264: 	$keyroot=$prefix;
                   7265:     } elsif (defined($prefix)) {
                   7266: 	# prefix that is missing a part
                   7267: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7268:     } else {
                   7269: 	# no prefix at all
                   7270: 	if (defined($part)) { $keyroot='_'.$part; }
                   7271:     }
                   7272:     return $keyroot;
                   7273: }
                   7274: 
1.71      www      7275: # ---------------------------------------------------------------- Get metadata
                   7276: 
1.599     albertel 7277: my %metaentry;
1.71      www      7278: sub metadata {
1.176     www      7279:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7280:     $uri=&declutter($uri);
1.288     albertel 7281:     # if it is a non metadata possible uri return quickly
1.529     albertel 7282:     if (($uri eq '') || 
                   7283: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7284: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7285:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7286: 	return undef;
                   7287:     }
                   7288:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7289: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7290: 	return undef;
1.288     albertel 7291:     }
1.73      www      7292:     my $filename=$uri;
                   7293:     $uri=~s/\.meta$//;
1.172     www      7294: #
                   7295: # Is the metadata already cached?
1.177     www      7296: # Look at timestamp of caching
1.172     www      7297: # Everything is cached by the main uri, libraries are never directly cached
                   7298: #
1.428     albertel 7299:     if (!defined($liburi)) {
1.599     albertel 7300: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7301: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7302:     }
                   7303:     {
1.172     www      7304: #
                   7305: # Is this a recursive call for a library?
                   7306: #
1.599     albertel 7307: #	if (! exists($metacache{$uri})) {
                   7308: #	    $metacache{$uri}={};
                   7309: #	}
1.924     albertel 7310: 	my $cachetime = 60*60;
1.171     www      7311:         if ($liburi) {
                   7312: 	    $liburi=&declutter($liburi);
                   7313:             $filename=$liburi;
1.401     bowersj2 7314:         } else {
1.599     albertel 7315: 	    &devalidate_cache_new('meta',$uri);
                   7316: 	    undef(%metaentry);
1.401     bowersj2 7317: 	}
1.140     www      7318:         my %metathesekeys=();
1.73      www      7319:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7320: 	my $metastring;
1.924     albertel 7321: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7322: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7323: 	    $metastring = 
1.929     albertel 7324: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7325: 					  ('grade_target' => 'meta'));
                   7326: 	    $cachetime = 1; # only want this cached in the child not long term
                   7327: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7328: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7329: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7330: 	    $metastring=&getfile($file);
1.489     albertel 7331: 	}
1.208     albertel 7332:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7333:         my $token;
1.140     www      7334:         undef %metathesekeys;
1.71      www      7335:         while ($token=$parser->get_token) {
1.339     albertel 7336: 	    if ($token->[0] eq 'S') {
                   7337: 		if (defined($token->[2]->{'package'})) {
1.172     www      7338: #
                   7339: # This is a package - get package info
                   7340: #
1.339     albertel 7341: 		    my $package=$token->[2]->{'package'};
                   7342: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7343: 		    if (defined($token->[2]->{'id'})) { 
                   7344: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7345: 		    }
1.599     albertel 7346: 		    if ($metaentry{':packages'}) {
                   7347: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7348: 		    } else {
1.599     albertel 7349: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7350: 		    }
1.736     albertel 7351: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7352: 			my $part=$keyroot;
                   7353: 			$part=~s/^\_//;
1.736     albertel 7354: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7355: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7356: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7357: 			    # ignore package.tab specified default values
                   7358:                             # here &package_tab_default() will fetch those
                   7359: 			    if ($subp eq 'default') { next; }
1.736     albertel 7360: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7361: 			    my $unikey;
                   7362: 			    if ($pack =~ /_0$/) {
                   7363: 				$unikey='parameter_0_'.$name;
                   7364: 				$part=0;
                   7365: 			    } else {
                   7366: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7367: 			    }
1.339     albertel 7368: 			    if ($subp eq 'display') {
                   7369: 				$value.=' [Part: '.$part.']';
                   7370: 			    }
1.599     albertel 7371: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7372: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7373: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7374: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7375: 			    }
1.599     albertel 7376: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7377: 				$metaentry{':'.$unikey}=
                   7378: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7379: 			    }
1.339     albertel 7380: 			}
                   7381: 		    }
                   7382: 		} else {
1.172     www      7383: #
                   7384: # This is not a package - some other kind of start tag
1.339     albertel 7385: #
                   7386: 		    my $entry=$token->[1];
                   7387: 		    my $unikey;
                   7388: 		    if ($entry eq 'import') {
                   7389: 			$unikey='';
                   7390: 		    } else {
                   7391: 			$unikey=$entry;
                   7392: 		    }
                   7393: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7394: 
                   7395: 		    if (defined($token->[2]->{'id'})) { 
                   7396: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7397: 		    }
1.175     www      7398: 
1.339     albertel 7399: 		    if ($entry eq 'import') {
1.175     www      7400: #
                   7401: # Importing a library here
1.339     albertel 7402: #
                   7403: 			if ($depthcount<20) {
                   7404: 			    my $location=$parser->get_text('/import');
                   7405: 			    my $dir=$filename;
                   7406: 			    $dir=~s|[^/]*$||;
                   7407: 			    $location=&filelocation($dir,$location);
1.736     albertel 7408: 			    my $metadata = 
                   7409: 				&metadata($uri,'keys', $location,$unikey,
                   7410: 					  $depthcount+1);
                   7411: 			    foreach my $meta (split(',',$metadata)) {
                   7412: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7413: 				$metathesekeys{$meta}=1;
1.339     albertel 7414: 			    }
                   7415: 			}
                   7416: 		    } else { 
                   7417: 			
                   7418: 			if (defined($token->[2]->{'name'})) { 
                   7419: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7420: 			}
                   7421: 			$metathesekeys{$unikey}=1;
1.736     albertel 7422: 			foreach my $param (@{$token->[3]}) {
                   7423: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7424: 				$token->[2]->{$param};
1.339     albertel 7425: 			}
                   7426: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7427: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7428: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7429: 		 # only ws inside the tag, and not in default, so use default
                   7430: 		 # as value
1.599     albertel 7431: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7432: 			} elsif ( $internaltext =~ /\S/ ) {
                   7433: 		  # something interesting inside the tag
                   7434: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7435: 			} else {
1.908     albertel 7436: 		  # no interesting values, don't set a default
1.339     albertel 7437: 			}
1.172     www      7438: # end of not-a-package not-a-library import
1.339     albertel 7439: 		    }
1.172     www      7440: # end of not-a-package start tag
1.339     albertel 7441: 		}
1.172     www      7442: # the next is the end of "start tag"
1.339     albertel 7443: 	    }
                   7444: 	}
1.483     albertel 7445: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7446: 	$extension = lc($extension);
                   7447: 	if ($extension eq 'htm') { $extension='html'; }
                   7448: 
1.737     albertel 7449: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7450: 	    #no specific packages #how's our extension
                   7451: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7452: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7453: 					 \%metathesekeys);
                   7454: 	}
1.883     albertel 7455: 
                   7456: 	if (!exists($metaentry{':packages'})
                   7457: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7458: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7459: 		#no specific packages well let's get default then
                   7460: 		if ($key!~/^default&/) { next; }
1.488     albertel 7461: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7462: 					     \%metathesekeys);
                   7463: 	    }
                   7464: 	}
1.338     www      7465: # are there custom rights to evaluate
1.599     albertel 7466: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7467: 
1.338     www      7468:     #
                   7469:     # Importing a rights file here
1.339     albertel 7470:     #
                   7471: 	    unless ($depthcount) {
1.599     albertel 7472: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7473: 		my $dir=$filename;
                   7474: 		$dir=~s|[^/]*$||;
                   7475: 		$location=&filelocation($dir,$location);
1.736     albertel 7476: 		my $rights_metadata =
                   7477: 		    &metadata($uri,'keys',$location,'_rights',
                   7478: 			      $depthcount+1);
                   7479: 		foreach my $rights (split(',',$rights_metadata)) {
                   7480: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7481: 		    $metathesekeys{$rights}=1;
1.339     albertel 7482: 		}
                   7483: 	    }
                   7484: 	}
1.737     albertel 7485: 	# uniqifiy package listing
                   7486: 	my %seen;
                   7487: 	my @uniq_packages =
                   7488: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7489: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7490: 
                   7491: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7492: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7493: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7494: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7495: # this is the end of "was not already recently cached
1.71      www      7496:     }
1.599     albertel 7497:     return $metaentry{':'.$what};
1.261     albertel 7498: }
                   7499: 
1.488     albertel 7500: sub metadata_create_package_def {
1.483     albertel 7501:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7502:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7503:     if ($subp eq 'default') { next; }
                   7504:     
1.599     albertel 7505:     if (defined($metaentry{':packages'})) {
                   7506: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7507:     } else {
1.599     albertel 7508: 	$metaentry{':packages'}=$package;
1.483     albertel 7509:     }
                   7510:     my $value=$packagetab{$key};
                   7511:     my $unikey;
                   7512:     $unikey='parameter_0_'.$name;
1.599     albertel 7513:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7514:     $$metathesekeys{$unikey}=1;
1.599     albertel 7515:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7516: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7517:     }
1.599     albertel 7518:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7519: 	$metaentry{':'.$unikey}=
                   7520: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7521:     }
                   7522: }
                   7523: 
1.261     albertel 7524: sub metadata_generate_part0 {
                   7525:     my ($metadata,$metacache,$uri) = @_;
                   7526:     my %allnames;
1.737     albertel 7527:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7528: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7529: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7530: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7531: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7532: 	    $allnames{$name}=$part;
                   7533: 	  }
                   7534: 	}
                   7535:     }
                   7536:     foreach my $name (keys(%allnames)) {
                   7537:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7538:       my $key=":parameter_0_$name";
1.261     albertel 7539:       $$metacache{"$key.part"}='0';
                   7540:       $$metacache{"$key.name"}=$name;
1.428     albertel 7541:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7542: 					   $allnames{$name}.'_'.$name.
                   7543: 					   '.type'};
1.428     albertel 7544:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7545: 			     '.display'};
1.644     www      7546:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7547:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7548:       $$metacache{"$key.display"}=$olddis;
                   7549:     }
1.71      www      7550: }
                   7551: 
1.764     albertel 7552: # ------------------------------------------------------ Devalidate title cache
                   7553: 
                   7554: sub devalidate_title_cache {
                   7555:     my ($url)=@_;
                   7556:     if (!$env{'request.course.id'}) { return; }
                   7557:     my $symb=&symbread($url);
                   7558:     if (!$symb) { return; }
                   7559:     my $key=$env{'request.course.id'}."\0".$symb;
                   7560:     &devalidate_cache_new('title',$key);
                   7561: }
                   7562: 
1.301     www      7563: # ------------------------------------------------- Get the title of a resource
                   7564: 
                   7565: sub gettitle {
                   7566:     my $urlsymb=shift;
                   7567:     my $symb=&symbread($urlsymb);
1.534     albertel 7568:     if ($symb) {
1.620     albertel 7569: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7570: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7571: 	if (defined($cached)) { 
                   7572: 	    return $result;
                   7573: 	}
1.534     albertel 7574: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7575: 	my $title='';
1.907     albertel 7576: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7577: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7578: 	} else {
                   7579: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7580: 		    &GDBM_READER(),0640)) {
                   7581: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7582: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7583: 		untie(%bighash);
                   7584: 	    }
1.534     albertel 7585: 	}
                   7586: 	$title=~s/\&colon\;/\:/gs;
                   7587: 	if ($title) {
1.599     albertel 7588: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7589: 	}
                   7590: 	$urlsymb=$url;
                   7591:     }
                   7592:     my $title=&metadata($urlsymb,'title');
                   7593:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7594:     return $title;
1.301     www      7595: }
1.613     albertel 7596: 
1.614     albertel 7597: sub get_slot {
                   7598:     my ($which,$cnum,$cdom)=@_;
                   7599:     if (!$cnum || !$cdom) {
1.790     albertel 7600: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7601: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7602: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7603:     }
1.703     albertel 7604:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7605:     my %slotinfo;
                   7606:     if (exists($remembered{$key})) {
                   7607: 	$slotinfo{$which} = $remembered{$key};
                   7608:     } else {
                   7609: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7610: 	&Apache::lonhomework::showhash(%slotinfo);
                   7611: 	my ($tmp)=keys(%slotinfo);
                   7612: 	if ($tmp=~/^error:/) { return (); }
                   7613: 	$remembered{$key} = $slotinfo{$which};
                   7614:     }
1.616     albertel 7615:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7616: 	return %{$slotinfo{$which}};
                   7617:     }
                   7618:     return $slotinfo{$which};
1.614     albertel 7619: }
1.31      www      7620: # ------------------------------------------------- Update symbolic store links
                   7621: 
                   7622: sub symblist {
                   7623:     my ($mapname,%newhash)=@_;
1.438     www      7624:     $mapname=&deversion(&declutter($mapname));
1.31      www      7625:     my %hash;
1.620     albertel 7626:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7627:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7628:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7629: 	    foreach my $url (keys %newhash) {
                   7630: 		next if ($url eq 'last_known'
                   7631: 			 && $env{'form.no_update_last_known'});
                   7632: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7633: 						    $newhash{$url}->[1],
                   7634: 						    $newhash{$url}->[0]);
1.191     harris41 7635:             }
1.31      www      7636:             if (untie(%hash)) {
                   7637: 		return 'ok';
                   7638:             }
                   7639:         }
                   7640:     }
                   7641:     return 'error';
1.212     www      7642: }
                   7643: 
                   7644: # --------------------------------------------------------------- Verify a symb
                   7645: 
                   7646: sub symbverify {
1.510     www      7647:     my ($symb,$thisurl)=@_;
                   7648:     my $thisfn=$thisurl;
1.439     www      7649:     $thisfn=&declutter($thisfn);
1.215     www      7650: # direct jump to resource in page or to a sequence - will construct own symbs
                   7651:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7652: # check URL part
1.409     www      7653:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7654: 
1.431     www      7655:     unless ($url eq $thisfn) { return 0; }
1.213     www      7656: 
1.216     www      7657:     $symb=&symbclean($symb);
1.510     www      7658:     $thisurl=&deversion($thisurl);
1.439     www      7659:     $thisfn=&deversion($thisfn);
1.213     www      7660: 
                   7661:     my %bighash;
                   7662:     my $okay=0;
1.431     www      7663: 
1.620     albertel 7664:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7665:                             &GDBM_READER(),0640)) {
1.510     www      7666:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7667:         unless ($ids) { 
1.510     www      7668:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7669:         }
                   7670:         if ($ids) {
                   7671: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7672: 	    foreach my $id (split(/\,/,$ids)) {
                   7673: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7674:                if (
                   7675:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7676:    eq $symb) { 
1.620     albertel 7677: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7678: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7679: 		       $okay=1; 
                   7680: 		   }
                   7681: 	       }
1.216     www      7682: 	   }
                   7683:         }
1.213     www      7684: 	untie(%bighash);
                   7685:     }
                   7686:     return $okay;
1.31      www      7687: }
                   7688: 
1.210     www      7689: # --------------------------------------------------------------- Clean-up symb
                   7690: 
                   7691: sub symbclean {
                   7692:     my $symb=shift;
1.568     albertel 7693:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7694: # remove version from map
                   7695:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7696: 
1.210     www      7697: # remove version from URL
                   7698:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7699: 
1.507     www      7700: # remove wrapper
                   7701: 
1.510     www      7702:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7703:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7704:     return $symb;
1.409     www      7705: }
                   7706: 
                   7707: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7708: 
                   7709: sub encode_symb {
                   7710:     my ($map,$resid,$url)=@_;
                   7711:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7712: }
1.409     www      7713: 
                   7714: sub decode_symb {
1.568     albertel 7715:     my $symb=shift;
                   7716:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7717:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7718:     return (&fixversion($map),$resid,&fixversion($url));
                   7719: }
                   7720: 
                   7721: sub fixversion {
                   7722:     my $fn=shift;
1.609     banghart 7723:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7724:     my %bighash;
                   7725:     my $uri=&clutter($fn);
1.620     albertel 7726:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7727: # is this cached?
1.599     albertel 7728:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7729:     if (defined($cached)) { return $result; }
                   7730: # unfortunately not cached, or expired
1.620     albertel 7731:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7732: 	    &GDBM_READER(),0640)) {
                   7733:  	if ($bighash{'version_'.$uri}) {
                   7734:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7735:  	    unless (($version eq 'mostrecent') || 
                   7736: 		    ($version==&getversion($uri))) {
1.440     www      7737:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7738:  	    }
                   7739:  	}
                   7740:  	untie %bighash;
1.413     www      7741:     }
1.599     albertel 7742:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7743: }
                   7744: 
                   7745: sub deversion {
                   7746:     my $url=shift;
                   7747:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7748:     return $url;
1.210     www      7749: }
                   7750: 
1.31      www      7751: # ------------------------------------------------------ Return symb list entry
                   7752: 
                   7753: sub symbread {
1.249     www      7754:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7755:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7756:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7757: # no filename provided? try from environment
1.44      www      7758:     unless ($thisfn) {
1.620     albertel 7759:         if ($env{'request.symb'}) {
                   7760: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7761: 	}
1.620     albertel 7762: 	$thisfn=$env{'request.filename'};
1.44      www      7763:     }
1.569     albertel 7764:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7765: # is that filename actually a symb? Verify, clean, and return
                   7766:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7767: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7768: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7769: 	}
1.242     www      7770:     }
1.44      www      7771:     $thisfn=declutter($thisfn);
1.31      www      7772:     my %hash;
1.37      www      7773:     my %bighash;
                   7774:     my $syval='';
1.620     albertel 7775:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7776:         my $targetfn = $thisfn;
1.609     banghart 7777:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7778:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7779:         }
1.687     albertel 7780: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7781: 	    $targetfn=$1;
                   7782: 	}
1.620     albertel 7783:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7784:                       &GDBM_READER(),0640)) {
1.481     raeburn  7785: 	    $syval=$hash{$targetfn};
1.37      www      7786:             untie(%hash);
                   7787:         }
                   7788: # ---------------------------------------------------------- There was an entry
                   7789:         if ($syval) {
1.601     albertel 7790: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7791: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7792: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7793: 		    #return $env{$cache_str}='';
1.601     albertel 7794: 		#}    
                   7795: 		#$syval.=$1;
                   7796: 	    #}
1.37      www      7797:         } else {
                   7798: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7799:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7800:                             &GDBM_READER(),0640)) {
1.37      www      7801: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7802:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7803:               unless ($ids) { 
                   7804:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7805:               }
                   7806:               unless ($ids) {
                   7807: # alias?
                   7808: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7809:               }
1.37      www      7810:               if ($ids) {
                   7811: # ------------------------------------------------------------------- Has ID(s)
                   7812:                  my @possibilities=split(/\,/,$ids);
1.39      www      7813:                  if ($#possibilities==0) {
                   7814: # ----------------------------------------------- There is only one possibility
1.37      www      7815: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7816: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7817: 						    $resid,$thisfn);
1.249     www      7818:                  } elsif (!$donotrecurse) {
1.39      www      7819: # ------------------------------------------ There is more than one possibility
                   7820:                      my $realpossible=0;
1.800     albertel 7821:                      foreach my $id (@possibilities) {
                   7822: 			 my $file=$bighash{'src_'.$id};
1.39      www      7823:                          if (&allowed('bre',$file)) {
1.800     albertel 7824:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7825:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7826: 				$realpossible++;
1.626     albertel 7827:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7828: 						    $resid,$thisfn);
1.39      www      7829:                             }
                   7830: 			 }
1.191     harris41 7831:                      }
1.39      www      7832: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7833:                  } else {
                   7834:                      $syval='';
1.37      www      7835:                  }
                   7836: 	      }
                   7837:               untie(%bighash)
1.481     raeburn  7838:            }
1.31      www      7839:         }
1.62      www      7840:         if ($syval) {
1.620     albertel 7841: 	    return $env{$cache_str}=$syval;
1.62      www      7842:         }
1.31      www      7843:     }
1.949     raeburn  7844:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7845:     return $env{$cache_str}='';
1.31      www      7846: }
                   7847: 
                   7848: # ---------------------------------------------------------- Return random seed
                   7849: 
1.32      www      7850: sub numval {
                   7851:     my $txt=shift;
                   7852:     $txt=~tr/A-J/0-9/;
                   7853:     $txt=~tr/a-j/0-9/;
                   7854:     $txt=~tr/K-T/0-9/;
                   7855:     $txt=~tr/k-t/0-9/;
                   7856:     $txt=~tr/U-Z/0-5/;
                   7857:     $txt=~tr/u-z/0-5/;
                   7858:     $txt=~s/\D//g;
1.564     albertel 7859:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7860:     return int($txt);
1.368     albertel 7861: }
                   7862: 
1.484     albertel 7863: sub numval2 {
                   7864:     my $txt=shift;
                   7865:     $txt=~tr/A-J/0-9/;
                   7866:     $txt=~tr/a-j/0-9/;
                   7867:     $txt=~tr/K-T/0-9/;
                   7868:     $txt=~tr/k-t/0-9/;
                   7869:     $txt=~tr/U-Z/0-5/;
                   7870:     $txt=~tr/u-z/0-5/;
                   7871:     $txt=~s/\D//g;
                   7872:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7873:     my $total;
                   7874:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7875:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7876:     return int($total);
                   7877: }
                   7878: 
1.575     albertel 7879: sub numval3 {
                   7880:     use integer;
                   7881:     my $txt=shift;
                   7882:     $txt=~tr/A-J/0-9/;
                   7883:     $txt=~tr/a-j/0-9/;
                   7884:     $txt=~tr/K-T/0-9/;
                   7885:     $txt=~tr/k-t/0-9/;
                   7886:     $txt=~tr/U-Z/0-5/;
                   7887:     $txt=~tr/u-z/0-5/;
                   7888:     $txt=~s/\D//g;
                   7889:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7890:     my $total;
                   7891:     foreach my $val (@txts) { $total+=$val; }
                   7892:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7893:     return $total;
                   7894: }
                   7895: 
1.675     albertel 7896: sub digest {
                   7897:     my ($data)=@_;
                   7898:     my $digest=&Digest::MD5::md5($data);
                   7899:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7900:     my ($e,$f);
                   7901:     {
                   7902:         use integer;
                   7903:         $e=($a+$b);
                   7904:         $f=($c+$d);
                   7905:         if ($_64bit) {
                   7906:             $e=(($e<<32)>>32);
                   7907:             $f=(($f<<32)>>32);
                   7908:         }
                   7909:     }
                   7910:     if (wantarray) {
                   7911: 	return ($e,$f);
                   7912:     } else {
                   7913: 	my $g;
                   7914: 	{
                   7915: 	    use integer;
                   7916: 	    $g=($e+$f);
                   7917: 	    if ($_64bit) {
                   7918: 		$g=(($g<<32)>>32);
                   7919: 	    }
                   7920: 	}
                   7921: 	return $g;
                   7922:     }
                   7923: }
                   7924: 
1.368     albertel 7925: sub latest_rnd_algorithm_id {
1.675     albertel 7926:     return '64bit5';
1.366     albertel 7927: }
1.32      www      7928: 
1.503     albertel 7929: sub get_rand_alg {
                   7930:     my ($courseid)=@_;
1.790     albertel 7931:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7932:     if ($courseid) {
1.620     albertel 7933: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7934:     }
                   7935:     return &latest_rnd_algorithm_id();
                   7936: }
                   7937: 
1.562     albertel 7938: sub validCODE {
                   7939:     my ($CODE)=@_;
                   7940:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7941:     return 0;
                   7942: }
                   7943: 
1.491     albertel 7944: sub getCODE {
1.620     albertel 7945:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7946:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7947: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7948: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7949: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7950:     }
                   7951:     return undef;
                   7952: }
                   7953: 
1.31      www      7954: sub rndseed {
1.155     albertel 7955:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7956:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7957:     if (!defined($symb)) {
1.366     albertel 7958: 	unless ($symb=$wsymb) { return time; }
                   7959:     }
                   7960:     if (!$courseid) { $courseid=$wcourseid; }
                   7961:     if (!$domain) { $domain=$wdomain; }
                   7962:     if (!$username) { $username=$wusername }
1.503     albertel 7963:     my $which=&get_rand_alg();
1.803     albertel 7964: 
1.491     albertel 7965:     if (defined(&getCODE())) {
1.675     albertel 7966: 	if ($which eq '64bit5') {
                   7967: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7968: 	} elsif ($which eq '64bit4') {
1.575     albertel 7969: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7970: 	} else {
                   7971: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7972: 	}
1.675     albertel 7973:     } elsif ($which eq '64bit5') {
                   7974: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7975:     } elsif ($which eq '64bit4') {
                   7976: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7977:     } elsif ($which eq '64bit3') {
                   7978: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7979:     } elsif ($which eq '64bit2') {
                   7980: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7981:     } elsif ($which eq '64bit') {
                   7982: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7983:     }
                   7984:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7985: }
                   7986: 
                   7987: sub rndseed_32bit {
                   7988:     my ($symb,$courseid,$domain,$username)=@_;
                   7989:     {
                   7990: 	use integer;
                   7991: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7992: 	my $symbseed=numval($symb) << 22;
                   7993: 	my $namechck=unpack("%32C*",$username) << 17;
                   7994: 	my $nameseed=numval($username) << 12;
                   7995: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7996: 	my $courseseed=unpack("%32C*",$courseid);
                   7997: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7998: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7999: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8000: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8001: 	return $num;
                   8002:     }
                   8003: }
                   8004: 
                   8005: sub rndseed_64bit {
                   8006:     my ($symb,$courseid,$domain,$username)=@_;
                   8007:     {
                   8008: 	use integer;
                   8009: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8010: 	my $symbseed=numval($symb) << 10;
                   8011: 	my $namechck=unpack("%32S*",$username);
                   8012: 	
                   8013: 	my $nameseed=numval($username) << 21;
                   8014: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8015: 	my $courseseed=unpack("%32S*",$courseid);
                   8016: 	
                   8017: 	my $num1=$symbchck+$symbseed+$namechck;
                   8018: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8019: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8020: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8021: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8022: 	return "$num1,$num2";
1.155     albertel 8023:     }
1.366     albertel 8024: }
                   8025: 
1.443     albertel 8026: sub rndseed_64bit2 {
                   8027:     my ($symb,$courseid,$domain,$username)=@_;
                   8028:     {
                   8029: 	use integer;
                   8030: 	# strings need to be an even # of cahracters long, it it is odd the
                   8031:         # last characters gets thrown away
                   8032: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8033: 	my $symbseed=numval($symb) << 10;
                   8034: 	my $namechck=unpack("%32S*",$username.' ');
                   8035: 	
                   8036: 	my $nameseed=numval($username) << 21;
1.501     albertel 8037: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8038: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8039: 	
                   8040: 	my $num1=$symbchck+$symbseed+$namechck;
                   8041: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8042: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8043: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8044: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8045: 	return "$num1,$num2";
                   8046:     }
                   8047: }
                   8048: 
                   8049: sub rndseed_64bit3 {
                   8050:     my ($symb,$courseid,$domain,$username)=@_;
                   8051:     {
                   8052: 	use integer;
                   8053: 	# strings need to be an even # of cahracters long, it it is odd the
                   8054:         # last characters gets thrown away
                   8055: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8056: 	my $symbseed=numval2($symb) << 10;
                   8057: 	my $namechck=unpack("%32S*",$username.' ');
                   8058: 	
                   8059: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8060: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8061: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8062: 	
                   8063: 	my $num1=$symbchck+$symbseed+$namechck;
                   8064: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8065: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8066: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8067: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8068: 	
1.503     albertel 8069: 	return "$num1:$num2";
1.443     albertel 8070:     }
                   8071: }
                   8072: 
1.575     albertel 8073: sub rndseed_64bit4 {
                   8074:     my ($symb,$courseid,$domain,$username)=@_;
                   8075:     {
                   8076: 	use integer;
                   8077: 	# strings need to be an even # of cahracters long, it it is odd the
                   8078:         # last characters gets thrown away
                   8079: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8080: 	my $symbseed=numval3($symb) << 10;
                   8081: 	my $namechck=unpack("%32S*",$username.' ');
                   8082: 	
                   8083: 	my $nameseed=numval3($username) << 21;
                   8084: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8085: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8086: 	
                   8087: 	my $num1=$symbchck+$symbseed+$namechck;
                   8088: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8089: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8090: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8091: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8092: 	
                   8093: 	return "$num1:$num2";
                   8094:     }
                   8095: }
                   8096: 
1.675     albertel 8097: sub rndseed_64bit5 {
                   8098:     my ($symb,$courseid,$domain,$username)=@_;
                   8099:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8100:     return "$num1:$num2";
                   8101: }
                   8102: 
1.366     albertel 8103: sub rndseed_CODE_64bit {
                   8104:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8105:     {
1.366     albertel 8106: 	use integer;
1.443     albertel 8107: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8108: 	my $symbseed=numval2($symb);
1.491     albertel 8109: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8110: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8111: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8112: 	my $num1=$symbseed+$CODEchck;
                   8113: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8114: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8115: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8116: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8117: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8118: 	return "$num1:$num2";
1.366     albertel 8119:     }
                   8120: }
                   8121: 
1.575     albertel 8122: sub rndseed_CODE_64bit4 {
                   8123:     my ($symb,$courseid,$domain,$username)=@_;
                   8124:     {
                   8125: 	use integer;
                   8126: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8127: 	my $symbseed=numval3($symb);
                   8128: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8129: 	my $CODEseed=numval3(&getCODE());
                   8130: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8131: 	my $num1=$symbseed+$CODEchck;
                   8132: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8133: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8134: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8135: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8136: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8137: 	return "$num1:$num2";
                   8138:     }
                   8139: }
                   8140: 
1.675     albertel 8141: sub rndseed_CODE_64bit5 {
                   8142:     my ($symb,$courseid,$domain,$username)=@_;
                   8143:     my $code = &getCODE();
                   8144:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8145:     return "$num1:$num2";
                   8146: }
                   8147: 
1.366     albertel 8148: sub setup_random_from_rndseed {
                   8149:     my ($rndseed)=@_;
1.503     albertel 8150:     if ($rndseed =~/([,:])/) {
                   8151: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8152: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8153:     } else {
                   8154: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8155:     }
1.36      albertel 8156: }
                   8157: 
1.474     albertel 8158: sub latest_receipt_algorithm_id {
1.835     albertel 8159:     return 'receipt3';
1.474     albertel 8160: }
                   8161: 
1.480     www      8162: sub recunique {
                   8163:     my $fucourseid=shift;
                   8164:     my $unique;
1.835     albertel 8165:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8166: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8167: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8168:     } else {
                   8169: 	$unique=$perlvar{'lonReceipt'};
                   8170:     }
                   8171:     return unpack("%32C*",$unique);
                   8172: }
                   8173: 
                   8174: sub recprefix {
                   8175:     my $fucourseid=shift;
                   8176:     my $prefix;
1.835     albertel 8177:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8178: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8179: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8180:     } else {
                   8181: 	$prefix=$perlvar{'lonHostID'};
                   8182:     }
                   8183:     return unpack("%32C*",$prefix);
                   8184: }
                   8185: 
1.76      www      8186: sub ireceipt {
1.474     albertel 8187:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8188: 
                   8189:     my $return =&recprefix($fucourseid).'-';
                   8190: 
                   8191:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8192: 	$env{'request.state'} eq 'construct') {
                   8193: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8194: 	return $return;
                   8195:     }
                   8196: 
1.76      www      8197:     my $cuname=unpack("%32C*",$funame);
                   8198:     my $cudom=unpack("%32C*",$fudom);
                   8199:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8200:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8201:     my $cunique=&recunique($fucourseid);
1.474     albertel 8202:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8203:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8204: 
1.790     albertel 8205: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8206: 			       
                   8207: 	$return.= ($cunique%$cuname+
                   8208: 		   $cunique%$cudom+
                   8209: 		   $cusymb%$cuname+
                   8210: 		   $cusymb%$cudom+
                   8211: 		   $cucourseid%$cuname+
                   8212: 		   $cucourseid%$cudom+
                   8213: 		   $cpart%$cuname+
                   8214: 		   $cpart%$cudom);
                   8215:     } else {
                   8216: 	$return.= ($cunique%$cuname+
                   8217: 		   $cunique%$cudom+
                   8218: 		   $cusymb%$cuname+
                   8219: 		   $cusymb%$cudom+
                   8220: 		   $cucourseid%$cuname+
                   8221: 		   $cucourseid%$cudom);
                   8222:     }
                   8223:     return $return;
1.76      www      8224: }
                   8225: 
                   8226: sub receipt {
1.474     albertel 8227:     my ($part)=@_;
1.790     albertel 8228:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8229:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8230: }
1.260     ng       8231: 
1.790     albertel 8232: sub whichuser {
                   8233:     my ($passedsymb)=@_;
                   8234:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8235:     if (defined($env{'form.grade_symb'})) {
                   8236: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8237: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8238: 	if (!$allowed &&
                   8239: 	    exists($env{'request.course.sec'}) &&
                   8240: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8241: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8242: 			      '/'.$env{'request.course.sec'});
                   8243: 	}
                   8244: 	if ($allowed) {
                   8245: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8246: 	    $courseid=$tmp_courseid;
                   8247: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8248: 	    ($name)=&get_env_multiple('form.grade_username');
                   8249: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8250: 	}
                   8251:     }
                   8252:     if (!$passedsymb) {
                   8253: 	$symb=&symbread();
                   8254:     } else {
                   8255: 	$symb=$passedsymb;
                   8256:     }
                   8257:     $courseid=$env{'request.course.id'};
                   8258:     $domain=$env{'user.domain'};
                   8259:     $name=$env{'user.name'};
                   8260:     if ($name eq 'public' && $domain eq 'public') {
                   8261: 	if (!defined($env{'form.username'})) {
                   8262: 	    $env{'form.username'}.=time.rand(10000000);
                   8263: 	}
                   8264: 	$name.=$env{'form.username'};
                   8265:     }
                   8266:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8267: 
                   8268: }
                   8269: 
1.36      albertel 8270: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8271: # returns either the contents of the file or 
                   8272: # -1 if the file doesn't exist
1.481     raeburn  8273: #
                   8274: # if the target is a file that was uploaded via DOCS, 
                   8275: # a check will be made to see if a current copy exists on the local server,
                   8276: # if it does this will be served, otherwise a copy will be retrieved from
                   8277: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8278: # the local server.   
1.472     albertel 8279: 
1.36      albertel 8280: sub getfile {
1.538     albertel 8281:     my ($file) = @_;
1.609     banghart 8282:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8283:     &repcopy($file);
                   8284:     return &readfile($file);
                   8285: }
                   8286: 
                   8287: sub repcopy_userfile {
                   8288:     my ($file)=@_;
1.609     banghart 8289:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8290:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8291:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8292: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8293:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8294:     if (-e "$file") {
1.828     www      8295: # we already have a local copy, check it out
1.538     albertel 8296: 	my @fileinfo = stat($file);
1.828     www      8297: 	my $rtncode;
                   8298: 	my $info;
1.538     albertel 8299: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8300: 	if ($lwpresp ne 'ok') {
1.828     www      8301: # there is no such file anymore, even though we had a local copy
1.482     albertel 8302: 	    if ($rtncode eq '404') {
1.538     albertel 8303: 		unlink($file);
1.482     albertel 8304: 	    }
                   8305: 	    return -1;
                   8306: 	}
                   8307: 	if ($info < $fileinfo[9]) {
1.828     www      8308: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8309: 	    return 'ok';
1.828     www      8310: 	} else {
                   8311: # the file is outdated, get rid of it
                   8312: 	    unlink($file);
1.482     albertel 8313: 	}
1.828     www      8314:     }
                   8315: # one way or the other, at this point, we don't have the file
                   8316: # construct the correct path for the file
                   8317:     my @parts = ($cdom,$cnum); 
                   8318:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8319: 	push @parts, split(/\//,$1);
                   8320:     }
                   8321:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8322:     foreach my $part (@parts) {
                   8323: 	$path .= '/'.$part;
                   8324: 	if (!-e $path) {
                   8325: 	    mkdir($path,0770);
1.482     albertel 8326: 	}
                   8327:     }
1.828     www      8328: # now the path exists for sure
                   8329: # get a user agent
                   8330:     my $ua=new LWP::UserAgent;
                   8331:     my $transferfile=$file.'.in.transfer';
                   8332: # FIXME: this should flock
                   8333:     if (-e $transferfile) { return 'ok'; }
                   8334:     my $request;
                   8335:     $uri=~s/^\///;
1.980     raeburn  8336:     my $homeserver = &homeserver($cnum,$cdom);
                   8337:     my $protocol = $protocol{$homeserver};
                   8338:     $protocol = 'http' if ($protocol ne 'https');
                   8339:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8340:     my $response=$ua->request($request,$transferfile);
                   8341: # did it work?
                   8342:     if ($response->is_error()) {
                   8343: 	unlink($transferfile);
                   8344: 	&logthis("Userfile repcopy failed for $uri");
                   8345: 	return -1;
                   8346:     }
                   8347: # worked, rename the transfer file
                   8348:     rename($transferfile,$file);
1.607     raeburn  8349:     return 'ok';
1.481     raeburn  8350: }
                   8351: 
1.517     albertel 8352: sub tokenwrapper {
                   8353:     my $uri=shift;
1.980     raeburn  8354:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8355:     $uri=~s|^/||;
1.620     albertel 8356:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8357:     my $token=$1;
1.552     albertel 8358:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8359:     if ($udom && $uname && $file) {
                   8360: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8361:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8362:         my $homeserver = &homeserver($uname,$udom);
                   8363:         my $protocol = $protocol{$homeserver};
                   8364:         $protocol = 'http' if ($protocol ne 'https');
                   8365:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8366:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8367:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8368:     } else {
                   8369:         return '/adm/notfound.html';
                   8370:     }
                   8371: }
                   8372: 
1.828     www      8373: # call with reqtype HEAD: get last modification time
                   8374: # call with reqtype GET: get the file contents
                   8375: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8376: #
1.481     raeburn  8377: sub getuploaded {
                   8378:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8379:     $uri=~s/^\///;
1.980     raeburn  8380:     my $homeserver = &homeserver($cnum,$cdom);
                   8381:     my $protocol = $protocol{$homeserver};
                   8382:     $protocol = 'http' if ($protocol ne 'https');
                   8383:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8384:     my $ua=new LWP::UserAgent;
                   8385:     my $request=new HTTP::Request($reqtype,$uri);
                   8386:     my $response=$ua->request($request);
                   8387:     $$rtncode = $response->code;
1.482     albertel 8388:     if (! $response->is_success()) {
                   8389: 	return 'failed';
                   8390:     }      
                   8391:     if ($reqtype eq 'HEAD') {
1.486     www      8392: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8393:     } elsif ($reqtype eq 'GET') {
                   8394: 	$$info = $response->content;
1.472     albertel 8395:     }
1.482     albertel 8396:     return 'ok';
1.36      albertel 8397: }
                   8398: 
1.481     raeburn  8399: sub readfile {
                   8400:     my $file = shift;
                   8401:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8402:     my $fh;
                   8403:     open($fh,"<$file");
                   8404:     my $a='';
1.800     albertel 8405:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8406:     return $a;
                   8407: }
                   8408: 
1.36      albertel 8409: sub filelocation {
1.590     banghart 8410:     my ($dir,$file) = @_;
                   8411:     my $location;
                   8412:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8413: 
                   8414:     if ($file =~ m-^/adm/-) {
                   8415: 	$file=~s-^/adm/wrapper/-/-;
                   8416: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8417:     }
1.882     albertel 8418: 
1.590     banghart 8419:     if ($file=~m:^/~:) { # is a contruction space reference
                   8420:         $location = $file;
                   8421:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8422:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8423: 	# is a correct contruction space reference
                   8424:         $location = $file;
1.956     raeburn  8425:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8426:         $location = $file;
1.609     banghart 8427:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8428:         my ($udom,$uname,$filename)=
1.811     albertel 8429:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8430:         my $home=&homeserver($uname,$udom);
                   8431:         my $is_me=0;
                   8432:         my @ids=&current_machine_ids();
                   8433:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8434:         if ($is_me) {
1.955     raeburn  8435:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8436:         } else {
                   8437:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8438:   	      $udom.'/'.$uname.'/'.$filename;
                   8439:         }
1.882     albertel 8440:     } elsif ($file =~ m-^/adm/-) {
                   8441: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8442:     } else {
                   8443:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8444:         $file=~s:^/res/:/:;
                   8445:         if ( !( $file =~ m:^/:) ) {
                   8446:             $location = $dir. '/'.$file;
                   8447:         } else {
                   8448:             $location = '/home/httpd/html/res'.$file;
                   8449:         }
1.59      albertel 8450:     }
1.590     banghart 8451:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8452:     while ($location=~m{/\.\./}) {
                   8453: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8454: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8455: 	} else {
                   8456: 	    $location=~ s{/\.\./}{/}g;
                   8457: 	}
                   8458:     } #remove dir/..
1.590     banghart 8459:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8460:     return $location;
1.46      www      8461: }
1.36      albertel 8462: 
1.46      www      8463: sub hreflocation {
                   8464:     my ($dir,$file)=@_;
1.980     raeburn  8465:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8466: 	$file=filelocation($dir,$file);
1.700     albertel 8467:     } elsif ($file=~m-^/adm/-) {
                   8468: 	$file=~s-^/adm/wrapper/-/-;
                   8469: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8470:     }
                   8471:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8472: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8473:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8474: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8475:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8476: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8477: 	    -/uploaded/$1/$2/-x;
1.46      www      8478:     }
1.913     albertel 8479:     if ($file=~ m{^/userfiles/}) {
                   8480: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8481:     }
1.462     albertel 8482:     return $file;
1.465     albertel 8483: }
                   8484: 
                   8485: sub current_machine_domains {
1.853     albertel 8486:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8487: }
                   8488: 
                   8489: sub machine_domains {
                   8490:     my ($hostname) = @_;
1.465     albertel 8491:     my @domains;
1.838     albertel 8492:     my %hostname = &all_hostnames();
1.465     albertel 8493:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8494: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8495: 	if ($hostname eq $name) {
1.844     albertel 8496: 	    push(@domains,&host_domain($id));
1.465     albertel 8497: 	}
                   8498:     }
                   8499:     return @domains;
                   8500: }
                   8501: 
                   8502: sub current_machine_ids {
1.853     albertel 8503:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8504: }
                   8505: 
                   8506: sub machine_ids {
                   8507:     my ($hostname) = @_;
                   8508:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8509:     my @ids;
1.888     albertel 8510:     my %name_to_host = &all_names();
1.889     albertel 8511:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8512: 	return @{ $name_to_host{$hostname} };
                   8513:     }
                   8514:     return;
1.31      www      8515: }
                   8516: 
1.824     raeburn  8517: sub additional_machine_domains {
                   8518:     my @domains;
                   8519:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8520:     while( my $line = <$fh>) {
                   8521:         $line =~ s/\s//g;
                   8522:         push(@domains,$line);
                   8523:     }
                   8524:     return @domains;
                   8525: }
                   8526: 
                   8527: sub default_login_domain {
                   8528:     my $domain = $perlvar{'lonDefDomain'};
                   8529:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8530:     foreach my $posdom (&current_machine_domains(),
                   8531:                         &additional_machine_domains()) {
                   8532:         if (lc($posdom) eq lc($testdomain)) {
                   8533:             $domain=$posdom;
                   8534:             last;
                   8535:         }
                   8536:     }
                   8537:     return $domain;
                   8538: }
                   8539: 
1.31      www      8540: # ------------------------------------------------------------- Declutters URLs
                   8541: 
                   8542: sub declutter {
                   8543:     my $thisfn=shift;
1.569     albertel 8544:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8545:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8546:     $thisfn=~s/^\///;
1.697     albertel 8547:     $thisfn=~s|^adm/wrapper/||;
                   8548:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8549:     $thisfn=~s/^res\///;
1.235     www      8550:     $thisfn=~s/\?.+$//;
1.268     www      8551:     return $thisfn;
                   8552: }
                   8553: 
                   8554: # ------------------------------------------------------------- Clutter up URLs
                   8555: 
                   8556: sub clutter {
                   8557:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8558:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8559: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8560:        $thisfn='/res'.$thisfn; 
                   8561:     }
1.694     albertel 8562:     if ($thisfn !~m|/adm|) {
1.695     albertel 8563: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8564: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8565: 	} else {
                   8566: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8567: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8568: 	    if ($embstyle eq 'ssi'
                   8569: 		|| ($embstyle eq 'hdn')
                   8570: 		|| ($embstyle eq 'rat')
                   8571: 		|| ($embstyle eq 'prv')
                   8572: 		|| ($embstyle eq 'ign')) {
                   8573: 		#do nothing with these
                   8574: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8575: 		|| ($embstyle eq 'emb')
                   8576: 		|| ($embstyle eq 'wrp')) {
                   8577: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8578: 	    } elsif ($embstyle eq 'unk'
                   8579: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8580: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8581: 	    } else {
1.718     www      8582: #		&logthis("Got a blank emb style");
1.695     albertel 8583: 	    }
1.694     albertel 8584: 	}
                   8585:     }
1.31      www      8586:     return $thisfn;
1.12      www      8587: }
                   8588: 
1.787     albertel 8589: sub clutter_with_no_wrapper {
                   8590:     my $uri = &clutter(shift);
                   8591:     if ($uri =~ m-^/adm/-) {
                   8592: 	$uri =~ s-^/adm/wrapper/-/-;
                   8593: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8594:     }
                   8595:     return $uri;
                   8596: }
                   8597: 
1.557     albertel 8598: sub freeze_escape {
                   8599:     my ($value)=@_;
                   8600:     if (ref($value)) {
                   8601: 	$value=&nfreeze($value);
                   8602: 	return '__FROZEN__'.&escape($value);
                   8603:     }
                   8604:     return &escape($value);
                   8605: }
                   8606: 
1.11      www      8607: 
1.557     albertel 8608: sub thaw_unescape {
                   8609:     my ($value)=@_;
                   8610:     if ($value =~ /^__FROZEN__/) {
                   8611: 	substr($value,0,10,undef);
                   8612: 	$value=&unescape($value);
                   8613: 	return &thaw($value);
                   8614:     }
                   8615:     return &unescape($value);
                   8616: }
                   8617: 
1.436     albertel 8618: sub correct_line_ends {
                   8619:     my ($result)=@_;
                   8620:     $$result =~s/\r\n/\n/mg;
                   8621:     $$result =~s/\r/\n/mg;
1.415     albertel 8622: }
1.1       albertel 8623: # ================================================================ Main Program
                   8624: 
1.184     www      8625: sub goodbye {
1.204     albertel 8626:    &logthis("Starting Shut down");
1.443     albertel 8627: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8628:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8629: #converted
1.599     albertel 8630: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8631:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8632: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8633: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8634: #1.1 only
1.870     albertel 8635: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8636: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8637: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8638: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8639:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8640:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8641:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8642:    &flushcourselogs();
                   8643:    &logthis("Shutting down");
                   8644: }
                   8645: 
1.852     albertel 8646: sub get_dns {
1.869     albertel 8647:     my ($url,$func,$ignore_cache) = @_;
                   8648:     if (!$ignore_cache) {
                   8649: 	my ($content,$cached)=
                   8650: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8651: 	if ($cached) {
                   8652: 	    &$func($content);
                   8653: 	    return;
                   8654: 	}
                   8655:     }
                   8656: 
                   8657:     my %alldns;
1.852     albertel 8658:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8659:     foreach my $dns (<$config>) {
                   8660: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8661:         my $line = $1;
                   8662:         my ($host,$protocol) = split(/:/,$line);
                   8663:         if ($protocol ne 'https') {
                   8664:             $protocol = 'http';
                   8665:         }
                   8666: 	$alldns{$host} = $protocol;
1.869     albertel 8667:     }
                   8668:     while (%alldns) {
                   8669: 	my ($dns) = keys(%alldns);
1.852     albertel 8670: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8671: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8672: 	my $response=$ua->request($request);
1.979     raeburn  8673:         delete($alldns{$dns});
1.852     albertel 8674: 	next if ($response->is_error());
                   8675: 	my @content = split("\n",$response->content);
1.869     albertel 8676: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8677: 	&$func(\@content);
1.869     albertel 8678: 	return;
1.852     albertel 8679:     }
                   8680:     close($config);
1.871     albertel 8681:     my $which = (split('/',$url))[3];
                   8682:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8683:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8684:     my @content = <$config>;
                   8685:     &$func(\@content);
                   8686:     return;
1.852     albertel 8687: }
1.327     albertel 8688: # ------------------------------------------------------------ Read domain file
                   8689: {
1.852     albertel 8690:     my $loaded;
1.846     albertel 8691:     my %domain;
                   8692: 
1.852     albertel 8693:     sub parse_domain_tab {
                   8694: 	my ($lines) = @_;
                   8695: 	foreach my $line (@$lines) {
                   8696: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8697: 
1.846     albertel 8698: 	    chomp($line);
1.852     albertel 8699: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8700: 	    my %this_domain;
                   8701: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8702: 			       'lang_def', 'city', 'longi', 'lati',
                   8703: 			       'primary') {
                   8704: 		$this_domain{$field} = shift(@elements);
                   8705: 	    }
                   8706: 	    $domain{$name} = \%this_domain;
1.852     albertel 8707: 	}
                   8708:     }
1.864     albertel 8709: 
                   8710:     sub reset_domain_info {
                   8711: 	undef($loaded);
                   8712: 	undef(%domain);
                   8713:     }
                   8714: 
1.852     albertel 8715:     sub load_domain_tab {
1.869     albertel 8716: 	my ($ignore_cache) = @_;
                   8717: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8718: 	my $fh;
                   8719: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8720: 	    my @lines = <$fh>;
                   8721: 	    &parse_domain_tab(\@lines);
1.448     albertel 8722: 	}
1.852     albertel 8723: 	close($fh);
                   8724: 	$loaded = 1;
1.327     albertel 8725:     }
1.846     albertel 8726: 
                   8727:     sub domain {
1.852     albertel 8728: 	&load_domain_tab() if (!$loaded);
                   8729: 
1.846     albertel 8730: 	my ($name,$what) = @_;
                   8731: 	return if ( !exists($domain{$name}) );
                   8732: 
                   8733: 	if (!$what) {
                   8734: 	    return $domain{$name}{'description'};
                   8735: 	}
                   8736: 	return $domain{$name}{$what};
                   8737:     }
1.974     raeburn  8738: 
                   8739:     sub domain_info {
                   8740:         &load_domain_tab() if (!$loaded);
                   8741:         return %domain;
                   8742:     }
                   8743: 
1.327     albertel 8744: }
                   8745: 
                   8746: 
1.1       albertel 8747: # ------------------------------------------------------------- Read hosts file
                   8748: {
1.838     albertel 8749:     my %hostname;
1.844     albertel 8750:     my %hostdom;
1.845     albertel 8751:     my %libserv;
1.852     albertel 8752:     my $loaded;
1.888     albertel 8753:     my %name_to_host;
1.852     albertel 8754: 
                   8755:     sub parse_hosts_tab {
                   8756: 	my ($file) = @_;
                   8757: 	foreach my $configline (@$file) {
                   8758: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8759: 	    next if ($configline =~ /^\^/);
                   8760: 	    chomp($configline);
1.968     raeburn  8761: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8762: 	    $name=~s/\s//g;
                   8763: 	    if ($id && $domain && $role && $name) {
                   8764: 		$hostname{$id}=$name;
1.888     albertel 8765: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8766: 		$hostdom{$id}=$domain;
                   8767: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8768:                 if (defined($protocol)) {
                   8769:                     if ($protocol eq 'https') {
                   8770:                         $protocol{$id} = $protocol;
                   8771:                     } else {
                   8772:                         $protocol{$id} = 'http'; 
                   8773:                     }
1.968     raeburn  8774:                 } else {
1.969     raeburn  8775:                     $protocol{$id} = 'http';
1.968     raeburn  8776:                 }
1.852     albertel 8777: 	    }
                   8778: 	}
                   8779:     }
1.864     albertel 8780:     
                   8781:     sub reset_hosts_info {
1.897     albertel 8782: 	&purge_remembered();
1.864     albertel 8783: 	&reset_domain_info();
                   8784: 	&reset_hosts_ip_info();
1.892     albertel 8785: 	undef(%name_to_host);
1.864     albertel 8786: 	undef(%hostname);
                   8787: 	undef(%hostdom);
                   8788: 	undef(%libserv);
                   8789: 	undef($loaded);
                   8790:     }
1.1       albertel 8791: 
1.852     albertel 8792:     sub load_hosts_tab {
1.869     albertel 8793: 	my ($ignore_cache) = @_;
                   8794: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8795: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8796: 	my @config = <$config>;
                   8797: 	&parse_hosts_tab(\@config);
                   8798: 	close($config);
                   8799: 	$loaded=1;
1.1       albertel 8800:     }
1.852     albertel 8801: 
1.838     albertel 8802:     sub hostname {
1.852     albertel 8803: 	&load_hosts_tab() if (!$loaded);
                   8804: 
1.838     albertel 8805: 	my ($lonid) = @_;
                   8806: 	return $hostname{$lonid};
                   8807:     }
1.845     albertel 8808: 
1.838     albertel 8809:     sub all_hostnames {
1.852     albertel 8810: 	&load_hosts_tab() if (!$loaded);
                   8811: 
1.838     albertel 8812: 	return %hostname;
                   8813:     }
1.845     albertel 8814: 
1.888     albertel 8815:     sub all_names {
                   8816: 	&load_hosts_tab() if (!$loaded);
                   8817: 
                   8818: 	return %name_to_host;
                   8819:     }
                   8820: 
1.974     raeburn  8821:     sub all_host_domain {
                   8822:         &load_hosts_tab() if (!$loaded);
                   8823:         return %hostdom;
                   8824:     }
                   8825: 
1.845     albertel 8826:     sub is_library {
1.852     albertel 8827: 	&load_hosts_tab() if (!$loaded);
                   8828: 
1.845     albertel 8829: 	return exists($libserv{$_[0]});
                   8830:     }
                   8831: 
                   8832:     sub all_library {
1.852     albertel 8833: 	&load_hosts_tab() if (!$loaded);
                   8834: 
1.845     albertel 8835: 	return %libserv;
                   8836:     }
                   8837: 
1.841     albertel 8838:     sub get_servers {
1.852     albertel 8839: 	&load_hosts_tab() if (!$loaded);
                   8840: 
1.841     albertel 8841: 	my ($domain,$type) = @_;
                   8842: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8843: 	                                          : %hostname;
                   8844: 	my %result;
1.842     albertel 8845: 	if (ref($domain) eq 'ARRAY') {
                   8846: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8847: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8848: 		    $result{$host} = $hostname;
                   8849: 		}
                   8850: 	    }
                   8851: 	} else {
                   8852: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8853: 		if ($hostdom{$host} eq $domain) {
                   8854: 		    $result{$host} = $hostname;
                   8855: 		}
1.841     albertel 8856: 	    }
                   8857: 	}
                   8858: 	return %result;
                   8859:     }
1.845     albertel 8860: 
1.844     albertel 8861:     sub host_domain {
1.852     albertel 8862: 	&load_hosts_tab() if (!$loaded);
                   8863: 
1.844     albertel 8864: 	my ($lonid) = @_;
                   8865: 	return $hostdom{$lonid};
                   8866:     }
                   8867: 
1.841     albertel 8868:     sub all_domains {
1.852     albertel 8869: 	&load_hosts_tab() if (!$loaded);
                   8870: 
1.841     albertel 8871: 	my %seen;
                   8872: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8873: 	return @uniq;
                   8874:     }
1.1       albertel 8875: }
                   8876: 
1.847     albertel 8877: { 
                   8878:     my %iphost;
1.856     albertel 8879:     my %name_to_ip;
                   8880:     my %lonid_to_ip;
1.869     albertel 8881: 
1.847     albertel 8882:     sub get_hosts_from_ip {
                   8883: 	my ($ip) = @_;
                   8884: 	my %iphosts = &get_iphost();
                   8885: 	if (ref($iphosts{$ip})) {
                   8886: 	    return @{$iphosts{$ip}};
                   8887: 	}
                   8888: 	return;
1.839     albertel 8889:     }
1.864     albertel 8890:     
                   8891:     sub reset_hosts_ip_info {
                   8892: 	undef(%iphost);
                   8893: 	undef(%name_to_ip);
                   8894: 	undef(%lonid_to_ip);
                   8895:     }
1.856     albertel 8896: 
                   8897:     sub get_host_ip {
                   8898: 	my ($lonid) = @_;
                   8899: 	if (exists($lonid_to_ip{$lonid})) {
                   8900: 	    return $lonid_to_ip{$lonid};
                   8901: 	}
                   8902: 	my $name=&hostname($lonid);
                   8903:    	my $ip = gethostbyname($name);
                   8904: 	return if (!$ip || length($ip) ne 4);
                   8905: 	$ip=inet_ntoa($ip);
                   8906: 	$name_to_ip{$name}   = $ip;
                   8907: 	$lonid_to_ip{$lonid} = $ip;
                   8908: 	return $ip;
                   8909:     }
1.847     albertel 8910:     
                   8911:     sub get_iphost {
1.869     albertel 8912: 	my ($ignore_cache) = @_;
1.894     albertel 8913: 
1.869     albertel 8914: 	if (!$ignore_cache) {
                   8915: 	    if (%iphost) {
                   8916: 		return %iphost;
                   8917: 	    }
                   8918: 	    my ($ip_info,$cached)=
                   8919: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8920: 	    if ($cached) {
                   8921: 		%iphost      = %{$ip_info->[0]};
                   8922: 		%name_to_ip  = %{$ip_info->[1]};
                   8923: 		%lonid_to_ip = %{$ip_info->[2]};
                   8924: 		return %iphost;
                   8925: 	    }
                   8926: 	}
1.894     albertel 8927: 
                   8928: 	# get yesterday's info for fallback
                   8929: 	my %old_name_to_ip;
                   8930: 	my ($ip_info,$cached)=
                   8931: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8932: 	if ($cached) {
                   8933: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8934: 	}
                   8935: 
1.888     albertel 8936: 	my %name_to_host = &all_names();
                   8937: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8938: 	    my $ip;
                   8939: 	    if (!exists($name_to_ip{$name})) {
                   8940: 		$ip = gethostbyname($name);
                   8941: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8942: 		    if (defined($old_name_to_ip{$name})) {
                   8943: 			$ip = $old_name_to_ip{$name};
                   8944: 			&logthis("Can't find $name defaulting to old $ip");
                   8945: 		    } else {
                   8946: 			&logthis("Name $name no IP found");
                   8947: 			next;
                   8948: 		    }
                   8949: 		} else {
                   8950: 		    $ip=inet_ntoa($ip);
1.847     albertel 8951: 		}
                   8952: 		$name_to_ip{$name} = $ip;
                   8953: 	    } else {
                   8954: 		$ip = $name_to_ip{$name};
1.653     albertel 8955: 	    }
1.888     albertel 8956: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8957: 		$lonid_to_ip{$id} = $ip;
                   8958: 	    }
                   8959: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8960: 	}
1.869     albertel 8961: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8962: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8963: 				      48*60*60);
1.869     albertel 8964: 
1.847     albertel 8965: 	return %iphost;
1.598     albertel 8966:     }
                   8967: }
                   8968: 
1.862     albertel 8969: BEGIN {
                   8970: 
                   8971: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8972:     unless ($readit) {
                   8973: {
                   8974:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8975:     %perlvar = (%perlvar,%{$configvars});
                   8976: }
                   8977: 
                   8978: 
1.1       albertel 8979: # ------------------------------------------------------ Read spare server file
                   8980: {
1.448     albertel 8981:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8982: 
                   8983:     while (my $configline=<$config>) {
                   8984:        chomp($configline);
1.284     matthew  8985:        if ($configline) {
1.784     albertel 8986: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8987: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8988: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8989:        }
                   8990:     }
1.448     albertel 8991:     close($config);
1.1       albertel 8992: }
1.11      www      8993: # ------------------------------------------------------------ Read permissions
                   8994: {
1.448     albertel 8995:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8996: 
                   8997:     while (my $configline=<$config>) {
1.448     albertel 8998: 	chomp($configline);
                   8999: 	if ($configline) {
                   9000: 	    my ($role,$perm)=split(/ /,$configline);
                   9001: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9002: 	}
1.11      www      9003:     }
1.448     albertel 9004:     close($config);
1.11      www      9005: }
                   9006: 
                   9007: # -------------------------------------------- Read plain texts for permissions
                   9008: {
1.448     albertel 9009:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9010: 
                   9011:     while (my $configline=<$config>) {
1.448     albertel 9012: 	chomp($configline);
                   9013: 	if ($configline) {
1.742     raeburn  9014: 	    my ($short,@plain)=split(/:/,$configline);
                   9015:             %{$prp{$short}} = ();
                   9016: 	    if (@plain > 0) {
                   9017:                 $prp{$short}{'std'} = $plain[0];
                   9018:                 for (my $i=1; $i<@plain; $i++) {
                   9019:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9020:                 }
                   9021:             }
1.448     albertel 9022: 	}
1.135     www      9023:     }
1.448     albertel 9024:     close($config);
1.135     www      9025: }
                   9026: 
                   9027: # ---------------------------------------------------------- Read package table
                   9028: {
1.448     albertel 9029:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9030: 
                   9031:     while (my $configline=<$config>) {
1.483     albertel 9032: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9033: 	chomp($configline);
                   9034: 	my ($short,$plain)=split(/:/,$configline);
                   9035: 	my ($pack,$name)=split(/\&/,$short);
                   9036: 	if ($plain ne '') {
                   9037: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9038: 	    $packagetab{$short}=$plain; 
                   9039: 	}
1.11      www      9040:     }
1.448     albertel 9041:     close($config);
1.329     matthew  9042: }
                   9043: 
                   9044: # ------------- set up temporary directory
                   9045: {
                   9046:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9047: 
1.11      www      9048: }
                   9049: 
1.794     albertel 9050: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9051: 				'compress_threshold'=> 20_000,
                   9052:  			        });
1.185     www      9053: 
1.281     www      9054: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9055: $dumpcount=0;
1.958     www      9056: $locknum=0;
1.22      www      9057: 
1.163     harris41 9058: &logtouch();
1.672     albertel 9059: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9060: $readit=1;
1.564     albertel 9061:     {
                   9062: 	use integer;
                   9063: 	my $test=(2**32)+1;
1.568     albertel 9064: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9065: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9066:     }
1.195     www      9067: }
1.1       albertel 9068: }
1.179     www      9069: 
1.1       albertel 9070: 1;
1.191     harris41 9071: __END__
                   9072: 
1.243     albertel 9073: =pod
                   9074: 
1.191     harris41 9075: =head1 NAME
                   9076: 
1.243     albertel 9077: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9078: 
                   9079: =head1 SYNOPSIS
                   9080: 
1.243     albertel 9081: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9082: 
                   9083:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9084: 
1.243     albertel 9085: Common parameters:
                   9086: 
                   9087: =over 4
                   9088: 
                   9089: =item *
                   9090: 
                   9091: $uname : an internal username (if $cname expecting a course Id specifically)
                   9092: 
                   9093: =item *
                   9094: 
                   9095: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9096: 
                   9097: =item *
                   9098: 
                   9099: $symb : a resource instance identifier
                   9100: 
                   9101: =item *
                   9102: 
                   9103: $namespace : the name of a .db file that contains the data needed or
                   9104: being set.
                   9105: 
                   9106: =back
                   9107: 
1.394     bowersj2 9108: =head1 OVERVIEW
1.191     harris41 9109: 
1.394     bowersj2 9110: lonnet provides subroutines which interact with the
                   9111: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9112: about classes, users, and resources.
1.243     albertel 9113: 
                   9114: For many of these objects you can also use this to store data about
                   9115: them or modify them in various ways.
1.191     harris41 9116: 
1.394     bowersj2 9117: =head2 Symbs
1.191     harris41 9118: 
1.394     bowersj2 9119: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9120: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9121: map, the resource number of the resource in the map, and the URL of
                   9122: the resource itself. The latter is somewhat redundant, but might help
                   9123: if maps change.
                   9124: 
                   9125: An example is
                   9126: 
                   9127:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9128: 
                   9129: The respective map entry is
                   9130: 
                   9131:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9132:   title="Problem 2">
                   9133:  </resource>
                   9134: 
                   9135: Symbs are used by the random number generator, as well as to store and
                   9136: restore data specific to a certain instance of for example a problem.
                   9137: 
                   9138: =head2 Storing And Retrieving Data
                   9139: 
                   9140: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9141: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9142: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9143: is is the non-critical message twin of cstore. These functions are for
                   9144: handlers to store a perl hash to a user's permanent data space in an
                   9145: easy manner, and to retrieve it again on another call. It is expected
                   9146: that a handler would use this once at the beginning to retrieve data,
                   9147: and then again once at the end to send only the new data back.
                   9148: 
                   9149: The data is stored in the user's data directory on the user's
                   9150: homeserver under the ID of the course.
                   9151: 
                   9152: The hash that is returned by restore will have all of the previous
                   9153: value for all of the elements of the hash.
                   9154: 
                   9155: Example:
                   9156: 
                   9157:  #creating a hash
                   9158:  my %hash;
                   9159:  $hash{'foo'}='bar';
                   9160: 
                   9161:  #storing it
                   9162:  &Apache::lonnet::cstore(\%hash);
                   9163: 
                   9164:  #changing a value
                   9165:  $hash{'foo'}='notbar';
                   9166: 
                   9167:  #adding a new value
                   9168:  $hash{'bar'}='foo';
                   9169:  &Apache::lonnet::cstore(\%hash);
                   9170: 
                   9171:  #retrieving the hash
                   9172:  my %history=&Apache::lonnet::restore();
                   9173: 
                   9174:  #print the hash
                   9175:  foreach my $key (sort(keys(%history))) {
                   9176:    print("\%history{$key} = $history{$key}");
                   9177:  }
                   9178: 
                   9179: Will print out:
1.191     harris41 9180: 
1.394     bowersj2 9181:  %history{1:foo} = bar
                   9182:  %history{1:keys} = foo:timestamp
                   9183:  %history{1:timestamp} = 990455579
                   9184:  %history{2:bar} = foo
                   9185:  %history{2:foo} = notbar
                   9186:  %history{2:keys} = foo:bar:timestamp
                   9187:  %history{2:timestamp} = 990455580
                   9188:  %history{bar} = foo
                   9189:  %history{foo} = notbar
                   9190:  %history{timestamp} = 990455580
                   9191:  %history{version} = 2
                   9192: 
                   9193: Note that the special hash entries C<keys>, C<version> and
                   9194: C<timestamp> were added to the hash. C<version> will be equal to the
                   9195: total number of versions of the data that have been stored. The
                   9196: C<timestamp> attribute will be the UNIX time the hash was
                   9197: stored. C<keys> is available in every historical section to list which
                   9198: keys were added or changed at a specific historical revision of a
                   9199: hash.
                   9200: 
                   9201: B<Warning>: do not store the hash that restore returns directly. This
                   9202: will cause a mess since it will restore the historical keys as if the
                   9203: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9204: 
1.394     bowersj2 9205: Calling convention:
1.191     harris41 9206: 
1.394     bowersj2 9207:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9208:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9209: 
1.394     bowersj2 9210: For more detailed information, see lonnet specific documentation.
1.191     harris41 9211: 
1.394     bowersj2 9212: =head1 RETURN MESSAGES
1.191     harris41 9213: 
1.394     bowersj2 9214: =over 4
1.191     harris41 9215: 
1.394     bowersj2 9216: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9217: 
1.394     bowersj2 9218: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9219: when the connection is brought back up
1.191     harris41 9220: 
1.394     bowersj2 9221: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9222: for later delivery
1.191     harris41 9223: 
1.967     bisitz   9224: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9225: 
1.394     bowersj2 9226: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9227: that was requested
1.191     harris41 9228: 
1.243     albertel 9229: =back
1.191     harris41 9230: 
1.243     albertel 9231: =head1 PUBLIC SUBROUTINES
1.191     harris41 9232: 
1.243     albertel 9233: =head2 Session Environment Functions
1.191     harris41 9234: 
1.243     albertel 9235: =over 4
1.191     harris41 9236: 
1.394     bowersj2 9237: =item * 
                   9238: X<appenv()>
1.949     raeburn  9239: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9240: the user envirnoment file, and will be restored for each access this
1.620     albertel 9241: user makes during this session, also modifies the %env for the current
1.949     raeburn  9242: process. Optional rolesarrayref - if defined contains a reference to an array
                   9243: of roles which are exempt from the restriction on modifying user.role entries 
                   9244: in the user's environment.db and in %env.    
1.191     harris41 9245: 
                   9246: =item *
1.394     bowersj2 9247: X<delenv()>
                   9248: B<delenv($regexp)>: removes all items from the session
                   9249: environment file that matches the regular expression in $regexp. The
1.620     albertel 9250: values are also delted from the current processes %env.
1.191     harris41 9251: 
1.795     albertel 9252: =item * get_env_multiple($name) 
                   9253: 
                   9254: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9255: values may be defined and end up as an array ref.
                   9256: 
                   9257: returns an array of values
                   9258: 
1.243     albertel 9259: =back
                   9260: 
                   9261: =head2 User Information
1.191     harris41 9262: 
1.243     albertel 9263: =over 4
1.191     harris41 9264: 
                   9265: =item *
1.394     bowersj2 9266: X<queryauthenticate()>
                   9267: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9268: authentication scheme
                   9269: 
                   9270: =item *
1.394     bowersj2 9271: X<authenticate()>
                   9272: B<authenticate($uname,$upass,$udom)>: try to
                   9273: authenticate user from domain's lib servers (first use the current
                   9274: one). C<$upass> should be the users password.
1.191     harris41 9275: 
                   9276: =item *
1.394     bowersj2 9277: X<homeserver()>
                   9278: B<homeserver($uname,$udom)>: find the server which has
                   9279: the user's directory and files (there must be only one), this caches
                   9280: the answer, and also caches if there is a borken connection.
1.191     harris41 9281: 
                   9282: =item *
1.394     bowersj2 9283: X<idget()>
                   9284: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9285: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9286: username, and only 1 username per ID in a specific domain) (returns
                   9287: hash: id=>name,id=>name)
1.191     harris41 9288: 
                   9289: =item *
1.394     bowersj2 9290: X<idrget()>
                   9291: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9292: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9293: 
                   9294: =item *
1.394     bowersj2 9295: X<idput()>
                   9296: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9297: 
                   9298: =item *
1.394     bowersj2 9299: X<rolesinit()>
                   9300: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9301: 
                   9302: =item *
1.551     albertel 9303: X<getsection()>
                   9304: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9305: course $cname, return section name/number or '' for "not in course"
                   9306: and '-1' for "no section"
                   9307: 
                   9308: =item *
1.394     bowersj2 9309: X<userenvironment()>
                   9310: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9311: passed in @what from the requested user's environment, returns a hash
                   9312: 
1.858     raeburn  9313: =item * 
                   9314: X<userlog_query()>
1.859     albertel 9315: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9316: activity.log file. %filters defines filters applied when parsing the
                   9317: log file. These can be start or end timestamps, or the type of action
                   9318: - log to look for Login or Logout events, check for Checkin or
                   9319: Checkout, role for role selection. The response is in the form
                   9320: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9321: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9322: 
1.243     albertel 9323: =back
                   9324: 
                   9325: =head2 User Roles
                   9326: 
                   9327: =over 4
                   9328: 
                   9329: =item *
                   9330: 
1.810     raeburn  9331: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9332:  F: full access
                   9333:  U,I,K: authentication modes (cxx only)
                   9334:  '': forbidden
                   9335:  1: user needs to choose course
                   9336:  2: browse allowed
1.766     albertel 9337:  A: passphrase authentication needed
1.243     albertel 9338: 
                   9339: =item *
                   9340: 
                   9341: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9342: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9343: and course level
                   9344: 
                   9345: =item *
                   9346: 
                   9347: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9348: explanation of a user role term
                   9349: 
1.832     raeburn  9350: =item *
                   9351: 
1.935     raeburn  9352: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9353: All arguments are optional. Returns a hash of a roles, either for
                   9354: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9355: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9356: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9357: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9358: For each key, value is set to colon-separated start and end times for
                   9359: the role.  If no username and domain are specified, will default to
1.934     raeburn  9360: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9361: of role statuses (active, future or previous), roles 
                   9362: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9363: to restrict the list of roles reported. If no array ref is 
                   9364: provided for types, will default to return only active roles.
1.834     albertel 9365: 
1.243     albertel 9366: =back
                   9367: 
                   9368: =head2 User Modification
                   9369: 
                   9370: =over 4
                   9371: 
                   9372: =item *
                   9373: 
1.957     raeburn  9374: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9375: user for the level given by URL.  Optional start and end dates (leave empty
                   9376: string or zero for "no date")
1.191     harris41 9377: 
                   9378: =item *
                   9379: 
1.243     albertel 9380: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9381: change a users, password, possible return values are: ok,
                   9382: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9383: refused
1.191     harris41 9384: 
                   9385: =item *
                   9386: 
1.243     albertel 9387: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9388: 
                   9389: =item *
                   9390: 
1.963     raeburn  9391: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9392:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9393: modify user
1.191     harris41 9394: 
                   9395: =item *
                   9396: 
1.286     matthew  9397: modifystudent
                   9398: 
1.957     raeburn  9399: modify a student's enrollment and identification information.
1.286     matthew  9400: The course id is resolved based on the current users environment.  
                   9401: This means the envoking user must be a course coordinator or otherwise
                   9402: associated with a course.
                   9403: 
1.297     matthew  9404: This call is essentially a wrapper for lonnet::modifyuser and
                   9405: lonnet::modify_student_enrollment
1.286     matthew  9406: 
                   9407: Inputs: 
                   9408: 
                   9409: =over 4
                   9410: 
1.957     raeburn  9411: =item B<$udom> Student's loncapa domain
1.286     matthew  9412: 
1.957     raeburn  9413: =item B<$uname> Student's loncapa login name
1.286     matthew  9414: 
1.964     bisitz   9415: =item B<$uid> Student/Employee ID
1.286     matthew  9416: 
1.957     raeburn  9417: =item B<$umode> Student's authentication mode
1.286     matthew  9418: 
1.957     raeburn  9419: =item B<$upass> Student's password
1.286     matthew  9420: 
1.957     raeburn  9421: =item B<$first> Student's first name
1.286     matthew  9422: 
1.957     raeburn  9423: =item B<$middle> Student's middle name
1.286     matthew  9424: 
1.957     raeburn  9425: =item B<$last> Student's last name
1.286     matthew  9426: 
1.957     raeburn  9427: =item B<$gene> Student's generation
1.286     matthew  9428: 
1.957     raeburn  9429: =item B<$usec> Student's section in course
1.286     matthew  9430: 
                   9431: =item B<$end> Unix time of the roles expiration
                   9432: 
                   9433: =item B<$start> Unix time of the roles start date
                   9434: 
                   9435: =item B<$forceid> If defined, allow $uid to be changed
                   9436: 
                   9437: =item B<$desiredhome> server to use as home server for student
                   9438: 
1.957     raeburn  9439: =item B<$email> Student's permanent e-mail address
                   9440: 
                   9441: =item B<$type> Type of enrollment (auto or manual)
                   9442: 
1.963     raeburn  9443: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9444: 
                   9445: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9446: 
1.963     raeburn  9447: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9448: 
1.963     raeburn  9449: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9450: 
1.963     raeburn  9451: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9452: 
1.286     matthew  9453: =back
1.297     matthew  9454: 
                   9455: =item *
                   9456: 
                   9457: modify_student_enrollment
                   9458: 
                   9459: Change a students enrollment status in a class.  The environment variable
                   9460: 'role.request.course' must be defined for this function to proceed.
                   9461: 
                   9462: Inputs:
                   9463: 
                   9464: =over 4
                   9465: 
                   9466: =item $udom, students domain
                   9467: 
                   9468: =item $uname, students name
                   9469: 
                   9470: =item $uid, students user id
                   9471: 
                   9472: =item $first, students first name
                   9473: 
                   9474: =item $middle
                   9475: 
                   9476: =item $last
                   9477: 
                   9478: =item $gene
                   9479: 
                   9480: =item $usec
                   9481: 
                   9482: =item $end
                   9483: 
                   9484: =item $start
                   9485: 
1.957     raeburn  9486: =item $type
                   9487: 
                   9488: =item $locktype
                   9489: 
                   9490: =item $cid
                   9491: 
                   9492: =item $selfenroll
                   9493: 
                   9494: =item $context
                   9495: 
1.297     matthew  9496: =back
                   9497: 
1.191     harris41 9498: 
                   9499: =item *
                   9500: 
1.243     albertel 9501: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9502: custom role; give a custom role to a user for the level given by URL.  Specify
                   9503: name and domain of role author, and role name
1.191     harris41 9504: 
                   9505: =item *
                   9506: 
1.243     albertel 9507: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9508: 
                   9509: =item *
                   9510: 
1.243     albertel 9511: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9512: 
                   9513: =back
                   9514: 
                   9515: =head2 Course Infomation
                   9516: 
                   9517: =over 4
1.191     harris41 9518: 
                   9519: =item *
                   9520: 
1.631     albertel 9521: coursedescription($courseid) : returns a hash of information about the
                   9522: specified course id, including all environment settings for the
                   9523: course, the description of the course will be in the hash under the
                   9524: key 'description'
1.191     harris41 9525: 
                   9526: =item *
                   9527: 
1.624     albertel 9528: resdata($name,$domain,$type,@which) : request for current parameter
                   9529: setting for a specific $type, where $type is either 'course' or 'user',
                   9530: @what should be a list of parameters to ask about. This routine caches
                   9531: answers for 5 minutes.
1.243     albertel 9532: 
1.877     foxr     9533: =item *
                   9534: 
                   9535: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9536: data base, returning a hash that is keyed by the resource name and has
                   9537: values that are the resource value.  I believe that the timestamps and
                   9538: versions are also returned.
                   9539: 
                   9540: 
1.243     albertel 9541: =back
                   9542: 
                   9543: =head2 Course Modification
                   9544: 
                   9545: =over 4
1.191     harris41 9546: 
                   9547: =item *
                   9548: 
1.243     albertel 9549: writecoursepref($courseid,%prefs) : write preferences (environment
                   9550: database) for a course
1.191     harris41 9551: 
                   9552: =item *
                   9553: 
1.243     albertel 9554: createcourse($udom,$description,$url) : make/modify course
                   9555: 
                   9556: =back
                   9557: 
                   9558: =head2 Resource Subroutines
                   9559: 
                   9560: =over 4
1.191     harris41 9561: 
                   9562: =item *
                   9563: 
1.243     albertel 9564: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9565: 
                   9566: =item *
                   9567: 
1.243     albertel 9568: repcopy($filename) : subscribes to the requested file, and attempts to
                   9569: replicate from the owning library server, Might return
1.607     raeburn  9570: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9571: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9572: resource. Expects the local filesystem pathname
                   9573: (/home/httpd/html/res/....)
                   9574: 
                   9575: =back
                   9576: 
                   9577: =head2 Resource Information
                   9578: 
                   9579: =over 4
1.191     harris41 9580: 
                   9581: =item *
                   9582: 
1.243     albertel 9583: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9584: a vairety of different possible values, $varname should be a request
                   9585: string, and the other parameters can be used to specify who and what
                   9586: one is asking about.
                   9587: 
                   9588: Possible values for $varname are environment.lastname (or other item
                   9589: from the envirnment hash), user.name (or someother aspect about the
                   9590: user), resource.0.maxtries (or some other part and parameter of a
                   9591: resource)
1.204     albertel 9592: 
                   9593: =item *
                   9594: 
1.243     albertel 9595: directcondval($number) : get current value of a condition; reads from a state
                   9596: string
1.204     albertel 9597: 
                   9598: =item *
                   9599: 
1.243     albertel 9600: condval($condidx) : value of condition index based on state
1.204     albertel 9601: 
                   9602: =item *
                   9603: 
1.243     albertel 9604: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9605: resource's metadata, $what should be either a specific key, or either
                   9606: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9607: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9608: 
                   9609: this function automatically caches all requests
1.191     harris41 9610: 
                   9611: =item *
                   9612: 
1.243     albertel 9613: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9614: network of library servers; returns file handle of where SQL and regex results
                   9615: will be stored for query
1.191     harris41 9616: 
                   9617: =item *
                   9618: 
1.243     albertel 9619: symbread($filename) : return symbolic list entry (filename argument optional);
                   9620: returns the data handle
1.191     harris41 9621: 
                   9622: =item *
                   9623: 
1.243     albertel 9624: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9625: a possible symb for the URL in $thisfn, and if is an encryypted
                   9626: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9627: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9628: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9629: 
1.191     harris41 9630: 
                   9631: =item *
                   9632: 
1.243     albertel 9633: symbclean($symb) : removes versions numbers from a symb, returns the
                   9634: cleaned symb
1.191     harris41 9635: 
                   9636: =item *
                   9637: 
1.243     albertel 9638: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9639: course map, user must be in a course for it to work.
1.191     harris41 9640: 
                   9641: =item *
                   9642: 
1.243     albertel 9643: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9644: 
                   9645: =item *
                   9646: 
1.243     albertel 9647: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9648: a random seed, all arguments are optional, if they aren't sent it uses the
                   9649: environment to derive them. Note: if symb isn't sent and it can't get one
                   9650: from &symbread it will use the current time as its return value
1.191     harris41 9651: 
                   9652: =item *
                   9653: 
1.243     albertel 9654: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9655: unfakeable, receipt
1.191     harris41 9656: 
                   9657: =item *
                   9658: 
1.620     albertel 9659: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9660: 
                   9661: =item *
                   9662: 
1.243     albertel 9663: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9664: 
                   9665: =item *
                   9666: 
1.243     albertel 9667: 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 9668: 
                   9669: =item *
                   9670: 
1.243     albertel 9671: 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 9672: 
                   9673: =item *
                   9674: 
1.243     albertel 9675: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9676: 
                   9677: =item *
                   9678: 
1.243     albertel 9679: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9680: forcing spreadsheet to reevaluate the resource scores next time.
                   9681: 
                   9682: =back
                   9683: 
                   9684: =head2 Storing/Retreiving Data
                   9685: 
                   9686: =over 4
1.191     harris41 9687: 
                   9688: =item *
                   9689: 
1.243     albertel 9690: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9691: for this url; hashref needs to be given and should be a \%hashname; the
                   9692: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9693: be derived from the env
1.191     harris41 9694: 
                   9695: =item *
                   9696: 
1.243     albertel 9697: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9698: uses critical subroutine
1.191     harris41 9699: 
                   9700: =item *
                   9701: 
1.243     albertel 9702: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9703: all args are optional
1.191     harris41 9704: 
                   9705: =item *
                   9706: 
1.717     albertel 9707: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9708: dumps the complete (or key matching regexp) namespace into a hash
                   9709: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9710: normally &store()ed into
                   9711: 
                   9712: $range should be either an integer '100' (give me the first 100
                   9713:                                            matching records)
                   9714:               or be  two integers sperated by a - with no spaces
                   9715:                  '30-50' (give me the 30th through the 50th matching
                   9716:                           records)
                   9717: 
                   9718: 
                   9719: =item *
                   9720: 
                   9721: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9722: replaces a &store() version of data with a replacement set of data
                   9723: for a particular resource in a namespace passed in the $storehash hash 
                   9724: reference
                   9725: 
                   9726: =item *
                   9727: 
1.243     albertel 9728: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9729: works very similar to store/cstore, but all data is stored in a
                   9730: temporary location and can be reset using tmpreset, $storehash should
                   9731: be a hash reference, returns nothing on success
1.191     harris41 9732: 
                   9733: =item *
                   9734: 
1.243     albertel 9735: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9736: similar to restore, but all data is stored in a temporary location and
                   9737: can be reset using tmpreset. Returns a hash of values on success,
                   9738: error string otherwise.
1.191     harris41 9739: 
                   9740: =item *
                   9741: 
1.243     albertel 9742: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9743: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9744: 
                   9745: =item *
                   9746: 
1.243     albertel 9747: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9748: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9749: 
                   9750: =item *
                   9751: 
1.243     albertel 9752: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9753: namesp ($udom and $uname are optional)
1.191     harris41 9754: 
                   9755: =item *
                   9756: 
1.702     albertel 9757: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9758: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9759: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9760: 
1.702     albertel 9761: $range should be either an integer '100' (give me the first 100
                   9762:                                            matching records)
                   9763:               or be  two integers sperated by a - with no spaces
                   9764:                  '30-50' (give me the 30th through the 50th matching
                   9765:                           records)
1.449     matthew  9766: =item *
                   9767: 
                   9768: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9769: $store can be a scalar, an array reference, or if the amount to be 
                   9770: incremented is > 1, a hash reference.
                   9771: 
                   9772: ($udom and $uname are optional)
1.191     harris41 9773: 
                   9774: =item *
                   9775: 
1.243     albertel 9776: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9777: ($udom and $uname are optional)
1.191     harris41 9778: 
                   9779: =item *
                   9780: 
1.243     albertel 9781: cput($namespace,$storehash,$udom,$uname) : critical put
                   9782: ($udom and $uname are optional)
1.191     harris41 9783: 
                   9784: =item *
                   9785: 
1.748     albertel 9786: newput($namespace,$storehash,$udom,$uname) :
                   9787: 
                   9788: Attempts to store the items in the $storehash, but only if they don't
                   9789: currently exist, if this succeeds you can be certain that you have 
                   9790: successfully created a new key value pair in the $namespace db.
                   9791: 
                   9792: 
                   9793: Args:
                   9794:  $namespace: name of database to store values to
                   9795:  $storehash: hashref to store to the db
                   9796:  $udom: (optional) domain of user containing the db
                   9797:  $uname: (optional) name of user caontaining the db
                   9798: 
                   9799: Returns:
                   9800:  'ok' -> succeeded in storing all keys of $storehash
                   9801:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9802:                         least <key> already existed in the db (other
                   9803:                         requested keys may also already exist)
1.967     bisitz   9804:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9805:  'con_lost' -> unable to contact request server
                   9806:  'refused' -> action was not allowed by remote machine
                   9807: 
                   9808: 
                   9809: =item *
                   9810: 
1.243     albertel 9811: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9812: reference filled in from namesp (encrypts the return communication)
                   9813: ($udom and $uname are optional)
1.191     harris41 9814: 
                   9815: =item *
                   9816: 
1.243     albertel 9817: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9818: critical subroutine
                   9819: 
1.806     raeburn  9820: =item *
                   9821: 
1.860     raeburn  9822: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9823: array reference filled in from namespace found in domain level on either
                   9824: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9825: 
                   9826: =item *
                   9827: 
1.860     raeburn  9828: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9829: domain level either on specified domain server ($uhome) or primary domain 
                   9830: server ($udom and $uhome are optional)
1.806     raeburn  9831: 
1.943     raeburn  9832: =item * 
                   9833: 
                   9834: get_domain_defaults($target_domain) : returns hash with defaults for
                   9835: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9836: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9837: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9838: Values are retrieved from cache (if current), or from domain's configuration.db
                   9839: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9840: or lonTabs/domain.tab. 
                   9841: 
                   9842: %domdefaults = &get_auth_defaults($target_domain);
                   9843: 
1.243     albertel 9844: =back
                   9845: 
                   9846: =head2 Network Status Functions
                   9847: 
                   9848: =over 4
1.191     harris41 9849: 
                   9850: =item *
                   9851: 
                   9852: dirlist($uri) : return directory list based on URI
                   9853: 
                   9854: =item *
                   9855: 
1.243     albertel 9856: spareserver() : find server with least workload from spare.tab
                   9857: 
                   9858: =back
                   9859: 
                   9860: =head2 Apache Request
                   9861: 
                   9862: =over 4
1.191     harris41 9863: 
                   9864: =item *
                   9865: 
1.243     albertel 9866: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9867: localhost, posts hash
                   9868: 
                   9869: =back
                   9870: 
                   9871: =head2 Data to String to Data
                   9872: 
                   9873: =over 4
1.191     harris41 9874: 
                   9875: =item *
                   9876: 
1.243     albertel 9877: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9878: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9879: 
                   9880: =item *
                   9881: 
1.243     albertel 9882: hashref2str($hashref) : convert a hashref into a string complete with
                   9883: escaping and '=' and '&' separators, supports elements that are
                   9884: arrayrefs and hashrefs
1.191     harris41 9885: 
                   9886: =item *
                   9887: 
1.243     albertel 9888: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9889: with escaping and '&' separators, supports elements that are arrayrefs
                   9890: and hashrefs
1.191     harris41 9891: 
                   9892: =item *
                   9893: 
1.243     albertel 9894: str2hash($string) : convert string to hash using unescaping and
                   9895: splitting on '=' and '&', supports elements that are arrayrefs and
                   9896: hashrefs
1.191     harris41 9897: 
                   9898: =item *
                   9899: 
1.243     albertel 9900: str2array($string) : convert string to hash using unescaping and
                   9901: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9902: 
                   9903: =back
                   9904: 
                   9905: =head2 Logging Routines
                   9906: 
                   9907: =over 4
                   9908: 
                   9909: These routines allow one to make log messages in the lonnet.log and
                   9910: lonnet.perm logfiles.
1.191     harris41 9911: 
                   9912: =item *
                   9913: 
1.243     albertel 9914: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9915: 
                   9916: =item *
                   9917: 
1.243     albertel 9918: logthis() : append message to the normal lonnet.log file, it gets
                   9919: preiodically rolled over and deleted.
1.191     harris41 9920: 
                   9921: =item *
                   9922: 
1.243     albertel 9923: logperm() : append a permanent message to lonnet.perm.log, this log
                   9924: file never gets deleted by any automated portion of the system, only
                   9925: messages of critical importance should go in here.
                   9926: 
                   9927: =back
                   9928: 
                   9929: =head2 General File Helper Routines
                   9930: 
                   9931: =over 4
1.191     harris41 9932: 
                   9933: =item *
                   9934: 
1.481     raeburn  9935: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9936: (a) files in /uploaded
                   9937:   (i) If a local copy of the file exists - 
                   9938:       compares modification date of local copy with last-modified date for 
                   9939:       definitive version stored on home server for course. If local copy is 
                   9940:       stale, requests a new version from the home server and stores it. 
                   9941:       If the original has been removed from the home server, then local copy 
                   9942:       is unlinked.
                   9943:   (ii) If local copy does not exist -
                   9944:       requests the file from the home server and stores it. 
                   9945:   
                   9946:   If $caller is 'uploadrep':  
                   9947:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9948:     for request for files originally uploaded via DOCS. 
                   9949:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9950:   
                   9951:   Otherwise:
                   9952:      This indicates a call from the content generation phase of the request.
                   9953:      -  returns the entire contents of the file or -1.
                   9954:      
                   9955: (b) files in /res
                   9956:    - returns the entire contents of a file or -1; 
                   9957:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9958: 
1.712     albertel 9959: 
                   9960: =item *
                   9961: 
                   9962: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9963:                   reference
                   9964: 
                   9965: returns either a stat() list of data about the file or an empty list
                   9966: if the file doesn't exist or couldn't find out about it (connection
                   9967: problems or user unknown)
                   9968: 
1.191     harris41 9969: =item *
                   9970: 
1.243     albertel 9971: filelocation($dir,$file) : returns file system location of a file
                   9972: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9973: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9974: and a file of ../bob will become /a/bob)
1.191     harris41 9975: 
                   9976: =item *
                   9977: 
                   9978: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9979: filelocation except for hrefs
                   9980: 
                   9981: =item *
                   9982: 
                   9983: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9984: 
1.243     albertel 9985: =back
                   9986: 
1.608     albertel 9987: =head2 Usererfile file routines (/uploaded*)
                   9988: 
                   9989: =over 4
                   9990: 
                   9991: =item *
                   9992: 
                   9993: userfileupload(): main rotine for putting a file in a user or course's
                   9994:                   filespace, arguments are,
                   9995: 
1.620     albertel 9996:  formname - required - this is the name of the element in $env where the
1.608     albertel 9997:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9998:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9999:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10000:  coursedoc - if true, store the file in the course of the active role
                   10001:              of the current user
                   10002:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10003:          if undefined, it will be placed in "unknown"
                   10004: 
                   10005:  (This routine calls clean_filename() to remove any dangerous
                   10006:  characters from the filename, and then calls finuserfileupload() to
                   10007:  complete the transaction)
                   10008: 
                   10009:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10010:  and /adm/notfound.html if unsuccessful
                   10011: 
                   10012: =item *
                   10013: 
                   10014: clean_filename(): routine for cleaing a filename up for storage in
                   10015:                  userfile space, argument is:
                   10016: 
                   10017:  filename - proposed filename
                   10018: 
                   10019: returns: the new clean filename
                   10020: 
                   10021: =item *
                   10022: 
                   10023: finishuserfileupload(): routine that creaes and sends the file to
                   10024: userspace, probably shouldn't be called directly
                   10025: 
                   10026:   docuname: username or courseid of destination for the file
                   10027:   docudom: domain of user/course of destination for the file
                   10028:   formname: same as for userfileupload()
                   10029:   fname: filename (inculding subdirectories) for the file
                   10030: 
                   10031:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10032:  and /adm/notfound.html if unsuccessful
                   10033: 
                   10034: =item *
                   10035: 
                   10036: renameuserfile(): renames an existing userfile to a new name
                   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:    old: current file name (including any subdirs under userfiles)
                   10042:    new: desired file name (including any subdirs under userfiles)
                   10043: 
                   10044: =item *
                   10045: 
                   10046: mkdiruserfile(): creates a directory is a userfiles dir
                   10047: 
                   10048:   Args:
                   10049:    docuname: username or courseid of destination for the file
                   10050:    docudom: domain of user/course of destination for the file
                   10051:    dir: dir to create (including any subdirs under userfiles)
                   10052: 
                   10053: =item *
                   10054: 
                   10055: removeuserfile(): removes a file that exists in userfiles
                   10056: 
                   10057:   Args:
                   10058:    docuname: username or courseid of destination for the file
                   10059:    docudom: domain of user/course of destination for the file
                   10060:    fname: filname to delete (including any subdirs under userfiles)
                   10061: 
                   10062: =item *
                   10063: 
                   10064: removeuploadedurl(): convience function for removeuserfile()
                   10065: 
                   10066:   Args:
                   10067:    url:  a full /uploaded/... url to delete
                   10068: 
1.747     albertel 10069: =item * 
                   10070: 
                   10071: get_portfile_permissions():
                   10072:   Args:
                   10073:     domain: domain of user or course contain the portfolio files
                   10074:     user: name of user or num of course contain the portfolio files
                   10075:   Returns:
                   10076:     hashref of a dump of the proper file_permissions.db
                   10077:    
                   10078: 
                   10079: =item * 
                   10080: 
                   10081: get_access_controls():
                   10082: 
                   10083: Args:
                   10084:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10085:   group: (optional) the group you want the files associated with
                   10086:   file: (optional) the file you want access info on
                   10087: 
                   10088: Returns:
1.749     raeburn  10089:     a hash (keys are file names) of hashes containing
                   10090:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10091:         values are XML containing access control settings (see below) 
1.747     albertel 10092: 
                   10093: Internal notes:
                   10094: 
1.749     raeburn  10095:  access controls are stored in file_permissions.db as key=value pairs.
                   10096:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10097:         where scope -> public,guest,course,group,domains or users.
                   10098:               end -> UNIX time for end of access (0 -> no end date)
                   10099:               start -> UNIX time for start of access
                   10100: 
                   10101:     value -> XML description of access control
                   10102:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10103:             <start></start>
                   10104:             <end></end>
                   10105: 
                   10106:             <password></password>  for scope type = guest
                   10107: 
                   10108:             <domain></domain>     for scope type = course or group
                   10109:             <number></number>
                   10110:             <roles id="">
                   10111:              <role></role>
                   10112:              <access></access>
                   10113:              <section></section>
                   10114:              <group></group>
                   10115:             </roles>
                   10116: 
                   10117:             <dom></dom>         for scope type = domains
                   10118: 
                   10119:             <users>             for scope type = users
                   10120:              <user>
                   10121:               <uname></uname>
                   10122:               <udom></udom>
                   10123:              </user>
                   10124:             </users>
                   10125:            </scope> 
                   10126:               
                   10127:  Access data is also aggregated for each file in an additional key=value pair:
                   10128:  key -> path to file/file_name\0accesscontrol 
                   10129:  value -> reference to hash
                   10130:           hash contains key = value pairs
                   10131:           where key = uniqueID:scope_end_start
                   10132:                 value = UNIX time record was last updated
                   10133: 
                   10134:           Used to improve speed of look-ups of access controls for each file.  
                   10135:  
                   10136:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10137: 
                   10138: modify_access_controls():
                   10139: 
                   10140: Modifies access controls for a portfolio file
                   10141: Args
                   10142: 1. file name
                   10143: 2. reference to hash of required changes,
                   10144: 3. domain
                   10145: 4. username
                   10146:   where domain,username are the domain of the portfolio owner 
                   10147:   (either a user or a course) 
                   10148: 
                   10149: Returns:
                   10150: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10151: 2. result of deletions ('ok' or 'error', with error message).
                   10152: 3. reference to hash of any new or updated access controls.
                   10153: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10154:    key = integer (inbound ID)
                   10155:    value = uniqueID  
1.747     albertel 10156: 
1.608     albertel 10157: =back
                   10158: 
1.243     albertel 10159: =head2 HTTP Helper Routines
                   10160: 
                   10161: =over 4
                   10162: 
1.191     harris41 10163: =item *
                   10164: 
                   10165: escape() : unpack non-word characters into CGI-compatible hex codes
                   10166: 
                   10167: =item *
                   10168: 
                   10169: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10170: 
1.243     albertel 10171: =back
                   10172: 
                   10173: =head1 PRIVATE SUBROUTINES
                   10174: 
                   10175: =head2 Underlying communication routines (Shouldn't call)
                   10176: 
                   10177: =over 4
                   10178: 
                   10179: =item *
                   10180: 
                   10181: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10182: 
                   10183: =item *
                   10184: 
                   10185: reply() : uses subreply to send a message to remote machine, logs all failures
                   10186: 
                   10187: =item *
                   10188: 
                   10189: critical() : passes a critical message to another server; if cannot
                   10190: get through then place message in connection buffer directory and
                   10191: returns con_delayed, if incapable of saving message, returns
                   10192: con_failed
                   10193: 
                   10194: =item *
                   10195: 
                   10196: reconlonc() : tries to reconnect lonc client processes.
                   10197: 
                   10198: =back
                   10199: 
                   10200: =head2 Resource Access Logging
                   10201: 
                   10202: =over 4
                   10203: 
                   10204: =item *
                   10205: 
                   10206: flushcourselogs() : flush (save) buffer logs and access logs
                   10207: 
                   10208: =item *
                   10209: 
                   10210: courselog($what) : save message for course in hash
                   10211: 
                   10212: =item *
                   10213: 
                   10214: courseacclog($what) : save message for course using &courselog().  Perform
                   10215: special processing for specific resource types (problems, exams, quizzes, etc).
                   10216: 
1.191     harris41 10217: =item *
                   10218: 
                   10219: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10220: as a PerlChildExitHandler
1.243     albertel 10221: 
                   10222: =back
                   10223: 
                   10224: =head2 Other
                   10225: 
                   10226: =over 4
                   10227: 
                   10228: =item *
                   10229: 
                   10230: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10231: 
                   10232: =back
                   10233: 
                   10234: =cut
1.877     foxr     10235: 

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