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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.987   ! raeburn     4: # $Id: lonnet.pm,v 1.986 2009/02/10 11:15:16 foxr 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;
1.986     foxr       77: use IO::Socket;
1.977     amueller   78: 
1.486     www        79: # use Date::Parse;
1.871     albertel   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    81:             $_64bit %env %protocol);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.539     albertel   93: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.676     albertel   99: 
1.195     www       100: my $readit;
1.550     foxr      101: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  102: 
1.977     amueller  103: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
                    104: 
1.619     albertel  105: require Exporter;
                    106: 
                    107: our @ISA = qw (Exporter);
                    108: our @EXPORT = qw(%env);
                    109: 
1.449     matthew   110: 
1.1       albertel  111: # --------------------------------------------------------------------- Logging
1.729     www       112: {
                    113:     my $logid;
                    114:     sub instructor_log {
1.957     raeburn   115: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    116:         if (($cnum eq '') || ($cdom eq '')) {
                    117:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    118:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    119:         }
1.729     www       120: 	$logid++;
1.957     raeburn   121:         my $now = time();
                    122: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       123: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       124: 				    { $id => {
                    125: 					'exe_uname' => $env{'user.name'},
                    126: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   127: 					'exe_time'  => $now,
1.730     www       128: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    129: 					'delflag'   => $delflag,
                    130: 					'logentry'  => $storehash,
                    131: 					'uname'     => $uname,
                    132: 					'udom'      => $udom,
                    133: 				    }
1.957     raeburn   134: 				  },$cdom,$cnum);
1.729     www       135:     }
                    136: }
1.1       albertel  137: 
1.163     harris41  138: sub logtouch {
                    139:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  140:     unless (-e "$execdir/logs/lonnet.log") {	
                    141: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  142: 	close $fh;
                    143:     }
                    144:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    145:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    146: }
                    147: 
1.1       albertel  148: sub logthis {
                    149:     my $message=shift;
                    150:     my $execdir=$perlvar{'lonDaemons'};
                    151:     my $now=time;
                    152:     my $local=localtime($now);
1.448     albertel  153:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      154: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    155: 	print $fh $logstring;
1.448     albertel  156: 	close($fh);
                    157:     }
1.1       albertel  158:     return 1;
                    159: }
                    160: 
                    161: sub logperm {
                    162:     my $message=shift;
                    163:     my $execdir=$perlvar{'lonDaemons'};
                    164:     my $now=time;
                    165:     my $local=localtime($now);
1.448     albertel  166:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    167: 	print $fh "$now:$message:$local\n";
                    168: 	close($fh);
                    169:     }
1.1       albertel  170:     return 1;
                    171: }
                    172: 
1.850     albertel  173: sub create_connection {
1.853     albertel  174:     my ($hostname,$lonid) = @_;
1.851     albertel  175:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  176: 				     Type    => SOCK_STREAM,
                    177: 				     Timeout => 10);
                    178:     return 0 if (!$client);
1.890     albertel  179:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  180:     my $result = <$client>;
                    181:     chomp($result);
                    182:     return 1 if ($result eq 'done');
                    183:     return 0;
                    184: }
                    185: 
1.983     raeburn   186: sub get_server_timezone {
                    187:     my ($cnum,$cdom) = @_;
                    188:     my $home=&homeserver($cnum,$cdom);
                    189:     if ($home ne 'no_host') {
                    190:         my $cachetime = 24*3600;
                    191:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    192:         if (defined($cached)) {
                    193:             return $timezone;
                    194:         } else {
                    195:             my $timezone = &reply('servertimezone',$home);
                    196:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    197:         }
                    198:     }
                    199: }
1.850     albertel  200: 
1.1       albertel  201: # -------------------------------------------------- Non-critical communication
                    202: sub subreply {
                    203:     my ($cmd,$server)=@_;
1.838     albertel  204:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      205:     #
                    206:     #  With loncnew process trimming, there's a timing hole between lonc server
                    207:     #  process exit and the master server picking up the listen on the AF_UNIX
                    208:     #  socket.  In that time interval, a lock file will exist:
                    209: 
                    210:     my $lockfile=$peerfile.".lock";
                    211:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    212: 	sleep(1);
                    213:     }
                    214:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      215:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      216:     #
1.550     foxr      217:     #   We'll give the connection a few tries before abandoning it.  If
                    218:     #   connection is not possible, we'll con_lost back to the client.
                    219:     #   
                    220:     my $client;
                    221:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    222: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    223: 				      Type    => SOCK_STREAM,
                    224: 				      Timeout => 10);
1.869     albertel  225: 	if ($client) {
1.550     foxr      226: 	    last;		# Connected!
1.850     albertel  227: 	} else {
1.853     albertel  228: 	    &create_connection(&hostname($server),$server);
1.550     foxr      229: 	}
1.850     albertel  230:         sleep(1);		# Try again later if failed connection.
1.550     foxr      231:     }
                    232:     my $answer;
                    233:     if ($client) {
1.704     albertel  234: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      235: 	$answer=<$client>;
                    236: 	if (!$answer) { $answer="con_lost"; }
                    237: 	chomp($answer);
                    238:     } else {
                    239: 	$answer = 'con_lost';	# Failed connection.
                    240:     }
1.1       albertel  241:     return $answer;
                    242: }
                    243: 
                    244: sub reply {
                    245:     my ($cmd,$server)=@_;
1.838     albertel  246:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  247:     my $answer=subreply($cmd,$server);
1.65      www       248:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  249:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       250:                 " $cmd to $server returned $answer</font>");
                    251:     }
1.1       albertel  252:     return $answer;
                    253: }
                    254: 
                    255: # ----------------------------------------------------------- Send USR1 to lonc
                    256: 
                    257: sub reconlonc {
1.891     albertel  258:     my ($lonid) = @_;
                    259:     my $hostname = &hostname($lonid);
                    260:     if ($lonid) {
                    261: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    262: 	if ($hostname && -e $peerfile) {
                    263: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    264: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    265: 					     Type    => SOCK_STREAM,
                    266: 					     Timeout => 10);
                    267: 	    if ($client) {
                    268: 		print $client ("reset_retries\n");
                    269: 		my $answer=<$client>;
                    270: 		#reset just this one.
                    271: 	    }
                    272: 	}
                    273: 	return;
                    274:     }
                    275: 
1.836     www       276:     &logthis("Trying to reconnect lonc");
1.1       albertel  277:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  278:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  279: 	my $loncpid=<$fh>;
                    280:         chomp($loncpid);
                    281:         if (kill 0 => $loncpid) {
                    282: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    283:             kill USR1 => $loncpid;
                    284:             sleep 1;
1.836     www       285:          } else {
1.12      www       286: 	    &logthis(
1.672     albertel  287:                "<font color=\"blue\">WARNING:".
1.12      www       288:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  289:         }
                    290:     } else {
1.836     www       291: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  292:     }
                    293: }
                    294: 
                    295: # ------------------------------------------------------ Critical communication
1.12      www       296: 
1.1       albertel  297: sub critical {
                    298:     my ($cmd,$server)=@_;
1.838     albertel  299:     unless (&hostname($server)) {
1.672     albertel  300:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       301:                " Critical message to unknown server ($server)</font>");
                    302:         return 'no_such_host';
                    303:     }
1.1       albertel  304:     my $answer=reply($cmd,$server);
                    305:     if ($answer eq 'con_lost') {
                    306: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  307: 	my $answer=reply($cmd,$server);
1.1       albertel  308:         if ($answer eq 'con_lost') {
                    309:             my $now=time;
                    310:             my $middlename=$cmd;
1.5       www       311:             $middlename=substr($middlename,0,16);
1.1       albertel  312:             $middlename=~s/\W//g;
                    313:             my $dfilename=
1.305     www       314:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    315:             $dumpcount++;
1.1       albertel  316:             {
1.448     albertel  317: 		my $dfh;
                    318: 		if (open($dfh,">$dfilename")) {
                    319: 		    print $dfh "$cmd\n"; 
                    320: 		    close($dfh);
                    321: 		}
1.1       albertel  322:             }
                    323:             sleep 2;
                    324:             my $wcmd='';
                    325:             {
1.448     albertel  326: 		my $dfh;
                    327: 		if (open($dfh,"<$dfilename")) {
                    328: 		    $wcmd=<$dfh>; 
                    329: 		    close($dfh);
                    330: 		}
1.1       albertel  331:             }
                    332:             chomp($wcmd);
1.7       www       333:             if ($wcmd eq $cmd) {
1.672     albertel  334: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       335:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  336:                 &logperm("D:$server:$cmd");
                    337: 	        return 'con_delayed';
                    338:             } else {
1.672     albertel  339:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       340:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  341:                 &logperm("F:$server:$cmd");
                    342:                 return 'con_failed';
                    343:             }
                    344:         }
                    345:     }
                    346:     return $answer;
1.405     albertel  347: }
                    348: 
1.755     albertel  349: # ------------------------------------------- check if return value is an error
                    350: 
                    351: sub error {
                    352:     my ($result) = @_;
1.756     albertel  353:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  354: 	if ($2 == 2) { return undef; }
                    355: 	return $1;
                    356:     }
                    357:     return undef;
                    358: }
                    359: 
1.783     albertel  360: sub convert_and_load_session_env {
                    361:     my ($lonidsdir,$handle)=@_;
                    362:     my @profile;
                    363:     {
1.917     albertel  364: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    365: 	if (!$opened) {
1.915     albertel  366: 	    return 0;
                    367: 	}
1.783     albertel  368: 	flock($idf,LOCK_SH);
                    369: 	@profile=<$idf>;
                    370: 	close($idf);
                    371:     }
                    372:     my %temp_env;
                    373:     foreach my $line (@profile) {
1.786     albertel  374: 	if ($line !~ m/=/) {
                    375: 	    return 0;
                    376: 	}
1.783     albertel  377: 	chomp($line);
                    378: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    379: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    380:     }
                    381:     unlink("$lonidsdir/$handle.id");
                    382:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    383: 	    0640)) {
                    384: 	%disk_env = %temp_env;
                    385: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    386: 	untie(%disk_env);
                    387:     }
1.786     albertel  388:     return 1;
1.783     albertel  389: }
                    390: 
1.374     www       391: # ------------------------------------------- Transfer profile into environment
1.780     albertel  392: my $env_loaded;
                    393: sub transfer_profile_to_env {
1.788     albertel  394:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    395:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       396: 
1.720     albertel  397:     if (!defined($lonidsdir)) {
                    398: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    399:     }
                    400:     if (!defined($handle)) {
                    401:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    402:     }
                    403: 
1.786     albertel  404:     my $convert;
                    405:     {
1.917     albertel  406:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    407: 	if (!$opened) {
1.915     albertel  408: 	    return;
                    409: 	}
1.786     albertel  410: 	flock($idf,LOCK_SH);
                    411: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    412: 		&GDBM_READER(),0640)) {
                    413: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    414: 	    untie(%disk_env);
                    415: 	} else {
                    416: 	    $convert = 1;
                    417: 	}
                    418:     }
                    419:     if ($convert) {
                    420: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    421: 	    &logthis("Failed to load session, or convert session.");
                    422: 	}
1.374     www       423:     }
1.783     albertel  424: 
1.786     albertel  425:     my %remove;
1.783     albertel  426:     while ( my $envname = each(%env) ) {
1.433     matthew   427:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    428:             if ($time < time-300) {
1.783     albertel  429:                 $remove{$key}++;
1.433     matthew   430:             }
                    431:         }
                    432:     }
1.783     albertel  433: 
1.619     albertel  434:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  435:     $env_loaded=1;
1.783     albertel  436:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   437:         &delenv($expired_key);
1.374     www       438:     }
1.1       albertel  439: }
                    440: 
1.916     albertel  441: # ---------------------------------------------------- Check for valid session 
                    442: sub check_for_valid_session {
                    443:     my ($r) = @_;
                    444:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    445:     my $lonid=$cookies{'lonID'};
                    446:     return undef if (!$lonid);
                    447: 
                    448:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    449:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    450:     return undef if (!-e "$lonidsdir/$handle.id");
                    451: 
1.917     albertel  452:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    453:     return undef if (!$opened);
1.916     albertel  454: 
                    455:     flock($idf,LOCK_SH);
                    456:     my %disk_env;
                    457:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    458: 	    &GDBM_READER(),0640)) {
                    459: 	return undef;	
                    460:     }
                    461: 
                    462:     if (!defined($disk_env{'user.name'})
                    463: 	|| !defined($disk_env{'user.domain'})) {
                    464: 	return undef;
                    465:     }
                    466:     return $handle;
                    467: }
                    468: 
1.830     albertel  469: sub timed_flock {
                    470:     my ($file,$lock_type) = @_;
                    471:     my $failed=0;
                    472:     eval {
                    473: 	local $SIG{__DIE__}='DEFAULT';
                    474: 	local $SIG{ALRM}=sub {
                    475: 	    $failed=1;
                    476: 	    die("failed lock");
                    477: 	};
                    478: 	alarm(13);
                    479: 	flock($file,$lock_type);
                    480: 	alarm(0);
                    481:     };
                    482:     if ($failed) {
                    483: 	return undef;
                    484:     } else {
                    485: 	return 1;
                    486:     }
                    487: }
                    488: 
1.5       www       489: # ---------------------------------------------------------- Append Environment
                    490: 
                    491: sub appenv {
1.949     raeburn   492:     my ($newenv,$roles) = @_;
                    493:     if (ref($newenv) eq 'HASH') {
                    494:         foreach my $key (keys(%{$newenv})) {
                    495:             my $refused = 0;
                    496: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    497:                 $refused = 1;
                    498:                 if (ref($roles) eq 'ARRAY') {
                    499:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    500:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    501:                         $refused = 0;
                    502:                     }
                    503:                 }
                    504:             }
                    505:             if ($refused) {
                    506:                 &logthis("<font color=\"blue\">WARNING: ".
                    507:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    508:                          .'</font>');
                    509: 	        delete($newenv->{$key});
                    510:             } else {
                    511:                 $env{$key}=$newenv->{$key};
                    512:             }
                    513:         }
                    514:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    515:         if ($opened
                    516: 	    && &timed_flock($env_file,LOCK_EX)
                    517: 	    &&
                    518: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    519: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    520: 	    while (my ($key,$value) = each(%{$newenv})) {
                    521: 	        $disk_env{$key} = $value;
                    522: 	    }
                    523: 	    untie(%disk_env);
1.35      www       524:         }
1.191     harris41  525:     }
1.56      www       526:     return 'ok';
                    527: }
                    528: # ----------------------------------------------------- Delete from Environment
                    529: 
                    530: sub delenv {
1.987   ! raeburn   531:     my ($delthis,$regexp) = @_;
1.56      www       532:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  533:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       534:                 "Attempt to delete from environment ".$delthis);
                    535:         return 'error';
                    536:     }
1.917     albertel  537:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    538:     if ($opened
1.915     albertel  539: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  540: 	&&
                    541: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    542: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  543: 	foreach my $key (keys(%disk_env)) {
1.987   ! raeburn   544: 	    if ($regexp) {
        !           545:                 if ($key=~/^$delthis/) {
        !           546:                     delete($env{$key});
        !           547:                     delete($disk_env{$key});
        !           548:                 } 
        !           549:             } else {
        !           550:                 if ($key=~/^\Q$delthis\E/) {
        !           551: 		    delete($env{$key});
        !           552: 		    delete($disk_env{$key});
        !           553: 	        }
        !           554:             }
1.448     albertel  555: 	}
1.783     albertel  556: 	untie(%disk_env);
1.5       www       557:     }
                    558:     return 'ok';
1.369     albertel  559: }
                    560: 
1.790     albertel  561: sub get_env_multiple {
                    562:     my ($name) = @_;
                    563:     my @values;
                    564:     if (defined($env{$name})) {
                    565:         # exists is it an array
                    566:         if (ref($env{$name})) {
                    567:             @values=@{ $env{$name} };
                    568:         } else {
                    569:             $values[0]=$env{$name};
                    570:         }
                    571:     }
                    572:     return(@values);
                    573: }
                    574: 
1.958     www       575: # ------------------------------------------------------------------- Locking
                    576: 
                    577: sub set_lock {
                    578:     my ($text)=@_;
                    579:     $locknum++;
                    580:     my $id=$$.'-'.$locknum;
                    581:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    582:              'session.lock.'.$id => $text});
                    583:     return $id;
                    584: }
                    585: 
                    586: sub get_locks {
                    587:     my $num=0;
                    588:     my %texts=();
                    589:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    590:        if ($lock=~/\w/) {
                    591:           $num++;
                    592:           $texts{$lock}=$env{'session.lock.'.$lock};
                    593:        }
                    594:    }
                    595:    return ($num,%texts);
                    596: }
                    597: 
                    598: sub remove_lock {
                    599:     my ($id)=@_;
                    600:     my $newlocks='';
                    601:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    602:        if (($lock=~/\w/) && ($lock ne $id)) {
                    603:           $newlocks.=','.$lock;
                    604:        }
                    605:     }
                    606:     &appenv({'session.locks' => $newlocks});
                    607:     &delenv('session.lock.'.$id);
                    608: }
                    609: 
                    610: sub remove_all_locks {
                    611:     my $activelocks=$env{'session.locks'};
                    612:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    613:        if ($lock=~/\w/) {
                    614:           &remove_lock($lock);
                    615:        }
                    616:     }
                    617: }
                    618: 
                    619: 
1.369     albertel  620: # ------------------------------------------ Find out current server userload
                    621: sub userload {
                    622:     my $numusers=0;
                    623:     {
                    624: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    625: 	my $filename;
                    626: 	my $curtime=time;
                    627: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  628: 	    next if ($filename eq '.' || $filename eq '..');
                    629: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  630: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  631: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  632: 	}
                    633: 	closedir(LONIDS);
                    634:     }
                    635:     my $userloadpercent=0;
                    636:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    637:     if ($maxuserload) {
1.371     albertel  638: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  639:     }
1.372     albertel  640:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  641:     return $userloadpercent;
1.283     www       642: }
                    643: 
                    644: # ------------------------------------------ Fight off request when overloaded
                    645: 
                    646: sub overloaderror {
                    647:     my ($r,$checkserver)=@_;
                    648:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    649:     my $loadavg;
                    650:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  651:        open(my $loadfile,'/proc/loadavg');
1.283     www       652:        $loadavg=<$loadfile>;
                    653:        $loadavg =~ s/\s.*//g;
1.285     matthew   654:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  655:        close($loadfile);
1.283     www       656:     } else {
                    657:        $loadavg=&reply('load',$checkserver);
                    658:     }
1.285     matthew   659:     my $overload=$loadavg-100;
1.283     www       660:     if ($overload>0) {
1.285     matthew   661: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       662:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       663:         return 413;
1.283     www       664:     }    
                    665:     return '';
1.5       www       666: }
1.1       albertel  667: 
                    668: # ------------------------------ Find server with least workload from spare.tab
1.11      www       669: 
1.1       albertel  670: sub spareserver {
1.670     albertel  671:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  672:     my $spare_server;
1.370     albertel  673:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  674:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    675:                                                      :  $userloadpercent;
                    676:     
                    677:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    678: 	($spare_server, $lowest_load) =
                    679: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    680:     }
                    681: 
                    682:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    683: 
                    684:     if (!$found_server) {
                    685: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    686: 	    ($spare_server, $lowest_load) =
                    687: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    688: 	}
                    689:     }
                    690: 
                    691:     if (!$want_server_name) {
1.968     raeburn   692:         my $protocol = 'http';
                    693:         if ($protocol{$spare_server} eq 'https') {
                    694:             $protocol = $protocol{$spare_server};
                    695:         }
                    696: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  697:     }
                    698:     return $spare_server;
                    699: }
                    700: 
                    701: sub compare_server_load {
                    702:     my ($try_server, $spare_server, $lowest_load) = @_;
                    703: 
                    704:     my $loadans     = &reply('load',    $try_server);
                    705:     my $userloadans = &reply('userload',$try_server);
                    706: 
                    707:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    708: 	next; #didn't get a number from the server
                    709:     }
                    710: 
                    711:     my $load;
                    712:     if ($loadans =~ /\d/) {
                    713: 	if ($userloadans =~ /\d/) {
                    714: 	    #both are numbers, pick the bigger one
                    715: 	    $load = ($loadans > $userloadans) ? $loadans 
                    716: 		                              : $userloadans;
1.411     albertel  717: 	} else {
1.784     albertel  718: 	    $load = $loadans;
1.411     albertel  719: 	}
1.784     albertel  720:     } else {
                    721: 	$load = $userloadans;
                    722:     }
                    723: 
                    724:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    725: 	$spare_server = $try_server;
                    726: 	$lowest_load  = $load;
1.370     albertel  727:     }
1.784     albertel  728:     return ($spare_server,$lowest_load);
1.202     matthew   729: }
1.914     albertel  730: 
                    731: # --------------------------- ask offload servers if user already has a session
                    732: sub find_existing_session {
                    733:     my ($udom,$uname) = @_;
                    734:     foreach my $try_server (@{ $spareid{'primary'} },
                    735: 			    @{ $spareid{'default'} }) {
                    736: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    737:     }
                    738:     return;
                    739: }
                    740: 
                    741: # -------------------------------- ask if server already has a session for user
                    742: sub has_user_session {
                    743:     my ($lonid,$udom,$uname) = @_;
                    744:     my $result = &reply(join(':','userhassession',
                    745: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    746:     return 1 if ($result eq 'ok');
                    747: 
                    748:     return 0;
                    749: }
                    750: 
1.202     matthew   751: # --------------------------------------------- Try to change a user's password
                    752: 
                    753: sub changepass {
1.799     raeburn   754:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   755:     $currentpass = &escape($currentpass);
                    756:     $newpass     = &escape($newpass);
1.799     raeburn   757:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   758: 		       $server);
                    759:     if (! $answer) {
                    760: 	&logthis("No reply on password change request to $server ".
                    761: 		 "by $uname in domain $udom.");
                    762:     } elsif ($answer =~ "^ok") {
                    763:         &logthis("$uname in $udom successfully changed their password ".
                    764: 		 "on $server.");
                    765:     } elsif ($answer =~ "^pwchange_failure") {
                    766: 	&logthis("$uname in $udom was unable to change their password ".
                    767: 		 "on $server.  The action was blocked by either lcpasswd ".
                    768: 		 "or pwchange");
                    769:     } elsif ($answer =~ "^non_authorized") {
                    770:         &logthis("$uname in $udom did not get their password correct when ".
                    771: 		 "attempting to change it on $server.");
                    772:     } elsif ($answer =~ "^auth_mode_error") {
                    773:         &logthis("$uname in $udom attempted to change their password despite ".
                    774: 		 "not being locally or internally authenticated on $server.");
                    775:     } elsif ($answer =~ "^unknown_user") {
                    776:         &logthis("$uname in $udom attempted to change their password ".
                    777: 		 "on $server but were unable to because $server is not ".
                    778: 		 "their home server.");
                    779:     } elsif ($answer =~ "^refused") {
                    780: 	&logthis("$server refused to change $uname in $udom password because ".
                    781: 		 "it was sent an unencrypted request to change the password.");
                    782:     }
                    783:     return $answer;
1.1       albertel  784: }
                    785: 
1.169     harris41  786: # ----------------------- Try to determine user's current authentication scheme
                    787: 
                    788: sub queryauthenticate {
                    789:     my ($uname,$udom)=@_;
1.456     albertel  790:     my $uhome=&homeserver($uname,$udom);
                    791:     if (!$uhome) {
                    792: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    793: 	return 'no_host';
                    794:     }
                    795:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    796:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    797: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  798:     }
1.456     albertel  799:     return $answer;
1.169     harris41  800: }
                    801: 
1.1       albertel  802: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       803: 
1.1       albertel  804: sub authenticate {
1.952     raeburn   805:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  806:     $upass=&escape($upass);
                    807:     $uname= &LONCAPA::clean_username($uname);
1.836     www       808:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   809:     my $newhome;
1.836     www       810:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    811: # Maybe the machine was offline and only re-appeared again recently?
                    812:         &reconlonc();
                    813: # One more
1.952     raeburn   814: 	$uhome=&homeserver($uname,$udom,1);
                    815:         if (($uhome eq 'no_host') && $checkdefauth) {
                    816:             if (defined(&domain($udom,'primary'))) {
                    817:                 $newhome=&domain($udom,'primary');
                    818:             }
                    819:             if ($newhome ne '') {
                    820:                 $uhome = $newhome;
                    821:             }
                    822:         }
1.836     www       823: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    824: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   825: 	    return 'no_host';
                    826:         }
1.1       albertel  827:     }
1.952     raeburn   828:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  829:     if ($answer eq 'authorized') {
1.952     raeburn   830:         if ($newhome) {
                    831:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    832:             return 'no_account_on_host'; 
                    833:         } else {
                    834:             &logthis("User $uname at $udom authorized by $uhome");
                    835:             return $uhome;
                    836:         }
1.471     albertel  837:     }
                    838:     if ($answer eq 'non_authorized') {
                    839: 	&logthis("User $uname at $udom rejected by $uhome");
                    840: 	return 'no_host'; 
1.9       www       841:     }
1.471     albertel  842:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  843:     return 'no_host';
                    844: }
                    845: 
                    846: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       847: 
1.599     albertel  848: my %homecache;
1.1       albertel  849: sub homeserver {
1.230     stredwic  850:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  851:     my $index="$uname:$udom";
1.426     albertel  852: 
1.599     albertel  853:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  854: 
                    855:     my %servers = &get_servers($udom,'library');
                    856:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  857:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  858: 		 exists($badServerCache{$tryserver}));
1.841     albertel  859: 
                    860: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    861: 	if ($answer eq 'found') {
                    862: 	    delete($badServerCache{$tryserver}); 
                    863: 	    return $homecache{$index}=$tryserver;
                    864: 	} elsif ($answer eq 'no_host') {
                    865: 	    $badServerCache{$tryserver}=1;
                    866: 	}
1.1       albertel  867:     }    
                    868:     return 'no_host';
1.70      www       869: }
                    870: 
                    871: # ------------------------------------- Find the usernames behind a list of IDs
                    872: 
                    873: sub idget {
                    874:     my ($udom,@ids)=@_;
                    875:     my %returnhash=();
                    876:     
1.841     albertel  877:     my %servers = &get_servers($udom,'library');
                    878:     foreach my $tryserver (keys(%servers)) {
                    879: 	my $idlist=join('&',@ids);
                    880: 	$idlist=~tr/A-Z/a-z/; 
                    881: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    882: 	my @answer=();
                    883: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    884: 	    @answer=split(/\&/,$reply);
                    885: 	}                    ;
                    886: 	my $i;
                    887: 	for ($i=0;$i<=$#ids;$i++) {
                    888: 	    if ($answer[$i]) {
                    889: 		$returnhash{$ids[$i]}=$answer[$i];
                    890: 	    } 
                    891: 	}
                    892:     } 
1.70      www       893:     return %returnhash;
                    894: }
                    895: 
                    896: # ------------------------------------- Find the IDs behind a list of usernames
                    897: 
                    898: sub idrget {
                    899:     my ($udom,@unames)=@_;
                    900:     my %returnhash=();
1.800     albertel  901:     foreach my $uname (@unames) {
                    902:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  903:     }
1.70      www       904:     return %returnhash;
                    905: }
                    906: 
                    907: # ------------------------------- Store away a list of names and associated IDs
                    908: 
                    909: sub idput {
                    910:     my ($udom,%ids)=@_;
                    911:     my %servers=();
1.800     albertel  912:     foreach my $uname (keys(%ids)) {
                    913: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    914:         my $uhom=&homeserver($uname,$udom);
1.70      www       915:         if ($uhom ne 'no_host') {
1.800     albertel  916:             my $id=&escape($ids{$uname});
1.70      www       917:             $id=~tr/A-Z/a-z/;
1.800     albertel  918:             my $esc_unam=&escape($uname);
1.70      www       919: 	    if ($servers{$uhom}) {
1.800     albertel  920: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       921:             } else {
1.800     albertel  922:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       923:             }
                    924:         }
1.191     harris41  925:     }
1.800     albertel  926:     foreach my $server (keys(%servers)) {
                    927:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  928:     }
1.344     www       929: }
                    930: 
1.806     raeburn   931: # ------------------------------------------- get items from domain db files   
                    932: 
                    933: sub get_dom {
1.860     raeburn   934:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   935:     my $items='';
                    936:     foreach my $item (@$storearr) {
                    937:         $items.=&escape($item).'&';
                    938:     }
                    939:     $items=~s/\&$//;
1.860     raeburn   940:     if (!$udom) {
                    941:         $udom=$env{'user.domain'};
                    942:         if (defined(&domain($udom,'primary'))) {
                    943:             $uhome=&domain($udom,'primary');
                    944:         } else {
1.874     albertel  945:             undef($uhome);
1.860     raeburn   946:         }
                    947:     } else {
                    948:         if (!$uhome) {
                    949:             if (defined(&domain($udom,'primary'))) {
                    950:                 $uhome=&domain($udom,'primary');
                    951:             }
                    952:         }
                    953:     }
                    954:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   955:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   956:         my %returnhash;
1.875     albertel  957:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   958:             return %returnhash;
                    959:         }
1.806     raeburn   960:         my @pairs=split(/\&/,$rep);
                    961:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    962:             return @pairs;
                    963:         }
                    964:         my $i=0;
                    965:         foreach my $item (@$storearr) {
                    966:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    967:             $i++;
                    968:         }
                    969:         return %returnhash;
                    970:     } else {
1.880     banghart  971:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   972:     }
                    973: }
                    974: 
                    975: # -------------------------------------------- put items in domain db files 
                    976: 
                    977: sub put_dom {
1.860     raeburn   978:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    979:     if (!$udom) {
                    980:         $udom=$env{'user.domain'};
                    981:         if (defined(&domain($udom,'primary'))) {
                    982:             $uhome=&domain($udom,'primary');
                    983:         } else {
1.874     albertel  984:             undef($uhome);
1.860     raeburn   985:         }
                    986:     } else {
                    987:         if (!$uhome) {
                    988:             if (defined(&domain($udom,'primary'))) {
                    989:                 $uhome=&domain($udom,'primary');
                    990:             }
                    991:         }
                    992:     } 
                    993:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   994:         my $items='';
                    995:         foreach my $item (keys(%$storehash)) {
                    996:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    997:         }
                    998:         $items=~s/\&$//;
                    999:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1000:     } else {
1.860     raeburn  1001:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1002:     }
                   1003: }
                   1004: 
1.837     raeburn  1005: sub retrieve_inst_usertypes {
                   1006:     my ($udom) = @_;
                   1007:     my (%returnhash,@order);
1.846     albertel 1008:     if (defined(&domain($udom,'primary'))) {
                   1009:         my $uhome=&domain($udom,'primary');
1.837     raeburn  1010:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960     raeburn  1011:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1012:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1013:             return (\%returnhash,\@order);
                   1014:         }
1.837     raeburn  1015:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1016:         my @pairs=split(/\&/,$hashitems);
                   1017:         foreach my $item (@pairs) {
                   1018:             my ($key,$value)=split(/=/,$item,2);
                   1019:             $key = &unescape($key);
                   1020:             next if ($key =~ /^error: 2 /);
                   1021:             $returnhash{$key}=&thaw_unescape($value);
                   1022:         }
                   1023:         my @esc_order = split(/\&/,$orderitems);
                   1024:         foreach my $item (@esc_order) {
                   1025:             push(@order,&unescape($item));
                   1026:         }
                   1027:     } else {
                   1028:         &logthis("get_dom failed - no primary domain server for $udom");
                   1029:     }
                   1030:     return (\%returnhash,\@order);
                   1031: }
                   1032: 
1.868     raeburn  1033: sub is_domainimage {
                   1034:     my ($url) = @_;
                   1035:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1036:         if (&domain($1) ne '') {
                   1037:             return '1';
                   1038:         }
                   1039:     }
                   1040:     return;
                   1041: }
                   1042: 
1.899     raeburn  1043: sub inst_directory_query {
                   1044:     my ($srch) = @_;
                   1045:     my $udom = $srch->{'srchdomain'};
                   1046:     my %results;
                   1047:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1048:     my $outcome;
1.899     raeburn  1049:     if ($homeserver ne '') {
1.904     albertel 1050: 	my $queryid=&reply("querysend:instdirsearch:".
                   1051: 			   &escape($srch->{'srchby'}).':'.
                   1052: 			   &escape($srch->{'srchterm'}).':'.
                   1053: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1054: 	my $host=&hostname($homeserver);
                   1055: 	if ($queryid !~/^\Q$host\E\_/) {
                   1056: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1057: 	    return;
                   1058: 	}
                   1059: 	my $response = &get_query_reply($queryid);
                   1060: 	my $maxtries = 5;
                   1061: 	my $tries = 1;
                   1062: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1063: 	    $response = &get_query_reply($queryid);
                   1064: 	    $tries ++;
                   1065: 	}
                   1066: 
                   1067:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1068:             if ($response eq 'unavailable') {
                   1069:                 $outcome = $response;
                   1070:             } else {
                   1071:                 $outcome = 'ok';
                   1072:                 my @matches = split(/\n/,$response);
                   1073:                 foreach my $match (@matches) {
                   1074:                     my ($key,$value) = split(/=/,$match);
                   1075:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1076:                 }
1.899     raeburn  1077:             }
                   1078:         }
                   1079:     }
1.909     raeburn  1080:     return ($outcome,%results);
1.899     raeburn  1081: }
                   1082: 
                   1083: sub usersearch {
                   1084:     my ($srch) = @_;
                   1085:     my $dom = $srch->{'srchdomain'};
                   1086:     my %results;
                   1087:     my %libserv = &all_library();
                   1088:     my $query = 'usersearch';
                   1089:     foreach my $tryserver (keys(%libserv)) {
                   1090:         if (&host_domain($tryserver) eq $dom) {
                   1091:             my $host=&hostname($tryserver);
                   1092:             my $queryid=
1.911     raeburn  1093:                 &reply("querysend:".&escape($query).':'.
                   1094:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1095:                        &escape($srch->{'srchtype'}).':'.
                   1096:                        &escape($srch->{'srchterm'}),$tryserver);
                   1097:             if ($queryid !~/^\Q$host\E\_/) {
                   1098:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1099:                 next;
1.899     raeburn  1100:             }
                   1101:             my $reply = &get_query_reply($queryid);
                   1102:             my $maxtries = 1;
                   1103:             my $tries = 1;
                   1104:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1105:                 $reply = &get_query_reply($queryid);
                   1106:                 $tries ++;
                   1107:             }
                   1108:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1109:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1110:             } else {
1.911     raeburn  1111:                 my @matches;
                   1112:                 if ($reply =~ /\n/) {
                   1113:                     @matches = split(/\n/,$reply);
                   1114:                 } else {
                   1115:                     @matches = split(/\&/,$reply);
                   1116:                 }
1.899     raeburn  1117:                 foreach my $match (@matches) {
                   1118:                     my ($uname,$udom,%userhash);
1.911     raeburn  1119:                     foreach my $entry (split(/:/,$match)) {
                   1120:                         my ($key,$value) =
                   1121:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1122:                         $userhash{$key} = $value;
                   1123:                         if ($key eq 'username') {
                   1124:                             $uname = $value;
                   1125:                         } elsif ($key eq 'domain') {
                   1126:                             $udom = $value;
1.911     raeburn  1127:                         }
1.899     raeburn  1128:                     }
                   1129:                     $results{$uname.':'.$udom} = \%userhash;
                   1130:                 }
                   1131:             }
                   1132:         }
                   1133:     }
                   1134:     return %results;
                   1135: }
                   1136: 
1.912     raeburn  1137: sub get_instuser {
                   1138:     my ($udom,$uname,$id) = @_;
                   1139:     my $homeserver = &domain($udom,'primary');
                   1140:     my ($outcome,%results);
                   1141:     if ($homeserver ne '') {
                   1142:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1143:                            &escape($id).':'.&escape($udom),$homeserver);
                   1144:         my $host=&hostname($homeserver);
                   1145:         if ($queryid !~/^\Q$host\E\_/) {
                   1146:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1147:             return;
                   1148:         }
                   1149:         my $response = &get_query_reply($queryid);
                   1150:         my $maxtries = 5;
                   1151:         my $tries = 1;
                   1152:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1153:             $response = &get_query_reply($queryid);
                   1154:             $tries ++;
                   1155:         }
                   1156:         if (!&error($response) && $response ne 'refused') {
                   1157:             if ($response eq 'unavailable') {
                   1158:                 $outcome = $response;
                   1159:             } else {
                   1160:                 $outcome = 'ok';
                   1161:                 my @matches = split(/\n/,$response);
                   1162:                 foreach my $match (@matches) {
                   1163:                     my ($key,$value) = split(/=/,$match);
                   1164:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1165:                 }
                   1166:             }
                   1167:         }
                   1168:     }
                   1169:     my %userinfo;
                   1170:     if (ref($results{$uname}) eq 'HASH') {
                   1171:         %userinfo = %{$results{$uname}};
                   1172:     } 
                   1173:     return ($outcome,%userinfo);
                   1174: }
                   1175: 
                   1176: sub inst_rulecheck {
1.923     raeburn  1177:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1178:     my %returnhash;
                   1179:     if ($udom ne '') {
                   1180:         if (ref($rules) eq 'ARRAY') {
                   1181:             @{$rules} = map {&escape($_);} (@{$rules});
                   1182:             my $rulestr = join(':',@{$rules});
                   1183:             my $homeserver=&domain($udom,'primary');
                   1184:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1185:                 my $response;
                   1186:                 if ($item eq 'username') {                
                   1187:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1188:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1189:                                               $homeserver));
1.923     raeburn  1190:                 } elsif ($item eq 'id') {
                   1191:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1192:                                               ':'.&escape($id).':'.$rulestr,
                   1193:                                               $homeserver));
1.945     raeburn  1194:                 } elsif ($item eq 'selfcreate') {
                   1195:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1196:                                                &escape($udom).':'.&escape($uname).
                   1197:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1198:                 }
1.912     raeburn  1199:                 if ($response ne 'refused') {
                   1200:                     my @pairs=split(/\&/,$response);
                   1201:                     foreach my $item (@pairs) {
                   1202:                         my ($key,$value)=split(/=/,$item,2);
                   1203:                         $key = &unescape($key);
                   1204:                         next if ($key =~ /^error: 2 /);
                   1205:                         $returnhash{$key}=&thaw_unescape($value);
                   1206:                     }
                   1207:                 }
                   1208:             }
                   1209:         }
                   1210:     }
                   1211:     return %returnhash;
                   1212: }
                   1213: 
                   1214: sub inst_userrules {
1.923     raeburn  1215:     my ($udom,$check) = @_;
1.912     raeburn  1216:     my (%ruleshash,@ruleorder);
                   1217:     if ($udom ne '') {
                   1218:         my $homeserver=&domain($udom,'primary');
                   1219:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1220:             my $response;
                   1221:             if ($check eq 'id') {
                   1222:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1223:                                  $homeserver);
1.943     raeburn  1224:             } elsif ($check eq 'email') {
                   1225:                 $response=&reply('instemailrules:'.&escape($udom),
                   1226:                                  $homeserver);
1.923     raeburn  1227:             } else {
                   1228:                 $response=&reply('instuserrules:'.&escape($udom),
                   1229:                                  $homeserver);
                   1230:             }
1.912     raeburn  1231:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1232:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1233:                 ($response ne 'no_such_host')) {
                   1234:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1235:                 my @pairs=split(/\&/,$hashitems);
                   1236:                 foreach my $item (@pairs) {
                   1237:                     my ($key,$value)=split(/=/,$item,2);
                   1238:                     $key = &unescape($key);
                   1239:                     next if ($key =~ /^error: 2 /);
                   1240:                     $ruleshash{$key}=&thaw_unescape($value);
                   1241:                 }
                   1242:                 my @esc_order = split(/\&/,$orderitems);
                   1243:                 foreach my $item (@esc_order) {
                   1244:                     push(@ruleorder,&unescape($item));
                   1245:                 }
                   1246:             }
                   1247:         }
                   1248:     }
                   1249:     return (\%ruleshash,\@ruleorder);
                   1250: }
                   1251: 
1.976     raeburn  1252: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1253: 
                   1254: sub get_domain_defaults {
                   1255:     my ($domain) = @_;
                   1256:     my $cachetime = 60*60*24;
                   1257:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1258:     if (defined($cached)) {
                   1259:         if (ref($result) eq 'HASH') {
                   1260:             return %{$result};
                   1261:         }
                   1262:     }
                   1263:     my %domdefaults;
                   1264:     my %domconfig =
1.976     raeburn  1265:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943     raeburn  1266:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1267:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1268:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1269:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1270:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1271:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1272:     } else {
                   1273:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1274:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1275:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1276:     }
1.976     raeburn  1277:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1278:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1279:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1280:         } else {
                   1281:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1282:         } 
                   1283:         my @usertools = ('aboutme','blog','portfolio');
                   1284:         foreach my $item (@usertools) {
                   1285:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1286:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1287:             }
                   1288:         }
                   1289:     }
1.985     raeburn  1290:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
                   1291:         foreach my $item ('official','unofficial') {
                   1292:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1293:         }
                   1294:     }
1.943     raeburn  1295:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1296:                                   $cachetime);
                   1297:     return %domdefaults;
                   1298: }
                   1299: 
1.344     www      1300: # --------------------------------------------------- Assign a key to a student
                   1301: 
                   1302: sub assign_access_key {
1.364     www      1303: #
                   1304: # a valid key looks like uname:udom#comments
                   1305: # comments are being appended
                   1306: #
1.498     www      1307:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1308:     $kdom=
1.620     albertel 1309:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1310:     $knum=
1.620     albertel 1311:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1312:     $cdom=
1.620     albertel 1313:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1314:     $cnum=
1.620     albertel 1315:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1316:     $udom=$env{'user.name'} unless (defined($udom));
                   1317:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1318:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1319:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1320:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1321:                                                   # assigned to this person
                   1322:                                                   # - this should not happen,
1.345     www      1323:                                                   # unless something went wrong
                   1324:                                                   # the first time around
                   1325: # ready to assign
1.364     www      1326:         $logentry=$1.'; '.$logentry;
1.496     www      1327:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1328:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1329: # key now belongs to user
1.346     www      1330: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1331:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1332:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1333:                 return 'ok';
                   1334:             } else {
                   1335:                 return 
                   1336:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1337: 	    }
                   1338:         } else {
                   1339:             return 'error: Could not assign key, try again later.';
                   1340:         }
1.364     www      1341:     } elsif (!$existing{$ckey}) {
1.345     www      1342: # the key does not exist
                   1343: 	return 'error: The key does not exist';
                   1344:     } else {
                   1345: # the key is somebody else's
                   1346: 	return 'error: The key is already in use';
                   1347:     }
1.344     www      1348: }
                   1349: 
1.364     www      1350: # ------------------------------------------ put an additional comment on a key
                   1351: 
                   1352: sub comment_access_key {
                   1353: #
                   1354: # a valid key looks like uname:udom#comments
                   1355: # comments are being appended
                   1356: #
                   1357:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1358:     $cdom=
1.620     albertel 1359:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1360:     $cnum=
1.620     albertel 1361:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1362:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1363:     if ($existing{$ckey}) {
                   1364:         $existing{$ckey}.='; '.$logentry;
                   1365: # ready to assign
1.367     www      1366:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1367:                                                  $cdom,$cnum) eq 'ok') {
                   1368: 	    return 'ok';
                   1369:         } else {
                   1370: 	    return 'error: Count not store comment.';
                   1371:         }
                   1372:     } else {
                   1373: # the key does not exist
                   1374: 	return 'error: The key does not exist';
                   1375:     }
                   1376: }
                   1377: 
1.344     www      1378: # ------------------------------------------------------ Generate a set of keys
                   1379: 
                   1380: sub generate_access_keys {
1.364     www      1381:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1382:     $cdom=
1.620     albertel 1383:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1384:     $cnum=
1.620     albertel 1385:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1386:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1387:     unless (($cdom) && ($cnum)) { return 0; }
                   1388:     if ($number>10000) { return 0; }
                   1389:     sleep(2); # make sure don't get same seed twice
                   1390:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1391:     my $total=0;
                   1392:     for (my $i=1;$i<=$number;$i++) {
                   1393:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1394:                   sprintf("%lx",int(100000*rand)).'-'.
                   1395:                   sprintf("%lx",int(100000*rand));
                   1396:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1397:        $newkey=~s/0/h/g; # and also 0 and O
                   1398:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1399:        if ($existing{$newkey}) {
                   1400:            $i--;
                   1401:        } else {
1.364     www      1402: 	  if (&put('accesskeys',
                   1403:               { $newkey => '# generated '.localtime().
1.620     albertel 1404:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1405:                            '; '.$logentry },
                   1406: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1407:               $total++;
                   1408: 	  }
                   1409:        }
                   1410:     }
1.620     albertel 1411:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1412:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1413:     return $total;
                   1414: }
                   1415: 
                   1416: # ------------------------------------------------------- Validate an accesskey
                   1417: 
                   1418: sub validate_access_key {
                   1419:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1420:     $cdom=
1.620     albertel 1421:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1422:     $cnum=
1.620     albertel 1423:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1424:     $udom=$env{'user.domain'} unless (defined($udom));
                   1425:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1426:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1427:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1428: }
                   1429: 
                   1430: # ------------------------------------- Find the section of student in a course
1.652     albertel 1431: sub devalidate_getsection_cache {
                   1432:     my ($udom,$unam,$courseid)=@_;
                   1433:     my $hashid="$udom:$unam:$courseid";
                   1434:     &devalidate_cache_new('getsection',$hashid);
                   1435: }
1.298     matthew  1436: 
1.815     albertel 1437: sub courseid_to_courseurl {
                   1438:     my ($courseid) = @_;
                   1439:     #already url style courseid
                   1440:     return $courseid if ($courseid =~ m{^/});
                   1441: 
                   1442:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1443: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1444: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1445: 	return "/$cdom/$cnum";
                   1446:     }
                   1447: 
                   1448:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1449:     if (exists($courseinfo{'num'})) {
                   1450: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1451:     }
                   1452: 
                   1453:     return undef;
                   1454: }
                   1455: 
1.298     matthew  1456: sub getsection {
                   1457:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1458:     my $cachetime=1800;
1.551     albertel 1459: 
                   1460:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1461:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1462:     if (defined($cached)) { return $result; }
                   1463: 
1.298     matthew  1464:     my %Pending; 
                   1465:     my %Expired;
                   1466:     #
                   1467:     # Each role can either have not started yet (pending), be active, 
                   1468:     #    or have expired.
                   1469:     #
                   1470:     # If there is an active role, we are done.
                   1471:     #
                   1472:     # If there is more than one role which has not started yet, 
                   1473:     #     choose the one which will start sooner
                   1474:     # If there is one role which has not started yet, return it.
                   1475:     #
                   1476:     # If there is more than one expired role, choose the one which ended last.
                   1477:     # If there is a role which has expired, return it.
                   1478:     #
1.815     albertel 1479:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1480:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1481:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1482:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1483:         my $section=$1;
                   1484:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1485:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1486:         my $now=time;
1.548     albertel 1487:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1488:             $Expired{$end}=$section;
                   1489:             next;
                   1490:         }
1.548     albertel 1491:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1492:             $Pending{$start}=$section;
                   1493:             next;
                   1494:         }
1.599     albertel 1495:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1496:     }
                   1497:     #
                   1498:     # Presumedly there will be few matching roles from the above
                   1499:     # loop and the sorting time will be negligible.
                   1500:     if (scalar(keys(%Pending))) {
                   1501:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1502:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1503:     } 
                   1504:     if (scalar(keys(%Expired))) {
                   1505:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1506:         my $time = pop(@sorted);
1.599     albertel 1507:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1508:     }
1.599     albertel 1509:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1510: }
1.70      www      1511: 
1.599     albertel 1512: sub save_cache {
                   1513:     &purge_remembered();
1.722     albertel 1514:     #&Apache::loncommon::validate_page();
1.620     albertel 1515:     undef(%env);
1.780     albertel 1516:     undef($env_loaded);
1.599     albertel 1517: }
1.452     albertel 1518: 
1.599     albertel 1519: my $to_remember=-1;
                   1520: my %remembered;
                   1521: my %accessed;
                   1522: my $kicks=0;
                   1523: my $hits=0;
1.849     albertel 1524: sub make_key {
                   1525:     my ($name,$id) = @_;
1.872     albertel 1526:     if (length($id) > 65 
                   1527: 	&& length(&escape($id)) > 200) {
                   1528: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1529:     }
1.849     albertel 1530:     return &escape($name.':'.$id);
                   1531: }
                   1532: 
1.599     albertel 1533: sub devalidate_cache_new {
                   1534:     my ($name,$id,$debug) = @_;
                   1535:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1536:     $id=&make_key($name,$id);
1.599     albertel 1537:     $memcache->delete($id);
                   1538:     delete($remembered{$id});
                   1539:     delete($accessed{$id});
                   1540: }
                   1541: 
                   1542: sub is_cached_new {
                   1543:     my ($name,$id,$debug) = @_;
1.849     albertel 1544:     $id=&make_key($name,$id);
1.599     albertel 1545:     if (exists($remembered{$id})) {
                   1546: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1547: 	$accessed{$id}=[&gettimeofday()];
                   1548: 	$hits++;
                   1549: 	return ($remembered{$id},1);
                   1550:     }
                   1551:     my $value = $memcache->get($id);
                   1552:     if (!(defined($value))) {
                   1553: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1554: 	return (undef,undef);
1.416     albertel 1555:     }
1.599     albertel 1556:     if ($value eq '__undef__') {
                   1557: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1558: 	$value=undef;
                   1559:     }
                   1560:     &make_room($id,$value,$debug);
                   1561:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1562:     return ($value,1);
                   1563: }
                   1564: 
                   1565: sub do_cache_new {
                   1566:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1567:     $id=&make_key($name,$id);
1.599     albertel 1568:     my $setvalue=$value;
                   1569:     if (!defined($setvalue)) {
                   1570: 	$setvalue='__undef__';
                   1571:     }
1.623     albertel 1572:     if (!defined($time) ) {
                   1573: 	$time=600;
                   1574:     }
1.599     albertel 1575:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1576:     my $result = $memcache->set($id,$setvalue,$time);
                   1577:     if (! $result) {
1.872     albertel 1578: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1579: 	$memcache->disconnect_all();
1.872     albertel 1580:     }
1.600     albertel 1581:     # need to make a copy of $value
1.919     albertel 1582:     &make_room($id,$value,$debug);
1.599     albertel 1583:     return $value;
                   1584: }
                   1585: 
                   1586: sub make_room {
                   1587:     my ($id,$value,$debug)=@_;
1.919     albertel 1588: 
                   1589:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1590:                                     : $value;
1.599     albertel 1591:     if ($to_remember<0) { return; }
                   1592:     $accessed{$id}=[&gettimeofday()];
                   1593:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1594:     my $to_kick;
                   1595:     my $max_time=0;
                   1596:     foreach my $other (keys(%accessed)) {
                   1597: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1598: 	    $to_kick=$other;
                   1599: 	    $max_time=&tv_interval($accessed{$other});
                   1600: 	}
                   1601:     }
                   1602:     delete($remembered{$to_kick});
                   1603:     delete($accessed{$to_kick});
                   1604:     $kicks++;
                   1605:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1606:     return;
                   1607: }
                   1608: 
1.599     albertel 1609: sub purge_remembered {
1.604     albertel 1610:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1611:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1612:     undef(%remembered);
                   1613:     undef(%accessed);
1.428     albertel 1614: }
1.70      www      1615: # ------------------------------------- Read an entry from a user's environment
                   1616: 
                   1617: sub userenvironment {
                   1618:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1619:     my $items;
                   1620:     foreach my $item (@what) {
                   1621:         $items.=&escape($item).'&';
                   1622:     }
                   1623:     $items=~s/\&$//;
1.70      www      1624:     my %returnhash=();
                   1625:     my @answer=split(/\&/,
1.976     raeburn  1626:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1627:                       &homeserver($unam,$udom)));
                   1628:     my $i;
                   1629:     for ($i=0;$i<=$#what;$i++) {
                   1630: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1631:     }
                   1632:     return %returnhash;
1.1       albertel 1633: }
                   1634: 
1.617     albertel 1635: # ---------------------------------------------------------- Get a studentphoto
                   1636: sub studentphoto {
                   1637:     my ($udom,$unam,$ext) = @_;
                   1638:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1639:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1640:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1641:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1642:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1643:             } else {
                   1644:                 my ($result,$perm_reqd)=
1.707     albertel 1645: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1646:                 if ($result eq 'ok') {
                   1647:                     if (!($perm_reqd eq 'yes')) {
                   1648:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1649:                     }
                   1650:                 }
                   1651:             }
                   1652:         }
                   1653:     } else {
                   1654:         my ($result,$perm_reqd) = 
1.707     albertel 1655: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1656:         if ($result eq 'ok') {
                   1657:             if (!($perm_reqd eq 'yes')) {
                   1658:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1659:             }
                   1660:         }
                   1661:     }
                   1662:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1663: }
                   1664: 
                   1665: sub retrievestudentphoto {
                   1666:     my ($udom,$unam,$ext,$type) = @_;
                   1667:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1668:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1669:     if ($ret eq 'ok') {
                   1670:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1671:         if ($type eq 'thumbnail') {
                   1672:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1673:         }
                   1674:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1675:         return $tokenurl;
                   1676:     } else {
                   1677:         if ($type eq 'thumbnail') {
                   1678:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1679:         } else { 
                   1680:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1681:         }
1.617     albertel 1682:     }
                   1683: }
                   1684: 
1.263     www      1685: # -------------------------------------------------------------------- New chat
                   1686: 
                   1687: sub chatsend {
1.724     raeburn  1688:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1689:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1690:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1691:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1692:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1693: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1694: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1695: }
                   1696: 
                   1697: # ------------------------------------------ Find current version of a resource
                   1698: 
                   1699: sub getversion {
                   1700:     my $fname=&clutter(shift);
                   1701:     unless ($fname=~/^\/res\//) { return -1; }
                   1702:     return &currentversion(&filelocation('',$fname));
                   1703: }
                   1704: 
                   1705: sub currentversion {
                   1706:     my $fname=shift;
1.599     albertel 1707:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1708:     if (defined($cached)) { return $result; }
1.292     www      1709:     my $author=$fname;
                   1710:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1711:     my ($udom,$uname)=split(/\//,$author);
                   1712:     my $home=homeserver($uname,$udom);
                   1713:     if ($home eq 'no_host') { 
                   1714:         return -1; 
                   1715:     }
                   1716:     my $answer=reply("currentversion:$fname",$home);
                   1717:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1718: 	return -1;
                   1719:     }
1.599     albertel 1720:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1721: }
                   1722: 
1.1       albertel 1723: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1724: 
1.1       albertel 1725: sub subscribe {
                   1726:     my $fname=shift;
1.761     raeburn  1727:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1728:     $fname=~s/[\n\r]//g;
1.1       albertel 1729:     my $author=$fname;
                   1730:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1731:     my ($udom,$uname)=split(/\//,$author);
                   1732:     my $home=homeserver($uname,$udom);
1.335     albertel 1733:     if ($home eq 'no_host') {
                   1734:         return 'not_found';
1.1       albertel 1735:     }
                   1736:     my $answer=reply("sub:$fname",$home);
1.64      www      1737:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1738: 	$answer.=' by '.$home;
                   1739:     }
1.1       albertel 1740:     return $answer;
                   1741: }
                   1742:     
1.8       www      1743: # -------------------------------------------------------------- Replicate file
                   1744: 
                   1745: sub repcopy {
                   1746:     my $filename=shift;
1.23      www      1747:     $filename=~s/\/+/\//g;
1.607     raeburn  1748:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1749:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1750:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1751: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1752: 	return &repcopy_userfile($filename);
                   1753:     }
1.532     albertel 1754:     $filename=~s/[\n\r]//g;
1.8       www      1755:     my $transname="$filename.in.transfer";
1.828     www      1756: # FIXME: this should flock
1.607     raeburn  1757:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1758:     my $remoteurl=subscribe($filename);
1.64      www      1759:     if ($remoteurl =~ /^con_lost by/) {
                   1760: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1761:            return 'unavailable';
1.8       www      1762:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1763: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1764: 	   return 'not_found';
1.64      www      1765:     } elsif ($remoteurl =~ /^rejected by/) {
                   1766: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1767:            return 'forbidden';
1.20      www      1768:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1769:            return 'ok';
1.8       www      1770:     } else {
1.290     www      1771:         my $author=$filename;
                   1772:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1773:         my ($udom,$uname)=split(/\//,$author);
                   1774:         my $home=homeserver($uname,$udom);
                   1775:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1776:            my @parts=split(/\//,$filename);
                   1777:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1778:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1779:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1780: 	       return 'bad_request';
1.8       www      1781:            }
                   1782:            my $count;
                   1783:            for ($count=5;$count<$#parts;$count++) {
                   1784:                $path.="/$parts[$count]";
                   1785:                if ((-e $path)!=1) {
                   1786: 		   mkdir($path,0777);
                   1787:                }
                   1788:            }
                   1789:            my $ua=new LWP::UserAgent;
                   1790:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1791:            my $response=$ua->request($request,$transname);
                   1792:            if ($response->is_error()) {
                   1793: 	       unlink($transname);
                   1794:                my $message=$response->status_line;
1.672     albertel 1795:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1796:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1797:                return 'unavailable';
1.8       www      1798:            } else {
1.16      www      1799: 	       if ($remoteurl!~/\.meta$/) {
                   1800:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1801:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1802:                   if ($mresponse->is_error()) {
                   1803: 		      unlink($filename.'.meta');
                   1804:                       &logthis(
1.672     albertel 1805:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1806:                   }
                   1807: 	       }
1.8       www      1808:                rename($transname,$filename);
1.607     raeburn  1809:                return 'ok';
1.8       www      1810:            }
1.290     www      1811:        }
1.8       www      1812:     }
1.330     www      1813: }
                   1814: 
                   1815: # ------------------------------------------------ Get server side include body
                   1816: sub ssi_body {
1.381     albertel 1817:     my ($filelink,%form)=@_;
1.606     matthew  1818:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1819:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1820:     }
1.953     www      1821:     my $output='';
                   1822:     my $response;
1.980     raeburn  1823:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1824:        ($output,$response)=&externalssi($filelink);
1.953     www      1825:     } else {
                   1826:        ($output,$response)=&ssi($filelink,%form);
                   1827:     }
1.778     albertel 1828:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1829:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1830:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1831:     if (wantarray) {
                   1832:         return ($output, $response);
                   1833:     } else {
                   1834:         return $output;
                   1835:     }
1.8       www      1836: }
                   1837: 
1.15      www      1838: # --------------------------------------------------------- Server Side Include
                   1839: 
1.782     albertel 1840: sub absolute_url {
                   1841:     my ($host_name) = @_;
                   1842:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1843:     if ($host_name eq '') {
                   1844: 	$host_name = $ENV{'SERVER_NAME'};
                   1845:     }
                   1846:     return $protocol.$host_name;
                   1847: }
                   1848: 
1.942     foxr     1849: #
                   1850: #   Server side include.
                   1851: # Parameters:
                   1852: #  fn     Possibly encrypted resource name/id.
                   1853: #  form   Hash that describes how the rendering should be done
                   1854: #         and other things.
1.944     foxr     1855: # Returns:
1.950     raeburn  1856: #   Scalar context: The content of the response.
                   1857: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1858: #     
1.15      www      1859: sub ssi {
                   1860: 
1.944     foxr     1861:     my ($fn,%form)=@_;
1.15      www      1862:     my $ua=new LWP::UserAgent;
1.23      www      1863:     my $request;
1.711     albertel 1864: 
                   1865:     $form{'no_update_last_known'}=1;
1.895     albertel 1866:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1867:     if (%form) {
1.782     albertel 1868:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1869:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1870:     } else {
1.782     albertel 1871:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1872:     }
                   1873: 
1.15      www      1874:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1875:     my $response=$ua->request($request);
                   1876: 
1.944     foxr     1877:     if (wantarray) {
                   1878: 	return ($response->content, $response);
                   1879:     } else {
                   1880: 	return $response->content;
1.942     foxr     1881:     }
1.324     www      1882: }
                   1883: 
                   1884: sub externalssi {
                   1885:     my ($url)=@_;
                   1886:     my $ua=new LWP::UserAgent;
                   1887:     my $request=new HTTP::Request('GET',$url);
                   1888:     my $response=$ua->request($request);
1.954     raeburn  1889:     if (wantarray) {
                   1890:         return ($response->content, $response);
                   1891:     } else {
                   1892:         return $response->content;
                   1893:     }
1.15      www      1894: }
1.254     www      1895: 
1.492     albertel 1896: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1897: 
                   1898: sub allowuploaded {
                   1899:     my ($srcurl,$url)=@_;
                   1900:     $url=&clutter(&declutter($url));
                   1901:     my $dir=$url;
                   1902:     $dir=~s/\/[^\/]+$//;
                   1903:     my %httpref=();
                   1904:     my $httpurl=&hreflocation('',$url);
                   1905:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1906:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1907: }
1.477     raeburn  1908: 
1.478     albertel 1909: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1910: # input: action, courseID, current domain, intended
1.637     raeburn  1911: #        path to file, source of file, instruction to parse file for objects,
                   1912: #        ref to hash for embedded objects,
                   1913: #        ref to hash for codebase of java objects.
                   1914: #
1.485     raeburn  1915: # output: url to file (if action was uploaddoc), 
                   1916: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1917: #
1.478     albertel 1918: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1919: # course.
1.477     raeburn  1920: #
1.478     albertel 1921: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1922: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1923: #          course's home server.
1.477     raeburn  1924: #
1.478     albertel 1925: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1926: #          be copied from $source (current location) to 
                   1927: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1928: #         and will then be copied to
                   1929: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1930: #         course's home server.
1.485     raeburn  1931: #
1.481     raeburn  1932: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1933: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1934: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1935: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1936: #         in course's home server.
1.637     raeburn  1937: #
1.477     raeburn  1938: 
                   1939: sub process_coursefile {
1.638     albertel 1940:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1941:     my $fetchresult;
1.638     albertel 1942:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1943:     if ($action eq 'propagate') {
1.638     albertel 1944:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1945: 			     $home);
1.481     raeburn  1946:     } else {
1.477     raeburn  1947:         my $fpath = '';
                   1948:         my $fname = $file;
1.478     albertel 1949:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1950:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1951:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1952:         if ($action eq 'copy') {
                   1953:             if ($source eq '') {
                   1954:                 $fetchresult = 'no source file';
                   1955:                 return $fetchresult;
                   1956:             } else {
                   1957:                 my $destination = $filepath.'/'.$fname;
                   1958:                 rename($source,$destination);
                   1959:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1960:                                  $home);
1.481     raeburn  1961:             }
                   1962:         } elsif ($action eq 'uploaddoc') {
                   1963:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1964:             print $fh $env{'form.'.$source};
1.481     raeburn  1965:             close($fh);
1.637     raeburn  1966:             if ($parser eq 'parse') {
1.961     raeburn  1967:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1968:                 unless ($parse_result eq 'ok') {
                   1969:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1970:                 }
                   1971:             }
1.477     raeburn  1972:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1973:                                  $home);
1.481     raeburn  1974:             if ($fetchresult eq 'ok') {
                   1975:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1976:             } else {
                   1977:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1978:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1979:                 return '/adm/notfound.html';
                   1980:             }
1.477     raeburn  1981:         }
                   1982:     }
1.485     raeburn  1983:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1984:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1985:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1986:     }
                   1987:     return $fetchresult;
                   1988: }
                   1989: 
1.637     raeburn  1990: sub build_filepath {
                   1991:     my ($fpath) = @_;
                   1992:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1993:     unless ($fpath eq '') {
                   1994:         my @parts=split('/',$fpath);
                   1995:         foreach my $part (@parts) {
                   1996:             $filepath.= '/'.$part;
                   1997:             if ((-e $filepath)!=1) {
                   1998:                 mkdir($filepath,0777);
                   1999:             }
                   2000:         }
                   2001:     }
                   2002:     return $filepath;
                   2003: }
                   2004: 
                   2005: sub store_edited_file {
1.638     albertel 2006:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2007:     my $file = $primary_url;
                   2008:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2009:     my $fpath = '';
                   2010:     my $fname = $file;
                   2011:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2012:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2013:     my $filepath = &build_filepath($fpath);
                   2014:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2015:     print $fh $content;
                   2016:     close($fh);
1.638     albertel 2017:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2018:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2019: 			  $home);
1.637     raeburn  2020:     if ($$fetchresult eq 'ok') {
                   2021:         return '/uploaded/'.$fpath.'/'.$fname;
                   2022:     } else {
1.638     albertel 2023:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2024: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2025:         return '/adm/notfound.html';
                   2026:     }
                   2027: }
                   2028: 
1.531     albertel 2029: sub clean_filename {
1.831     albertel 2030:     my ($fname,$args)=@_;
1.315     www      2031: # Replace Windows backslashes by forward slashes
1.257     www      2032:     $fname=~s/\\/\//g;
1.831     albertel 2033:     if (!$args->{'keep_path'}) {
                   2034:         # Get rid of everything but the actual filename
                   2035: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2036:     }
1.315     www      2037: # Replace spaces by underscores
                   2038:     $fname=~s/\s+/\_/g;
                   2039: # Replace all other weird characters by nothing
1.831     albertel 2040:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2041: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2042: # numbers
                   2043:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2044:     return $fname;
                   2045: }
1.984     neumanie 2046: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2047: sub resizeImage {
                   2048: 	my($img_url) = @_;	
                   2049: 	my $ima = Image::Magick->new;                       
                   2050:         $ima->Read($img_url);
                   2051: 	if($ima->Get('width') > 400)
                   2052: 	{
                   2053: 		my $factor = $ima->Get('width')/400;
                   2054:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2055: 	}
                   2056: 	if($ima->Get('height') > 500)
                   2057:         {
                   2058:         	my $factor = $ima->Get('height')/500;
                   2059:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2060:         } 
                   2061: 		
                   2062: 	$ima->Write($img_url);
                   2063: }
1.531     albertel 2064: 
1.977     amueller 2065: #Wrapper function for userphotoupload
                   2066: sub userphotoupload
                   2067: {
                   2068: 	my($formname,$subdir) = @_;
                   2069: 	$upload_photo_form = 1;
                   2070: 	return &userfileupload($formname,undef,$subdir);
                   2071: }
                   2072: 
1.608     albertel 2073: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2074: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2075: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2076: #        $coursedoc - if true up to the current course
                   2077: #                     if false
                   2078: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2079: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2080: #        $allfiles - reference to hash for embedded objects
                   2081: #        $codebase - reference to hash for codebase of java objects
                   2082: #        $desuname - username for permanent storage of uploaded file
                   2083: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2084: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2085: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2086: # 
1.686     albertel 2087: # output: url of file in userspace, or error: <message> 
                   2088: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2089: 
                   2090: 
1.531     albertel 2091: sub userfileupload {
1.860     raeburn  2092:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2093:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2094:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2095:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2096:     $fname=&clean_filename($fname);
1.315     www      2097: # See if there is anything left
1.257     www      2098:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2099:     chop($env{'form.'.$formname});
1.523     raeburn  2100:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2101:         my $now = time;
                   2102:         my $filepath = 'tmp/helprequests/'.$now;
                   2103:         my @parts=split(/\//,$filepath);
                   2104:         my $fullpath = $perlvar{'lonDaemons'};
                   2105:         for (my $i=0;$i<@parts;$i++) {
                   2106:             $fullpath .= '/'.$parts[$i];
                   2107:             if ((-e $fullpath)!=1) {
                   2108:                 mkdir($fullpath,0777);
                   2109:             }
                   2110:         }
                   2111:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2112:         print $fh $env{'form.'.$formname};
1.523     raeburn  2113:         close($fh);
1.741     raeburn  2114:         return $fullpath.'/'.$fname;
                   2115:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2116:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2117:                        '_'.$env{'user.domain'}.'/pending';
                   2118:         my @parts=split(/\//,$filepath);
                   2119:         my $fullpath = $perlvar{'lonDaemons'};
                   2120:         for (my $i=0;$i<@parts;$i++) {
                   2121:             $fullpath .= '/'.$parts[$i];
                   2122:             if ((-e $fullpath)!=1) {
                   2123:                 mkdir($fullpath,0777);
                   2124:             }
                   2125:         }
                   2126:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2127:         print $fh $env{'form.'.$formname};
                   2128:         close($fh);
                   2129:         return $fullpath.'/'.$fname;
1.523     raeburn  2130:     }
1.719     banghart 2131:     
1.258     www      2132: # Create the directory if not present
1.493     albertel 2133:     $fname="$subdir/$fname";
1.259     www      2134:     if ($coursedoc) {
1.638     albertel 2135: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2136: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2137:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2138:             return &finishuserfileupload($docuname,$docudom,
                   2139: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2140: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2141:         } else {
1.620     albertel 2142:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2143:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2144: 				       $fname,$formname,$parser,
                   2145: 				       $allfiles,$codebase);
1.481     raeburn  2146:         }
1.719     banghart 2147:     } elsif (defined($destuname)) {
                   2148:         my $docuname=$destuname;
                   2149:         my $docudom=$destudom;
1.860     raeburn  2150: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2151: 				     $parser,$allfiles,$codebase,
                   2152:                                      $thumbwidth,$thumbheight);
1.719     banghart 2153:         
1.259     www      2154:     } else {
1.638     albertel 2155:         my $docuname=$env{'user.name'};
                   2156:         my $docudom=$env{'user.domain'};
1.714     raeburn  2157:         if (exists($env{'form.group'})) {
                   2158:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2159:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2160:         }
1.860     raeburn  2161: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2162: 				     $parser,$allfiles,$codebase,
                   2163:                                      $thumbwidth,$thumbheight);
1.259     www      2164:     }
1.271     www      2165: }
                   2166: 
                   2167: sub finishuserfileupload {
1.860     raeburn  2168:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2169:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2170:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2171:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2172:   
1.860     raeburn  2173:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2174:     $file=$fname;
                   2175:     if ($fname=~m|/|) {
                   2176:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2177: 	$path.=$fnamepath.'/';
                   2178:     }
1.259     www      2179:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2180:     my $count;
                   2181:     for ($count=4;$count<=$#parts;$count++) {
                   2182:         $filepath.="/$parts[$count]";
                   2183:         if ((-e $filepath)!=1) {
                   2184: 	    mkdir($filepath,0777);
                   2185:         }
                   2186:     }
1.984     neumanie 2187: 
1.258     www      2188: # Save the file
                   2189:     {
1.701     albertel 2190: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2191: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2192: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2193: 	    return '/adm/notfound.html';
                   2194: 	}
                   2195: 	if (!print FH ($env{'form.'.$formname})) {
                   2196: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2197: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2198: 	    return '/adm/notfound.html';
                   2199: 	}
1.570     albertel 2200: 	close(FH);
1.977     amueller 2201: 	if($upload_photo_form==1)
                   2202: 	{
1.984     neumanie 2203: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2204: 		$upload_photo_form = 0;
                   2205: 	}
1.258     www      2206:     }
1.637     raeburn  2207:     if ($parser eq 'parse') {
1.961     raeburn  2208:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2209: 						   $codebase);
1.637     raeburn  2210:         unless ($parse_result eq 'ok') {
1.638     albertel 2211:             &logthis('Failed to parse '.$filepath.$file.
                   2212: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2213:         }
                   2214:     }
1.860     raeburn  2215:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2216:         my $input = $filepath.'/'.$file;
                   2217:         my $output = $filepath.'/'.'tn-'.$file;
                   2218:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2219:         system("convert -sample $thumbsize $input $output");
                   2220:         if (-e $filepath.'/'.'tn-'.$file) {
                   2221:             $fetchthumb  = 1; 
                   2222:         }
                   2223:     }
1.858     raeburn  2224:  
1.259     www      2225: # Notify homeserver to grep it
                   2226: #
1.984     neumanie 2227:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2228:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2229:     if ($fetchresult eq 'ok') {
1.860     raeburn  2230:         if ($fetchthumb) {
                   2231:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2232:             if ($thumbresult ne 'ok') {
                   2233:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2234:                          $docuhome.': '.$thumbresult);
                   2235:             }
                   2236:         }
1.259     www      2237: #
1.258     www      2238: # Return the URL to it
1.494     albertel 2239:         return '/uploaded/'.$path.$file;
1.263     www      2240:     } else {
1.494     albertel 2241:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2242: 		 ': '.$fetchresult);
1.263     www      2243:         return '/adm/notfound.html';
1.858     raeburn  2244:     }
1.493     albertel 2245: }
                   2246: 
1.637     raeburn  2247: sub extract_embedded_items {
1.961     raeburn  2248:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2249:     my @state = ();
                   2250:     my %javafiles = (
                   2251:                       codebase => '',
                   2252:                       code => '',
                   2253:                       archive => ''
                   2254:                     );
                   2255:     my %mediafiles = (
                   2256:                       src => '',
                   2257:                       movie => '',
                   2258:                      );
1.648     raeburn  2259:     my $p;
                   2260:     if ($content) {
                   2261:         $p = HTML::LCParser->new($content);
                   2262:     } else {
1.961     raeburn  2263:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2264:     }
1.641     albertel 2265:     while (my $t=$p->get_token()) {
1.640     albertel 2266: 	if ($t->[0] eq 'S') {
                   2267: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2268: 	    push(@state, $tagname);
1.648     raeburn  2269:             if (lc($tagname) eq 'allow') {
                   2270:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2271:             }
1.640     albertel 2272: 	    if (lc($tagname) eq 'img') {
                   2273: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2274: 	    }
1.886     albertel 2275: 	    if (lc($tagname) eq 'a') {
                   2276: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2277: 	    }
1.645     raeburn  2278:             if (lc($tagname) eq 'script') {
                   2279:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2280:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2281:                 } else {
                   2282:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2283:                 }
                   2284:             }
                   2285:             if (lc($tagname) eq 'link') {
                   2286:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2287:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2288:                 }
                   2289:             }
1.640     albertel 2290: 	    if (lc($tagname) eq 'object' ||
                   2291: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2292: 		foreach my $item (keys(%javafiles)) {
                   2293: 		    $javafiles{$item} = '';
                   2294: 		}
                   2295: 	    }
                   2296: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2297: 		my $name = lc($attr->{'name'});
                   2298: 		foreach my $item (keys(%javafiles)) {
                   2299: 		    if ($name eq $item) {
                   2300: 			$javafiles{$item} = $attr->{'value'};
                   2301: 			last;
                   2302: 		    }
                   2303: 		}
                   2304: 		foreach my $item (keys(%mediafiles)) {
                   2305: 		    if ($name eq $item) {
                   2306: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2307: 			last;
                   2308: 		    }
                   2309: 		}
                   2310: 	    }
                   2311: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2312: 		foreach my $item (keys(%javafiles)) {
                   2313: 		    if ($attr->{$item}) {
                   2314: 			$javafiles{$item} = $attr->{$item};
                   2315: 			last;
                   2316: 		    }
                   2317: 		}
                   2318: 		foreach my $item (keys(%mediafiles)) {
                   2319: 		    if ($attr->{$item}) {
                   2320: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2321: 			last;
                   2322: 		    }
                   2323: 		}
                   2324: 	    }
                   2325: 	} elsif ($t->[0] eq 'E') {
                   2326: 	    my ($tagname) = ($t->[1]);
                   2327: 	    if ($javafiles{'codebase'} ne '') {
                   2328: 		$javafiles{'codebase'} .= '/';
                   2329: 	    }  
                   2330: 	    if (lc($tagname) eq 'applet' ||
                   2331: 		lc($tagname) eq 'object' ||
                   2332: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2333: 		) {
                   2334: 		foreach my $item (keys(%javafiles)) {
                   2335: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2336: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2337: 			&add_filetype($allfiles,$file,$item);
                   2338: 		    }
                   2339: 		}
                   2340: 	    } 
                   2341: 	    pop @state;
                   2342: 	}
                   2343:     }
1.637     raeburn  2344:     return 'ok';
                   2345: }
                   2346: 
1.639     albertel 2347: sub add_filetype {
                   2348:     my ($allfiles,$file,$type)=@_;
                   2349:     if (exists($allfiles->{$file})) {
                   2350: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2351: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2352: 	}
                   2353:     } else {
                   2354: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2355:     }
                   2356: }
                   2357: 
1.493     albertel 2358: sub removeuploadedurl {
1.984     neumanie 2359:     my ($url)=@_;	
                   2360:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2361:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2362: }
                   2363: 
                   2364: sub removeuserfile {
                   2365:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2366:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2367:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2368:     if ($result eq 'ok') {	
1.798     raeburn  2369:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2370:             my $metafile = $fname.'.meta';
                   2371:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2372: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2373:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2374:             my $sqlresult = 
1.823     albertel 2375:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2376:                                         'portfolio_metadata',$group,
                   2377:                                         'delete');
1.798     raeburn  2378:         }
                   2379:     }
                   2380:     return $result;
1.257     www      2381: }
1.15      www      2382: 
1.530     albertel 2383: sub mkdiruserfile {
                   2384:     my ($docuname,$docudom,$dir)=@_;
                   2385:     my $home=&homeserver($docuname,$docudom);
                   2386:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2387: }
                   2388: 
1.531     albertel 2389: sub renameuserfile {
                   2390:     my ($docuname,$docudom,$old,$new)=@_;
                   2391:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2392:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2393:                         &escape("$old").':'.&escape("$new"),$home);
                   2394:     if ($result eq 'ok') {
                   2395:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2396:             my $oldmeta = $old.'.meta';
                   2397:             my $newmeta = $new.'.meta';
                   2398:             my $metaresult = 
                   2399:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2400: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2401:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2402:             my $sqlresult = 
1.823     albertel 2403:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2404:                                         'portfolio_metadata',$group,
                   2405:                                         'delete');
1.798     raeburn  2406:         }
                   2407:     }
                   2408:     return $result;
1.531     albertel 2409: }
                   2410: 
1.14      www      2411: # ------------------------------------------------------------------------- Log
                   2412: 
                   2413: sub log {
                   2414:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2415:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2416: }
                   2417: 
                   2418: # ------------------------------------------------------------------ Course Log
1.352     www      2419: #
                   2420: # This routine flushes several buffers of non-mission-critical nature
                   2421: #
1.157     www      2422: 
                   2423: sub flushcourselogs {
1.352     www      2424:     &logthis('Flushing log buffers');
                   2425: #
                   2426: # course logs
                   2427: # This is a log of all transactions in a course, which can be used
                   2428: # for data mining purposes
                   2429: #
                   2430: # It also collects the courseid database, which lists last transaction
                   2431: # times and course titles for all courseids
                   2432: #
                   2433:     my %courseidbuffer=();
1.921     raeburn  2434:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2435:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2436: 		          &escape($courselogs{$crsid}),
                   2437: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2438: 	    delete $courselogs{$crsid};
                   2439:         } else {
                   2440:             &logthis('Failed to flush log buffer for '.$crsid);
                   2441:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2442:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2443:                         " exceeded maximum size, deleting.</font>");
                   2444:                delete $courselogs{$crsid};
                   2445:             }
1.352     www      2446:         }
1.920     raeburn  2447:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2448:             'description' => $coursedescrbuf{$crsid},
                   2449:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2450:             'type'        => $coursetypebuf{$crsid},
                   2451:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2452:         };
1.191     harris41 2453:     }
1.352     www      2454: #
                   2455: # Write course id database (reverse lookup) to homeserver of courses 
                   2456: # Is used in pickcourse
                   2457: #
1.840     albertel 2458:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2459:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2460:                                     $courseidbuffer{$crs_home},
                   2461:                                     $crs_home,'timeonly');
1.352     www      2462:     }
                   2463: #
                   2464: # File accesses
                   2465: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2466: #
1.449     matthew  2467:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2468:         if ($entry =~ /___count$/) {
                   2469:             my ($dom,$name);
1.807     albertel 2470:             ($dom,$name,undef)=
1.811     albertel 2471: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2472:             if (! defined($dom) || $dom eq '' || 
                   2473:                 ! defined($name) || $name eq '') {
1.620     albertel 2474:                 my $cid = $env{'request.course.id'};
                   2475:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2476:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2477:             }
1.450     matthew  2478:             my $value = $accesshash{$entry};
                   2479:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2480:             my %temphash=($url => $value);
1.449     matthew  2481:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2482:             if ($result eq 'ok') {
                   2483:                 delete $accesshash{$entry};
                   2484:             } elsif ($result eq 'unknown_cmd') {
                   2485:                 # Target server has old code running on it.
1.450     matthew  2486:                 my %temphash=($entry => $value);
1.449     matthew  2487:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2488:                     delete $accesshash{$entry};
                   2489:                 }
                   2490:             }
                   2491:         } else {
1.811     albertel 2492:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2493:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2494:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2495:                 delete $accesshash{$entry};
                   2496:             }
1.185     www      2497:         }
1.191     harris41 2498:     }
1.352     www      2499: #
                   2500: # Roles
                   2501: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2502: #
1.800     albertel 2503:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2504:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2505: 	    split(/\:/,$entry);
                   2506:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2507:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2508:                 $rudom,$runame) eq 'ok') {
                   2509: 	    delete $userrolehash{$entry};
                   2510:         }
                   2511:     }
1.662     raeburn  2512: #
                   2513: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2514: #
                   2515:     my %domrolebuffer = ();
                   2516:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2517:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2518:         if ($domrolebuffer{$rudom}) {
                   2519:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2520:                       '='.&escape($domainrolehash{$entry});
                   2521:         } else {
                   2522:             $domrolebuffer{$rudom}.=&escape($entry).
                   2523:                       '='.&escape($domainrolehash{$entry});
                   2524:         }
                   2525:         delete $domainrolehash{$entry};
                   2526:     }
                   2527:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2528: 	my %servers = &get_servers($dom,'library');
                   2529: 	foreach my $tryserver (keys(%servers)) {
                   2530: 	    unless (&reply('domroleput:'.$dom.':'.
                   2531: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2532: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2533: 	    }
1.662     raeburn  2534:         }
                   2535:     }
1.186     www      2536:     $dumpcount++;
1.157     www      2537: }
                   2538: 
                   2539: sub courselog {
                   2540:     my $what=shift;
1.158     www      2541:     $what=time.':'.$what;
1.620     albertel 2542:     unless ($env{'request.course.id'}) { return ''; }
                   2543:     $coursedombuf{$env{'request.course.id'}}=
                   2544:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2545:     $coursenumbuf{$env{'request.course.id'}}=
                   2546:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2547:     $coursehombuf{$env{'request.course.id'}}=
                   2548:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2549:     $coursedescrbuf{$env{'request.course.id'}}=
                   2550:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2551:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2552:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2553:     $courseownerbuf{$env{'request.course.id'}}=
                   2554:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2555:     $coursetypebuf{$env{'request.course.id'}}=
                   2556:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2557:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2558: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2559:     } else {
1.620     albertel 2560: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2561:     }
1.620     albertel 2562:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2563: 	&flushcourselogs();
                   2564:     }
1.158     www      2565: }
                   2566: 
                   2567: sub courseacclog {
                   2568:     my $fnsymb=shift;
1.620     albertel 2569:     unless ($env{'request.course.id'}) { return ''; }
                   2570:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2571:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2572:         $what.=':POST';
1.583     matthew  2573:         # FIXME: Probably ought to escape things....
1.800     albertel 2574: 	foreach my $key (keys(%env)) {
                   2575:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2576:                 my $formitem = $1;
                   2577:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2578:                     $what.=':'.$formitem.'='.$env{$key};
                   2579:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2580:                     $what.=':'.$formitem.'='.$env{$key};
                   2581:                 }
1.158     www      2582:             }
1.191     harris41 2583:         }
1.583     matthew  2584:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2585:         # FIXME: We should not be depending on a form parameter that someone
                   2586:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2587:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2588:             $what.= ':POST';
                   2589:             # FIXME: Probably ought to escape things....
                   2590:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2591:                                  'crsdiscuss') {
1.620     albertel 2592:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2593:             }
                   2594:         }
1.158     www      2595:     }
                   2596:     &courselog($what);
1.149     www      2597: }
                   2598: 
1.185     www      2599: sub countacc {
                   2600:     my $url=&declutter(shift);
1.458     matthew  2601:     return if (! defined($url) || $url eq '');
1.620     albertel 2602:     unless ($env{'request.course.id'}) { return ''; }
                   2603:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2604:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2605:     $accesshash{$key}++;
1.185     www      2606: }
1.349     www      2607: 
1.361     www      2608: sub linklog {
                   2609:     my ($from,$to)=@_;
                   2610:     $from=&declutter($from);
                   2611:     $to=&declutter($to);
                   2612:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2613:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2614: }
                   2615:   
1.349     www      2616: sub userrolelog {
                   2617:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2618:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2619:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2620:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2621:         ($trole=~/^ta/)) {
1.350     www      2622:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2623:        $userrolehash
                   2624:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2625:                     =$tend.':'.$tstart;
1.662     raeburn  2626:     }
1.898     albertel 2627:     if (($env{'request.role'} =~ /dc\./) &&
                   2628: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2629: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2630: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2631:        $userrolehash
                   2632:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2633:                     =$tend.':'.$tstart;
                   2634:     }
1.662     raeburn  2635:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2636:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2637:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2638:         ($trole=~/^sc/)) {
                   2639:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2640:        $domainrolehash
                   2641:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2642:                     = $tend.':'.$tstart;
                   2643:     }
1.351     www      2644: }
                   2645: 
1.957     raeburn  2646: sub courserolelog {
                   2647:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2648:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2649:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2650:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2651:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2652:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2653:             my $cdom = $1;
                   2654:             my $cnum = $2;
                   2655:             my $sec = $3;
                   2656:             my $namespace = 'rolelog';
                   2657:             my %storehash = (
                   2658:                                role    => $trole,
                   2659:                                start   => $tstart,
                   2660:                                end     => $tend,
                   2661:                                selfenroll => $selfenroll,
                   2662:                                context    => $context,
                   2663:                             );
                   2664:             if ($trole eq 'gr') {
                   2665:                 $namespace = 'groupslog';
                   2666:                 $storehash{'group'} = $sec;
                   2667:             } else {
                   2668:                 $storehash{'section'} = $sec;
                   2669:             }
                   2670:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2671:         }
                   2672:     }
                   2673:     return;
                   2674: }
                   2675: 
1.351     www      2676: sub get_course_adv_roles {
1.948     raeburn  2677:     my ($cid,$codes) = @_;
1.620     albertel 2678:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2679:     my %coursehash=&coursedescription($cid);
1.470     www      2680:     my %nothide=();
1.800     albertel 2681:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2682:         if ($user !~ /:/) {
                   2683: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2684:         } else {
                   2685:             $nothide{$user}=1;
                   2686:         }
1.470     www      2687:     }
1.351     www      2688:     my %returnhash=();
                   2689:     my %dumphash=
                   2690:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2691:     my $now=time;
1.800     albertel 2692:     foreach my $entry (keys %dumphash) {
                   2693: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2694:         if (($tstart) && ($tstart<0)) { next; }
                   2695:         if (($tend) && ($tend<$now)) { next; }
                   2696:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2697:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2698: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2699: 	if ((&privileged($username,$domain)) && 
                   2700: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2701: 	if ($role eq 'cr') { next; }
1.948     raeburn  2702:         if ($codes) {
                   2703:             if ($section) { $role .= ':'.$section; }
                   2704:             if ($returnhash{$role}) {
                   2705:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2706:             } else {
                   2707:                 $returnhash{$role}=$username.':'.$domain;
                   2708:             }
1.351     www      2709:         } else {
1.948     raeburn  2710:             my $key=&plaintext($role);
1.973     bisitz   2711:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2712:             if ($returnhash{$key}) {
                   2713: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2714:             } else {
                   2715:                 $returnhash{$key}=$username.':'.$domain;
                   2716:             }
1.351     www      2717:         }
1.948     raeburn  2718:     }
1.400     www      2719:     return %returnhash;
                   2720: }
                   2721: 
                   2722: sub get_my_roles {
1.937     raeburn  2723:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2724:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2725:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2726:     my (%dumphash,%nothide);
1.858     raeburn  2727:     if ($context eq 'userroles') { 
                   2728:         %dumphash = &dump('roles',$udom,$uname);
                   2729:     } else {
                   2730:         %dumphash=
1.400     www      2731:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2732:         if ($hidepriv) {
                   2733:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2734:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2735:                 if ($user !~ /:/) {
                   2736:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2737:                 } else {
                   2738:                     $nothide{$user} = 1;
                   2739:                 }
                   2740:             }
                   2741:         }
1.858     raeburn  2742:     }
1.400     www      2743:     my %returnhash=();
                   2744:     my $now=time;
1.800     albertel 2745:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2746:         my ($role,$tend,$tstart);
                   2747:         if ($context eq 'userroles') {
                   2748: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2749:         } else {
                   2750:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2751:         }
1.400     www      2752:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2753:         my $status = 'active';
1.939     raeburn  2754:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2755:             $status = 'previous';
                   2756:         } 
                   2757:         if (($tstart) && ($now<$tstart)) {
                   2758:             $status = 'future';
                   2759:         }
                   2760:         if (ref($types) eq 'ARRAY') {
                   2761:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2762:                 next;
                   2763:             } 
                   2764:         } else {
                   2765:             if ($status ne 'active') {
                   2766:                 next;
                   2767:             }
                   2768:         }
1.867     raeburn  2769:         my ($rolecode,$username,$domain,$section,$area);
                   2770:         if ($context eq 'userroles') {
                   2771:             ($area,$rolecode) = split(/_/,$entry);
                   2772:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2773:         } else {
                   2774:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2775:         }
1.832     raeburn  2776:         if (ref($roledoms) eq 'ARRAY') {
                   2777:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2778:                 next;
                   2779:             }
                   2780:         }
                   2781:         if (ref($roles) eq 'ARRAY') {
                   2782:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2783:                 if ($role =~ /^cr\//) {
                   2784:                     if (!grep(/^cr$/,@{$roles})) {
                   2785:                         next;
                   2786:                     }
                   2787:                 } else {
                   2788:                     next;
                   2789:                 }
1.832     raeburn  2790:             }
1.867     raeburn  2791:         }
1.937     raeburn  2792:         if ($hidepriv) {
                   2793:             if ((&privileged($username,$domain)) &&
                   2794:                 (!$nothide{$username.':'.$domain})) { 
                   2795:                 next;
                   2796:             }
                   2797:         }
1.933     raeburn  2798:         if ($withsec) {
                   2799:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2800:                 $tstart.':'.$tend;
                   2801:         } else {
                   2802:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2803:         }
1.832     raeburn  2804:     }
1.373     www      2805:     return %returnhash;
1.399     www      2806: }
                   2807: 
                   2808: # ----------------------------------------------------- Frontpage Announcements
                   2809: #
                   2810: #
                   2811: 
                   2812: sub postannounce {
                   2813:     my ($server,$text)=@_;
1.844     albertel 2814:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2815:     unless ($text=~/\w/) { $text=''; }
                   2816:     return &reply('setannounce:'.&escape($text),$server);
                   2817: }
                   2818: 
                   2819: sub getannounce {
1.448     albertel 2820: 
                   2821:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2822: 	my $announcement='';
1.800     albertel 2823: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2824: 	close($fh);
1.399     www      2825: 	if ($announcement=~/\w/) { 
                   2826: 	    return 
                   2827:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2828:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2829: 	} else {
                   2830: 	    return '';
                   2831: 	}
                   2832:     } else {
                   2833: 	return '';
                   2834:     }
1.351     www      2835: }
1.353     www      2836: 
                   2837: # ---------------------------------------------------------- Course ID routines
                   2838: # Deal with domain's nohist_courseid.db files
                   2839: #
                   2840: 
                   2841: sub courseidput {
1.921     raeburn  2842:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2843:     my $outcome;
                   2844:     if ($caller eq 'timeonly') {
                   2845:         my $cids = '';
                   2846:         foreach my $item (keys(%$storehash)) {
                   2847:             $cids.=&escape($item).'&';
                   2848:         }
                   2849:         $cids=~s/\&$//;
                   2850:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2851:                           $coursehome);       
                   2852:     } else {
                   2853:         my $items = '';
                   2854:         foreach my $item (keys(%$storehash)) {
                   2855:             $items.= &escape($item).'='.
                   2856:                      &freeze_escape($$storehash{$item}).'&';
                   2857:         }
                   2858:         $items=~s/\&$//;
                   2859:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2860:                           $coursehome);
1.918     raeburn  2861:     }
                   2862:     if ($outcome eq 'unknown_cmd') {
                   2863:         my $what;
                   2864:         foreach my $cid (keys(%$storehash)) {
                   2865:             $what .= &escape($cid).'=';
1.921     raeburn  2866:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2867:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2868:             }
                   2869:             $what =~ s/\:$/&/;
                   2870:         }
                   2871:         $what =~ s/\&$//;  
                   2872:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2873:     } else {
                   2874:         return $outcome;
                   2875:     }
1.353     www      2876: }
                   2877: 
                   2878: sub courseiddump {
1.921     raeburn  2879:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2880:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2881:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2882:     my $as_hash = 1;
                   2883:     my %returnhash;
                   2884:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2885:     my %libserv = &all_library();
                   2886:     foreach my $tryserver (keys(%libserv)) {
                   2887:         if ( (  $hostidflag == 1 
                   2888: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2889: 	     || (!defined($hostidflag)) ) {
                   2890: 
1.918     raeburn  2891: 	    if (($domfilter eq '') ||
                   2892: 		(&host_domain($tryserver) eq $domfilter)) {
                   2893:                 my $rep = 
                   2894:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2895:                          $sincefilter.':'.&escape($descfilter).':'.
                   2896:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2897:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2898:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2899:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2900:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2901:                 my @pairs=split(/\&/,$rep);
                   2902:                 foreach my $item (@pairs) {
                   2903:                     my ($key,$value)=split(/\=/,$item,2);
                   2904:                     $key = &unescape($key);
                   2905:                     next if ($key =~ /^error: 2 /);
                   2906:                     my $result = &thaw_unescape($value);
                   2907:                     if (ref($result) eq 'HASH') {
                   2908:                         $returnhash{$key}=$result;
                   2909:                     } else {
1.921     raeburn  2910:                         my @responses = split(/:/,$value);
                   2911:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2912:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2913:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2914:                         }
                   2915:                     } 
1.353     www      2916:                 }
                   2917:             }
                   2918:         }
                   2919:     }
                   2920:     return %returnhash;
                   2921: }
                   2922: 
1.658     raeburn  2923: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2924: 
                   2925: sub dcmailput {
1.685     raeburn  2926:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2927:     my $status = &Apache::lonnet::critical(
1.740     www      2928:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2929:        &escape($message),$server);
1.662     raeburn  2930:     return $status;
                   2931: }
                   2932: 
1.658     raeburn  2933: sub dcmaildump {
                   2934:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2935:     my %returnhash=();
1.846     albertel 2936: 
                   2937:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2938:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2939:                                                          &escape($enddate).':';
                   2940: 	my @esc_senders=map { &escape($_)} @$senders;
                   2941: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2942: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2943:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2944:             if (($key) && ($value)) {
                   2945:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2946:             }
                   2947:         }
                   2948:     }
                   2949:     return %returnhash;
                   2950: }
1.662     raeburn  2951: # ---------------------------------------------------------- Domain roles
                   2952: 
                   2953: sub get_domain_roles {
                   2954:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2955:     if (undef($startdate) || $startdate eq '') {
                   2956:         $startdate = '.';
                   2957:     }
                   2958:     if (undef($enddate) || $enddate eq '') {
                   2959:         $enddate = '.';
                   2960:     }
1.922     raeburn  2961:     my $rolelist;
                   2962:     if (ref($roles) eq 'ARRAY') {
                   2963:         $rolelist = join(':',@{$roles});
                   2964:     }
1.662     raeburn  2965:     my %personnel = ();
1.841     albertel 2966: 
                   2967:     my %servers = &get_servers($dom,'library');
                   2968:     foreach my $tryserver (keys(%servers)) {
                   2969: 	%{$personnel{$tryserver}}=();
                   2970: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2971: 					    &escape($startdate).':'.
                   2972: 					    &escape($enddate).':'.
                   2973: 					    &escape($rolelist), $tryserver))) {
                   2974: 	    my ($key,$value) = split(/\=/,$line,2);
                   2975: 	    if (($key) && ($value)) {
                   2976: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2977: 	    }
                   2978: 	}
1.662     raeburn  2979:     }
                   2980:     return %personnel;
                   2981: }
1.658     raeburn  2982: 
1.149     www      2983: # ----------------------------------------------------------- Check out an item
                   2984: 
1.504     albertel 2985: sub get_first_access {
                   2986:     my ($type,$argsymb)=@_;
1.790     albertel 2987:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2988:     if ($argsymb) { $symb=$argsymb; }
                   2989:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2990:     if ($type eq 'course') {
                   2991: 	$res='course';
                   2992:     } elsif ($type eq 'map') {
1.588     albertel 2993: 	$res=&symbread($map);
                   2994:     } else {
                   2995: 	$res=$symb;
                   2996:     }
                   2997:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2998:     return $times{"$courseid\0$res"};
1.504     albertel 2999: }
                   3000: 
                   3001: sub set_first_access {
                   3002:     my ($type)=@_;
1.790     albertel 3003:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3004:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3005:     if ($type eq 'course') {
                   3006: 	$res='course';
                   3007:     } elsif ($type eq 'map') {
1.588     albertel 3008: 	$res=&symbread($map);
                   3009:     } else {
                   3010: 	$res=$symb;
                   3011:     }
                   3012:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3013:     if (!$firstaccess) {
1.588     albertel 3014: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3015:     }
                   3016:     return 'already_set';
1.504     albertel 3017: }
                   3018: 
1.149     www      3019: sub checkout {
                   3020:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3021:     my $now=time;
                   3022:     my $lonhost=$perlvar{'lonHostID'};
                   3023:     my $infostr=&escape(
1.234     www      3024:                  'CHECKOUTTOKEN&'.
1.149     www      3025:                  $tuname.'&'.
                   3026:                  $tudom.'&'.
                   3027:                  $tcrsid.'&'.
                   3028:                  $symb.'&'.
                   3029: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3030:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3031:     if ($token=~/^error\:/) { 
1.672     albertel 3032:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3033:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3034:                  "</font>");
                   3035:         return ''; 
                   3036:     }
                   3037: 
1.149     www      3038:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3039:     $token=~tr/a-z/A-Z/;
                   3040: 
1.153     www      3041:     my %infohash=('resource.0.outtoken' => $token,
                   3042:                   'resource.0.checkouttime' => $now,
                   3043:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3044: 
                   3045:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3046:        return '';
1.151     www      3047:     } else {
1.672     albertel 3048:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3049:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3050:                  "</font>");
1.149     www      3051:     }    
                   3052: 
                   3053:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3054:                          &escape('Checkout '.$infostr.' - '.
                   3055:                                                  $token)) ne 'ok') {
                   3056: 	return '';
1.151     www      3057:     } else {
1.672     albertel 3058:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3059:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3060:                  "</font>");
1.149     www      3061:     }
1.151     www      3062:     return $token;
1.149     www      3063: }
                   3064: 
                   3065: # ------------------------------------------------------------ Check in an item
                   3066: 
                   3067: sub checkin {
                   3068:     my $token=shift;
1.150     www      3069:     my $now=time;
                   3070:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3071:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3072:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3073:     $dtoken=~s/\W/\_/g;
1.234     www      3074:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3075:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3076: 
1.154     www      3077:     unless (($tuname) && ($tudom)) {
                   3078:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3079:         return '';
                   3080:     }
                   3081:     
                   3082:     unless (&allowed('mgr',$tcrsid)) {
                   3083:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3084:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3085:         return '';
                   3086:     }
                   3087: 
1.153     www      3088:     my %infohash=('resource.0.intoken' => $token,
                   3089:                   'resource.0.checkintime' => $now,
                   3090:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3091: 
                   3092:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3093:        return '';
                   3094:     }    
                   3095: 
                   3096:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3097:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3098: 	return '';
                   3099:     }
                   3100: 
                   3101:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3102: }
                   3103: 
                   3104: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3105: 
                   3106: sub expirespread {
                   3107:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3108:     my $cid=$env{'request.course.id'}; 
1.110     www      3109:     if ($cid) {
                   3110:        my $now=time;
                   3111:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3112:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3113:                             $env{'course.'.$cid.'.num'}.
1.110     www      3114: 	        	    ':nohist_expirationdates:'.
                   3115:                             &escape($key).'='.$now,
1.620     albertel 3116:                             $env{'course.'.$cid.'.home'})
1.110     www      3117:     }
                   3118:     return 'ok';
1.14      www      3119: }
                   3120: 
1.109     www      3121: # ----------------------------------------------------- Devalidate Spreadsheets
                   3122: 
                   3123: sub devalidate {
1.325     www      3124:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3125:     my $cid=$env{'request.course.id'}; 
1.109     www      3126:     if ($cid) {
1.391     matthew  3127:         # delete the stored spreadsheets for
                   3128:         # - the student level sheet of this user in course's homespace
                   3129:         # - the assessment level sheet for this resource 
                   3130:         #   for this user in user's homespace
1.553     albertel 3131: 	# - current conditional state info
1.325     www      3132: 	my $key=$uname.':'.$udom.':';
1.109     www      3133:         my $status=
1.299     matthew  3134: 	    &del('nohist_calculatedsheets',
1.391     matthew  3135: 		 [$key.'studentcalc:'],
1.620     albertel 3136: 		 $env{'course.'.$cid.'.domain'},
                   3137: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3138: 		.' '.
                   3139: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3140: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3141:         unless ($status eq 'ok ok') {
                   3142:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3143:                     $uname.' at '.$udom.' for '.
1.109     www      3144: 		    $symb.': '.$status);
1.133     albertel 3145:         }
1.553     albertel 3146: 	&delenv('user.state.'.$cid);
1.109     www      3147:     }
                   3148: }
                   3149: 
1.265     albertel 3150: sub get_scalar {
                   3151:     my ($string,$end) = @_;
                   3152:     my $value;
                   3153:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3154: 	$value = $1;
                   3155:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3156: 	$value = $1;
                   3157:     }
                   3158:     return &unescape($value);
                   3159: }
                   3160: 
                   3161: sub array2str {
                   3162:   my (@array) = @_;
                   3163:   my $result=&arrayref2str(\@array);
                   3164:   $result=~s/^__ARRAY_REF__//;
                   3165:   $result=~s/__END_ARRAY_REF__$//;
                   3166:   return $result;
                   3167: }
                   3168: 
1.204     albertel 3169: sub arrayref2str {
                   3170:   my ($arrayref) = @_;
1.265     albertel 3171:   my $result='__ARRAY_REF__';
1.204     albertel 3172:   foreach my $elem (@$arrayref) {
1.265     albertel 3173:     if(ref($elem) eq 'ARRAY') {
                   3174:       $result.=&arrayref2str($elem).'&';
                   3175:     } elsif(ref($elem) eq 'HASH') {
                   3176:       $result.=&hashref2str($elem).'&';
                   3177:     } elsif(ref($elem)) {
                   3178:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3179:     } else {
                   3180:       $result.=&escape($elem).'&';
                   3181:     }
                   3182:   }
                   3183:   $result=~s/\&$//;
1.265     albertel 3184:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3185:   return $result;
                   3186: }
                   3187: 
1.168     albertel 3188: sub hash2str {
1.204     albertel 3189:   my (%hash) = @_;
                   3190:   my $result=&hashref2str(\%hash);
1.265     albertel 3191:   $result=~s/^__HASH_REF__//;
                   3192:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3193:   return $result;
                   3194: }
                   3195: 
                   3196: sub hashref2str {
                   3197:   my ($hashref)=@_;
1.265     albertel 3198:   my $result='__HASH_REF__';
1.800     albertel 3199:   foreach my $key (sort(keys(%$hashref))) {
                   3200:     if (ref($key) eq 'ARRAY') {
                   3201:       $result.=&arrayref2str($key).'=';
                   3202:     } elsif (ref($key) eq 'HASH') {
                   3203:       $result.=&hashref2str($key).'=';
                   3204:     } elsif (ref($key)) {
1.265     albertel 3205:       $result.='=';
1.800     albertel 3206:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3207:     } else {
1.800     albertel 3208: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3209:     }
                   3210: 
1.800     albertel 3211:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3212:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3213:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3214:       $result.=&hashref2str($hashref->{$key}).'&';
                   3215:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3216:        $result.='&';
1.800     albertel 3217:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3218:     } else {
1.800     albertel 3219:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3220:     }
                   3221:   }
1.168     albertel 3222:   $result=~s/\&$//;
1.265     albertel 3223:   $result .= '__END_HASH_REF__';
1.168     albertel 3224:   return $result;
                   3225: }
                   3226: 
                   3227: sub str2hash {
1.265     albertel 3228:     my ($string)=@_;
                   3229:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3230:     return %$hash;
                   3231: }
                   3232: 
                   3233: sub str2hashref {
1.168     albertel 3234:   my ($string) = @_;
1.265     albertel 3235: 
                   3236:   my %hash;
                   3237: 
                   3238:   if($string !~ /^__HASH_REF__/) {
                   3239:       if (! ($string eq '' || !defined($string))) {
                   3240: 	  $hash{'error'}='Not hash reference';
                   3241:       }
                   3242:       return (\%hash, $string);
                   3243:   }
                   3244: 
                   3245:   $string =~ s/^__HASH_REF__//;
                   3246: 
                   3247:   while($string !~ /^__END_HASH_REF__/) {
                   3248:       #key
                   3249:       my $key='';
                   3250:       if($string =~ /^__HASH_REF__/) {
                   3251:           ($key, $string)=&str2hashref($string);
                   3252:           if(defined($key->{'error'})) {
                   3253:               $hash{'error'}='Bad data';
                   3254:               return (\%hash, $string);
                   3255:           }
                   3256:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3257:           ($key, $string)=&str2arrayref($string);
                   3258:           if($key->[0] eq 'Array reference error') {
                   3259:               $hash{'error'}='Bad data';
                   3260:               return (\%hash, $string);
                   3261:           }
                   3262:       } else {
                   3263:           $string =~ s/^(.*?)=//;
1.267     albertel 3264: 	  $key=&unescape($1);
1.265     albertel 3265:       }
                   3266:       $string =~ s/^=//;
                   3267: 
                   3268:       #value
                   3269:       my $value='';
                   3270:       if($string =~ /^__HASH_REF__/) {
                   3271:           ($value, $string)=&str2hashref($string);
                   3272:           if(defined($value->{'error'})) {
                   3273:               $hash{'error'}='Bad data';
                   3274:               return (\%hash, $string);
                   3275:           }
                   3276:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3277:           ($value, $string)=&str2arrayref($string);
                   3278:           if($value->[0] eq 'Array reference error') {
                   3279:               $hash{'error'}='Bad data';
                   3280:               return (\%hash, $string);
                   3281:           }
                   3282:       } else {
                   3283: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3284:       }
                   3285:       $string =~ s/^&//;
                   3286: 
                   3287:       $hash{$key}=$value;
1.204     albertel 3288:   }
1.265     albertel 3289: 
                   3290:   $string =~ s/^__END_HASH_REF__//;
                   3291: 
                   3292:   return (\%hash, $string);
1.204     albertel 3293: }
                   3294: 
                   3295: sub str2array {
1.265     albertel 3296:     my ($string)=@_;
                   3297:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3298:     return @$array;
                   3299: }
                   3300: 
                   3301: sub str2arrayref {
1.204     albertel 3302:   my ($string) = @_;
1.265     albertel 3303:   my @array;
                   3304: 
                   3305:   if($string !~ /^__ARRAY_REF__/) {
                   3306:       if (! ($string eq '' || !defined($string))) {
                   3307: 	  $array[0]='Array reference error';
                   3308:       }
                   3309:       return (\@array, $string);
                   3310:   }
                   3311: 
                   3312:   $string =~ s/^__ARRAY_REF__//;
                   3313: 
                   3314:   while($string !~ /^__END_ARRAY_REF__/) {
                   3315:       my $value='';
                   3316:       if($string =~ /^__HASH_REF__/) {
                   3317:           ($value, $string)=&str2hashref($string);
                   3318:           if(defined($value->{'error'})) {
                   3319:               $array[0] ='Array reference error';
                   3320:               return (\@array, $string);
                   3321:           }
                   3322:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3323:           ($value, $string)=&str2arrayref($string);
                   3324:           if($value->[0] eq 'Array reference error') {
                   3325:               $array[0] ='Array reference error';
                   3326:               return (\@array, $string);
                   3327:           }
                   3328:       } else {
                   3329: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3330:       }
                   3331:       $string =~ s/^&//;
                   3332: 
                   3333:       push(@array, $value);
1.191     harris41 3334:   }
1.265     albertel 3335: 
                   3336:   $string =~ s/^__END_ARRAY_REF__//;
                   3337: 
                   3338:   return (\@array, $string);
1.168     albertel 3339: }
                   3340: 
1.167     albertel 3341: # -------------------------------------------------------------------Temp Store
                   3342: 
1.168     albertel 3343: sub tmpreset {
                   3344:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3345:   if (!$symb) {
                   3346:     $symb=&symbread();
1.620     albertel 3347:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3348:   }
                   3349:   $symb=escape($symb);
                   3350: 
1.620     albertel 3351:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3352:   $namespace=~s/\//\_/g;
                   3353:   $namespace=~s/\W//g;
                   3354: 
1.620     albertel 3355:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3356:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3357:   if ($domain eq 'public' && $stuname eq 'public') {
                   3358:       $stuname=$ENV{'REMOTE_ADDR'};
                   3359:   }
1.168     albertel 3360:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3361:   my %hash;
                   3362:   if (tie(%hash,'GDBM_File',
                   3363: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3364: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3365:     foreach my $key (keys %hash) {
1.180     albertel 3366:       if ($key=~ /:$symb/) {
1.168     albertel 3367: 	delete($hash{$key});
                   3368:       }
                   3369:     }
                   3370:   }
                   3371: }
                   3372: 
1.167     albertel 3373: sub tmpstore {
1.168     albertel 3374:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3375: 
                   3376:   if (!$symb) {
                   3377:     $symb=&symbread();
1.620     albertel 3378:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3379:   }
                   3380:   $symb=escape($symb);
                   3381: 
                   3382:   if (!$namespace) {
                   3383:     # I don't think we would ever want to store this for a course.
                   3384:     # it seems this will only be used if we don't have a course.
1.620     albertel 3385:     #$namespace=$env{'request.course.id'};
1.168     albertel 3386:     #if (!$namespace) {
1.620     albertel 3387:       $namespace=$env{'request.state'};
1.168     albertel 3388:     #}
                   3389:   }
                   3390:   $namespace=~s/\//\_/g;
                   3391:   $namespace=~s/\W//g;
1.620     albertel 3392:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3393:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3394:   if ($domain eq 'public' && $stuname eq 'public') {
                   3395:       $stuname=$ENV{'REMOTE_ADDR'};
                   3396:   }
1.168     albertel 3397:   my $now=time;
                   3398:   my %hash;
                   3399:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3400:   if (tie(%hash,'GDBM_File',
                   3401: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3402: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3403:     $hash{"version:$symb"}++;
                   3404:     my $version=$hash{"version:$symb"};
                   3405:     my $allkeys=''; 
                   3406:     foreach my $key (keys(%$storehash)) {
                   3407:       $allkeys.=$key.':';
1.591     albertel 3408:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3409:     }
                   3410:     $hash{"$version:$symb:timestamp"}=$now;
                   3411:     $allkeys.='timestamp';
                   3412:     $hash{"$version:keys:$symb"}=$allkeys;
                   3413:     if (untie(%hash)) {
                   3414:       return 'ok';
                   3415:     } else {
                   3416:       return "error:$!";
                   3417:     }
                   3418:   } else {
                   3419:     return "error:$!";
                   3420:   }
                   3421: }
1.167     albertel 3422: 
1.168     albertel 3423: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3424: 
1.168     albertel 3425: sub tmprestore {
                   3426:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3427: 
1.168     albertel 3428:   if (!$symb) {
                   3429:     $symb=&symbread();
1.620     albertel 3430:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3431:   }
                   3432:   $symb=escape($symb);
                   3433: 
1.620     albertel 3434:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3435: 
1.620     albertel 3436:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3437:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3438:   if ($domain eq 'public' && $stuname eq 'public') {
                   3439:       $stuname=$ENV{'REMOTE_ADDR'};
                   3440:   }
1.168     albertel 3441:   my %returnhash;
                   3442:   $namespace=~s/\//\_/g;
                   3443:   $namespace=~s/\W//g;
                   3444:   my %hash;
                   3445:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3446:   if (tie(%hash,'GDBM_File',
                   3447: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3448: 	  &GDBM_READER(),0640)) {
1.168     albertel 3449:     my $version=$hash{"version:$symb"};
                   3450:     $returnhash{'version'}=$version;
                   3451:     my $scope;
                   3452:     for ($scope=1;$scope<=$version;$scope++) {
                   3453:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3454:       my @keys=split(/:/,$vkeys);
                   3455:       my $key;
                   3456:       $returnhash{"$scope:keys"}=$vkeys;
                   3457:       foreach $key (@keys) {
1.591     albertel 3458: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3459: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3460:       }
                   3461:     }
1.168     albertel 3462:     if (!(untie(%hash))) {
                   3463:       return "error:$!";
                   3464:     }
                   3465:   } else {
                   3466:     return "error:$!";
                   3467:   }
                   3468:   return %returnhash;
1.167     albertel 3469: }
                   3470: 
1.9       www      3471: # ----------------------------------------------------------------------- Store
                   3472: 
                   3473: sub store {
1.124     www      3474:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3475:     my $home='';
                   3476: 
1.168     albertel 3477:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3478: 
1.213     www      3479:     $symb=&symbclean($symb);
1.122     albertel 3480:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3481: 
1.620     albertel 3482:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3483:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3484: 
                   3485:     &devalidate($symb,$stuname,$domain);
1.109     www      3486: 
                   3487:     $symb=escape($symb);
1.187     www      3488:     if (!$namespace) { 
1.620     albertel 3489:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3490:           return ''; 
                   3491:        } 
                   3492:     }
1.620     albertel 3493:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3494: 
                   3495:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3496:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3497: 
1.12      www      3498:     my $namevalue='';
1.800     albertel 3499:     foreach my $key (keys(%$storehash)) {
                   3500:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3501:     }
1.12      www      3502:     $namevalue=~s/\&$//;
1.187     www      3503:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3504:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3505: }
                   3506: 
1.47      www      3507: # -------------------------------------------------------------- Critical Store
                   3508: 
                   3509: sub cstore {
1.124     www      3510:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3511:     my $home='';
                   3512: 
1.168     albertel 3513:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3514: 
1.213     www      3515:     $symb=&symbclean($symb);
1.122     albertel 3516:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3517: 
1.620     albertel 3518:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3519:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3520: 
                   3521:     &devalidate($symb,$stuname,$domain);
1.109     www      3522: 
                   3523:     $symb=escape($symb);
1.187     www      3524:     if (!$namespace) { 
1.620     albertel 3525:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3526:           return ''; 
                   3527:        } 
                   3528:     }
1.620     albertel 3529:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3530: 
                   3531:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3532:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3533: 
1.47      www      3534:     my $namevalue='';
1.800     albertel 3535:     foreach my $key (keys(%$storehash)) {
                   3536:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3537:     }
1.47      www      3538:     $namevalue=~s/\&$//;
1.187     www      3539:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3540:     return critical
                   3541:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3542: }
                   3543: 
1.9       www      3544: # --------------------------------------------------------------------- Restore
                   3545: 
                   3546: sub restore {
1.124     www      3547:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3548:     my $home='';
                   3549: 
1.168     albertel 3550:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3551: 
1.122     albertel 3552:     if (!$symb) {
                   3553:       unless ($symb=escape(&symbread())) { return ''; }
                   3554:     } else {
1.213     www      3555:       $symb=&escape(&symbclean($symb));
1.122     albertel 3556:     }
1.188     www      3557:     if (!$namespace) { 
1.620     albertel 3558:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3559:           return ''; 
                   3560:        } 
                   3561:     }
1.620     albertel 3562:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3563:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3564:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3565:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3566: 
1.12      www      3567:     my %returnhash=();
1.800     albertel 3568:     foreach my $line (split(/\&/,$answer)) {
                   3569: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3570:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3571:     }
1.75      www      3572:     my $version;
                   3573:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3574:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3575:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3576:        }
1.75      www      3577:     }
1.13      www      3578:     return %returnhash;
1.34      www      3579: }
                   3580: 
                   3581: # ---------------------------------------------------------- Course Description
                   3582: 
                   3583: sub coursedescription {
1.731     albertel 3584:     my ($courseid,$args)=@_;
1.34      www      3585:     $courseid=~s/^\///;
1.49      www      3586:     $courseid=~s/\_/\//g;
1.34      www      3587:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3588:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3589:     my $normalid=$cdomain.'_'.$cnum;
                   3590:     # need to always cache even if we get errors otherwise we keep 
                   3591:     # trying and trying and trying to get the course description.
                   3592:     my %envhash=();
                   3593:     my %returnhash=();
1.731     albertel 3594:     
                   3595:     my $expiretime=600;
                   3596:     if ($env{'request.course.id'} eq $normalid) {
                   3597: 	$expiretime=120;
                   3598:     }
                   3599: 
                   3600:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3601:     if (!$args->{'freshen_cache'}
                   3602: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3603: 	foreach my $key (keys(%env)) {
                   3604: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3605: 	    my ($setting) = $1;
                   3606: 	    $returnhash{$setting} = $env{$key};
                   3607: 	}
                   3608: 	return %returnhash;
                   3609:     }
                   3610: 
                   3611:     # get the data agin
                   3612:     if (!$args->{'one_time'}) {
                   3613: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3614:     }
1.811     albertel 3615: 
1.34      www      3616:     if ($chome ne 'no_host') {
1.302     albertel 3617:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3618:        if (!exists($returnhash{'con_lost'})) {
                   3619:            $returnhash{'home'}= $chome;
                   3620: 	   $returnhash{'domain'} = $cdomain;
                   3621: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3622:            if (!defined($returnhash{'type'})) {
                   3623:                $returnhash{'type'} = 'Course';
                   3624:            }
1.130     albertel 3625:            while (my ($name,$value) = each %returnhash) {
1.53      www      3626:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3627:            }
1.270     www      3628:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3629:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3630: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3631:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3632:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3633:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3634:        }
                   3635:     }
1.731     albertel 3636:     if (!$args->{'one_time'}) {
1.949     raeburn  3637: 	&appenv(\%envhash);
1.731     albertel 3638:     }
1.302     albertel 3639:     return %returnhash;
1.461     www      3640: }
                   3641: 
                   3642: # -------------------------------------------------See if a user is privileged
                   3643: 
                   3644: sub privileged {
                   3645:     my ($username,$domain)=@_;
                   3646:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3647: 			&homeserver($username,$domain));
                   3648:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3649:     my $now=time;
                   3650:     if ($rolesdump ne '') {
1.800     albertel 3651:         foreach my $entry (split(/&/,$rolesdump)) {
                   3652: 	    if ($entry!~/^rolesdef_/) {
                   3653: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3654: 		$area=~s/\_\w\w$//;
                   3655: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3656: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3657: 		    my $active=1;
                   3658: 		    if ($tend) {
                   3659: 			if ($tend<$now) { $active=0; }
                   3660: 		    }
                   3661: 		    if ($tstart) {
                   3662: 			if ($tstart>$now) { $active=0; }
                   3663: 		    }
                   3664: 		    if ($active) { return 1; }
                   3665: 		}
                   3666: 	    }
                   3667: 	}
                   3668:     }
                   3669:     return 0;
1.9       www      3670: }
1.1       albertel 3671: 
1.103     harris41 3672: # -------------------------------------------------------- Get user privileges
1.11      www      3673: 
                   3674: sub rolesinit {
                   3675:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3676:     my %userroles;
1.11      www      3677:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3678:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3679:     my %allroles=();
1.678     raeburn  3680:     my %allgroups=();   
1.11      www      3681:     my $now=time;
1.966     raeburn  3682:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3683:     my $group_privs;
1.11      www      3684: 
                   3685:     if ($rolesdump ne '') {
1.800     albertel 3686:         foreach my $entry (split(/&/,$rolesdump)) {
                   3687: 	  if ($entry!~/^rolesdef_/) {
                   3688:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3689: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3690:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3691: 	    if ($role=~/^cr/) { 
1.807     albertel 3692: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3693: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3694: 		    ($tend,$tstart)=split('_',$trest);
                   3695: 		} else {
                   3696: 		    $trole=$role;
                   3697: 		}
1.678     raeburn  3698:             } elsif ($role =~ m|^gr/|) {
                   3699:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3700:                 ($trole,$group_privs) = split(/\//,$trole);
                   3701:                 $group_privs = &unescape($group_privs);
1.587     albertel 3702: 	    } else {
                   3703: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3704: 	    }
1.743     albertel 3705: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3706: 					 $username);
                   3707: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3708:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3709:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3710:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3711: 		my $spec=$trole.'.'.$area;
                   3712: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3713: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3714:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3715:                 } elsif ($trole eq 'gr') {
                   3716:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3717: 		} else {
1.567     raeburn  3718:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3719: 		}
1.12      www      3720:             }
1.662     raeburn  3721:           }
1.191     harris41 3722:         }
1.743     albertel 3723:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3724:         $userroles{'user.adv'}    = $adv;
                   3725: 	$userroles{'user.author'} = $author;
1.620     albertel 3726:         $env{'user.adv'}=$adv;
1.11      www      3727:     }
1.743     albertel 3728:     return \%userroles;  
1.11      www      3729: }
                   3730: 
1.567     raeburn  3731: sub set_arearole {
                   3732:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3733: # log the associated role with the area
                   3734:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3735:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3736: }
                   3737: 
                   3738: sub custom_roleprivs {
                   3739:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3740:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3741:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3742:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3743:         my ($rdummy,$roledef)=
                   3744:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3745:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3746:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3747:             if (defined($syspriv)) {
                   3748:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3749:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3750:             }
                   3751:             if ($tdomain ne '') {
                   3752:                 if (defined($dompriv)) {
                   3753:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3754:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3755:                 }
                   3756:                 if (($trest ne '') && (defined($coursepriv))) {
                   3757:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3758:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3759:                 }
                   3760:             }
                   3761:         }
                   3762:     }
                   3763: }
                   3764: 
1.678     raeburn  3765: sub group_roleprivs {
                   3766:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3767:     my $access = 1;
                   3768:     my $now = time;
                   3769:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3770:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3771:     if ($access) {
1.811     albertel 3772:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3773:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3774:     }
                   3775: }
1.567     raeburn  3776: 
                   3777: sub standard_roleprivs {
                   3778:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3779:     if (defined($pr{$trole.':s'})) {
                   3780:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3781:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3782:     }
                   3783:     if ($tdomain ne '') {
                   3784:         if (defined($pr{$trole.':d'})) {
                   3785:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3786:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3787:         }
                   3788:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3789:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3790:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3791:         }
                   3792:     }
                   3793: }
                   3794: 
                   3795: sub set_userprivs {
1.678     raeburn  3796:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3797:     my $author=0;
                   3798:     my $adv=0;
1.678     raeburn  3799:     my %grouproles = ();
                   3800:     if (keys(%{$allgroups}) > 0) {
                   3801:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3802:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3803:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3804:                 $trole = $1;
                   3805:                 $area = $2;
1.681     raeburn  3806:                 $sec = $3;
                   3807:                 $extendedarea = $area.$sec;
                   3808:                 if (exists($$allgroups{$area})) {
                   3809:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3810:                         my $spec = $trole.'.'.$extendedarea;
                   3811:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3812:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3813:                     }
                   3814:                 }
                   3815:             }
                   3816:         }
                   3817:     }
1.800     albertel 3818:     foreach my $group (keys(%grouproles)) {
                   3819:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3820:     }
1.800     albertel 3821:     foreach my $role (keys(%{$allroles})) {
                   3822:         my %thesepriv;
1.941     raeburn  3823:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3824:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3825:             if ($item ne '') {
                   3826:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3827:                 if ($restrictions eq '') {
                   3828:                     $thesepriv{$privilege}='F';
                   3829:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3830:                     $thesepriv{$privilege}.=$restrictions;
                   3831:                 }
                   3832:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3833:             }
                   3834:         }
                   3835:         my $thesestr='';
1.800     albertel 3836:         foreach my $priv (keys(%thesepriv)) {
                   3837: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3838: 	}
                   3839:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3840:     }
                   3841:     return ($author,$adv);
                   3842: }
                   3843: 
1.12      www      3844: # --------------------------------------------------------------- get interface
                   3845: 
                   3846: sub get {
1.131     albertel 3847:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3848:    my $items='';
1.800     albertel 3849:    foreach my $item (@$storearr) {
                   3850:        $items.=&escape($item).'&';
1.191     harris41 3851:    }
1.12      www      3852:    $items=~s/\&$//;
1.620     albertel 3853:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3854:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3855:    my $uhome=&homeserver($uname,$udomain);
                   3856: 
1.133     albertel 3857:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3858:    my @pairs=split(/\&/,$rep);
1.273     albertel 3859:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3860:      return @pairs;
                   3861:    }
1.15      www      3862:    my %returnhash=();
1.42      www      3863:    my $i=0;
1.800     albertel 3864:    foreach my $item (@$storearr) {
                   3865:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3866:       $i++;
1.191     harris41 3867:    }
1.15      www      3868:    return %returnhash;
1.27      www      3869: }
                   3870: 
                   3871: # --------------------------------------------------------------- del interface
                   3872: 
                   3873: sub del {
1.133     albertel 3874:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3875:    my $items='';
1.800     albertel 3876:    foreach my $item (@$storearr) {
                   3877:        $items.=&escape($item).'&';
1.191     harris41 3878:    }
1.984     neumanie 3879: 
1.27      www      3880:    $items=~s/\&$//;
1.620     albertel 3881:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3882:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3883:    my $uhome=&homeserver($uname,$udomain);
                   3884:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3885: }
                   3886: 
                   3887: # -------------------------------------------------------------- dump interface
                   3888: 
                   3889: sub dump {
1.755     albertel 3890:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3891:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3892:     if (!$uname) { $uname=$env{'user.name'}; }
                   3893:     my $uhome=&homeserver($uname,$udomain);
                   3894:     if ($regexp) {
                   3895: 	$regexp=&escape($regexp);
                   3896:     } else {
                   3897: 	$regexp='.';
                   3898:     }
                   3899:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3900:     my @pairs=split(/\&/,$rep);
                   3901:     my %returnhash=();
                   3902:     foreach my $item (@pairs) {
                   3903: 	my ($key,$value)=split(/=/,$item,2);
                   3904: 	$key = &unescape($key);
                   3905: 	next if ($key =~ /^error: 2 /);
                   3906: 	$returnhash{$key}=&thaw_unescape($value);
                   3907:     }
                   3908:     return %returnhash;
1.407     www      3909: }
                   3910: 
1.717     albertel 3911: # --------------------------------------------------------- dumpstore interface
                   3912: 
                   3913: sub dumpstore {
                   3914:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3915:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3916:    if (!$uname) { $uname=$env{'user.name'}; }
                   3917:    my $uhome=&homeserver($uname,$udomain);
                   3918:    if ($regexp) {
                   3919:        $regexp=&escape($regexp);
                   3920:    } else {
                   3921:        $regexp='.';
                   3922:    }
                   3923:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3924:    my @pairs=split(/\&/,$rep);
                   3925:    my %returnhash=();
                   3926:    foreach my $item (@pairs) {
                   3927:        my ($key,$value)=split(/=/,$item,2);
                   3928:        next if ($key =~ /^error: 2 /);
                   3929:        $returnhash{$key}=&thaw_unescape($value);
                   3930:    }
                   3931:    return %returnhash;
1.717     albertel 3932: }
                   3933: 
1.407     www      3934: # -------------------------------------------------------------- keys interface
                   3935: 
                   3936: sub getkeys {
                   3937:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3938:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3939:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3940:    my $uhome=&homeserver($uname,$udomain);
                   3941:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3942:    my @keyarray=();
1.800     albertel 3943:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3944:       next if ($key =~ /^error: 2 /);
1.800     albertel 3945:       push(@keyarray,&unescape($key));
1.407     www      3946:    }
                   3947:    return @keyarray;
1.318     matthew  3948: }
                   3949: 
1.319     matthew  3950: # --------------------------------------------------------------- currentdump
                   3951: sub currentdump {
1.328     matthew  3952:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3953:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3954:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3955:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3956:    my $uhome = &homeserver($sname,$sdom);
                   3957:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3958:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3959:    #
1.318     matthew  3960:    my %returnhash=();
1.319     matthew  3961:    #
                   3962:    if ($rep eq "unknown_cmd") { 
                   3963:        # an old lond will not know currentdump
                   3964:        # Do a dump and make it look like a currentdump
1.822     albertel 3965:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3966:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3967:        my %hash = @tmp;
                   3968:        @tmp=();
1.424     matthew  3969:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3970:    } else {
                   3971:        my @pairs=split(/\&/,$rep);
1.800     albertel 3972:        foreach my $pair (@pairs) {
                   3973:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3974:            my ($symb,$param) = split(/:/,$key);
                   3975:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3976:                                                         &thaw_unescape($value);
1.319     matthew  3977:        }
1.191     harris41 3978:    }
1.12      www      3979:    return %returnhash;
1.424     matthew  3980: }
                   3981: 
                   3982: sub convert_dump_to_currentdump{
                   3983:     my %hash = %{shift()};
                   3984:     my %returnhash;
                   3985:     # Code ripped from lond, essentially.  The only difference
                   3986:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3987:     # we might run in to problems with parameter names =~ /^v\./
                   3988:     while (my ($key,$value) = each(%hash)) {
                   3989:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3990: 	$symb  = &unescape($symb);
                   3991: 	$param = &unescape($param);
1.424     matthew  3992:         next if ($v eq 'version' || $symb eq 'keys');
                   3993:         next if (exists($returnhash{$symb}) &&
                   3994:                  exists($returnhash{$symb}->{$param}) &&
                   3995:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3996:         $returnhash{$symb}->{$param}=$value;
                   3997:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3998:     }
                   3999:     #
                   4000:     # Remove all of the keys in the hashes which keep track of
                   4001:     # the version of the parameter.
                   4002:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4003:         # use a foreach because we are going to delete from the hash.
                   4004:         foreach my $key (keys(%$param_hash)) {
                   4005:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4006:         }
                   4007:     }
                   4008:     return \%returnhash;
1.12      www      4009: }
                   4010: 
1.627     albertel 4011: # ------------------------------------------------------ critical inc interface
                   4012: 
                   4013: sub cinc {
                   4014:     return &inc(@_,'critical');
                   4015: }
                   4016: 
1.449     matthew  4017: # --------------------------------------------------------------- inc interface
                   4018: 
                   4019: sub inc {
1.627     albertel 4020:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4021:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4022:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4023:     my $uhome=&homeserver($uname,$udomain);
                   4024:     my $items='';
                   4025:     if (! ref($store)) {
                   4026:         # got a single value, so use that instead
                   4027:         $items = &escape($store).'=&';
                   4028:     } elsif (ref($store) eq 'SCALAR') {
                   4029:         $items = &escape($$store).'=&';        
                   4030:     } elsif (ref($store) eq 'ARRAY') {
                   4031:         $items = join('=&',map {&escape($_);} @{$store});
                   4032:     } elsif (ref($store) eq 'HASH') {
                   4033:         while (my($key,$value) = each(%{$store})) {
                   4034:             $items.= &escape($key).'='.&escape($value).'&';
                   4035:         }
                   4036:     }
                   4037:     $items=~s/\&$//;
1.627     albertel 4038:     if ($critical) {
                   4039: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4040:     } else {
                   4041: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4042:     }
1.449     matthew  4043: }
                   4044: 
1.12      www      4045: # --------------------------------------------------------------- put interface
                   4046: 
                   4047: sub put {
1.134     albertel 4048:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4049:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4050:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4051:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4052:    my $items='';
1.800     albertel 4053:    foreach my $item (keys(%$storehash)) {
                   4054:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4055:    }
1.12      www      4056:    $items=~s/\&$//;
1.134     albertel 4057:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4058: }
                   4059: 
1.631     albertel 4060: # ------------------------------------------------------------ newput interface
                   4061: 
                   4062: sub newput {
                   4063:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4064:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4065:    if (!$uname) { $uname=$env{'user.name'}; }
                   4066:    my $uhome=&homeserver($uname,$udomain);
                   4067:    my $items='';
                   4068:    foreach my $key (keys(%$storehash)) {
                   4069:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4070:    }
                   4071:    $items=~s/\&$//;
                   4072:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4073: }
                   4074: 
                   4075: # ---------------------------------------------------------  putstore interface
                   4076: 
1.524     raeburn  4077: sub putstore {
1.715     albertel 4078:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4079:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4080:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4081:    my $uhome=&homeserver($uname,$udomain);
                   4082:    my $items='';
1.715     albertel 4083:    foreach my $key (keys(%$storehash)) {
                   4084:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4085:    }
1.715     albertel 4086:    $items=~s/\&$//;
1.716     albertel 4087:    my $esc_symb=&escape($symb);
                   4088:    my $esc_v=&escape($version);
1.715     albertel 4089:    my $reply =
1.716     albertel 4090:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4091: 	      $uhome);
                   4092:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4093:        # gfall back to way things use to be done
1.715     albertel 4094:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4095: 			    $uname);
1.524     raeburn  4096:    }
1.715     albertel 4097:    return $reply;
                   4098: }
                   4099: 
                   4100: sub old_putstore {
1.716     albertel 4101:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4102:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4103:     if (!$uname) { $uname=$env{'user.name'}; }
                   4104:     my $uhome=&homeserver($uname,$udomain);
                   4105:     my %newstorehash;
1.800     albertel 4106:     foreach my $item (keys(%$storehash)) {
                   4107: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4108: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4109:     }
                   4110:     my $items='';
                   4111:     my %allitems = ();
1.800     albertel 4112:     foreach my $item (keys(%newstorehash)) {
                   4113: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4114: 	    my $key = $1.':keys:'.$2;
                   4115: 	    $allitems{$key} .= $3.':';
                   4116: 	}
1.800     albertel 4117: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4118:     }
1.800     albertel 4119:     foreach my $item (keys(%allitems)) {
                   4120: 	$allitems{$item} =~ s/\:$//;
                   4121: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4122:     }
                   4123:     $items=~s/\&$//;
                   4124:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4125: }
                   4126: 
1.47      www      4127: # ------------------------------------------------------ critical put interface
                   4128: 
                   4129: sub cput {
1.134     albertel 4130:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4131:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4132:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4133:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4134:    my $items='';
1.800     albertel 4135:    foreach my $item (keys(%$storehash)) {
                   4136:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4137:    }
1.47      www      4138:    $items=~s/\&$//;
1.134     albertel 4139:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4140: }
                   4141: 
                   4142: # -------------------------------------------------------------- eget interface
                   4143: 
                   4144: sub eget {
1.133     albertel 4145:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4146:    my $items='';
1.800     albertel 4147:    foreach my $item (@$storearr) {
                   4148:        $items.=&escape($item).'&';
1.191     harris41 4149:    }
1.12      www      4150:    $items=~s/\&$//;
1.620     albertel 4151:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4152:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4153:    my $uhome=&homeserver($uname,$udomain);
                   4154:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4155:    my @pairs=split(/\&/,$rep);
                   4156:    my %returnhash=();
1.42      www      4157:    my $i=0;
1.800     albertel 4158:    foreach my $item (@$storearr) {
                   4159:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4160:       $i++;
1.191     harris41 4161:    }
1.12      www      4162:    return %returnhash;
                   4163: }
                   4164: 
1.667     albertel 4165: # ------------------------------------------------------------ tmpput interface
                   4166: sub tmpput {
1.802     raeburn  4167:     my ($storehash,$server,$context)=@_;
1.667     albertel 4168:     my $items='';
1.800     albertel 4169:     foreach my $item (keys(%$storehash)) {
                   4170: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4171:     }
                   4172:     $items=~s/\&$//;
1.802     raeburn  4173:     if (defined($context)) {
                   4174:         $items .= ':'.&escape($context);
                   4175:     }
1.667     albertel 4176:     return &reply("tmpput:$items",$server);
                   4177: }
                   4178: 
                   4179: # ------------------------------------------------------------ tmpget interface
                   4180: sub tmpget {
1.688     albertel 4181:     my ($token,$server)=@_;
                   4182:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4183:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4184:     my %returnhash;
                   4185:     foreach my $item (split(/\&/,$rep)) {
                   4186: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4187:         next if ($key =~ /^error: 2 /);
1.667     albertel 4188: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4189:     }
                   4190:     return %returnhash;
                   4191: }
                   4192: 
1.688     albertel 4193: # ------------------------------------------------------------ tmpget interface
                   4194: sub tmpdel {
                   4195:     my ($token,$server)=@_;
                   4196:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4197:     return &reply("tmpdel:$token",$server);
                   4198: }
                   4199: 
1.765     albertel 4200: # -------------------------------------------------- portfolio access checking
                   4201: 
                   4202: sub portfolio_access {
1.766     albertel 4203:     my ($requrl) = @_;
1.765     albertel 4204:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4205:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4206:     if ($result) {
                   4207:         my %setters;
                   4208:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4209:             my ($startblock,$endblock) =
                   4210:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4211:             if ($startblock && $endblock) {
                   4212:                 return 'B';
                   4213:             }
                   4214:         } else {
                   4215:             my ($startblock,$endblock) =
                   4216:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4217:             if ($startblock && $endblock) {
                   4218:                 return 'B';
                   4219:             }
                   4220:         }
                   4221:     }
1.765     albertel 4222:     if ($result eq 'ok') {
1.766     albertel 4223:        return 'F';
1.765     albertel 4224:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4225:        return 'A';
1.765     albertel 4226:     }
1.766     albertel 4227:     return '';
1.765     albertel 4228: }
                   4229: 
                   4230: sub get_portfolio_access {
1.767     albertel 4231:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4232: 
                   4233:     if (!ref($access_hash)) {
                   4234: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4235: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4236: 						   $file_name);
                   4237: 	$access_hash = $access_controls{$file_name};
                   4238:     }
                   4239: 
1.765     albertel 4240:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4241:     my $now = time;
                   4242:     if (ref($access_hash) eq 'HASH') {
                   4243:         foreach my $key (keys(%{$access_hash})) {
                   4244:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4245:             if ($start > $now) {
                   4246:                 next;
                   4247:             }
                   4248:             if ($end && $end<$now) {
                   4249:                 next;
                   4250:             }
                   4251:             if ($scope eq 'public') {
                   4252:                 $public = $key;
                   4253:                 last;
                   4254:             } elsif ($scope eq 'guest') {
                   4255:                 $guest = $key;
                   4256:             } elsif ($scope eq 'domains') {
                   4257:                 push(@domains,$key);
                   4258:             } elsif ($scope eq 'users') {
                   4259:                 push(@users,$key);
                   4260:             } elsif ($scope eq 'course') {
                   4261:                 push(@courses,$key);
                   4262:             } elsif ($scope eq 'group') {
                   4263:                 push(@groups,$key);
                   4264:             }
                   4265:         }
                   4266:         if ($public) {
                   4267:             return 'ok';
                   4268:         }
                   4269:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4270:             if ($guest) {
                   4271:                 return $guest;
                   4272:             }
                   4273:         } else {
                   4274:             if (@domains > 0) {
                   4275:                 foreach my $domkey (@domains) {
                   4276:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4277:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4278:                             return 'ok';
                   4279:                         }
                   4280:                     }
                   4281:                 }
                   4282:             }
                   4283:             if (@users > 0) {
                   4284:                 foreach my $userkey (@users) {
1.865     raeburn  4285:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4286:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4287:                             if (ref($item) eq 'HASH') {
                   4288:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4289:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4290:                                     return 'ok';
                   4291:                                 }
                   4292:                             }
                   4293:                         }
                   4294:                     } 
1.765     albertel 4295:                 }
                   4296:             }
                   4297:             my %roleshash;
                   4298:             my @courses_and_groups = @courses;
                   4299:             push(@courses_and_groups,@groups); 
                   4300:             if (@courses_and_groups > 0) {
                   4301:                 my (%allgroups,%allroles); 
                   4302:                 my ($start,$end,$role,$sec,$group);
                   4303:                 foreach my $envkey (%env) {
1.811     albertel 4304:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4305:                         my $cid = $2.'_'.$3; 
                   4306:                         if ($1 eq 'gr') {
                   4307:                             $group = $4;
                   4308:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4309:                         } else {
                   4310:                             if ($4 eq '') {
                   4311:                                 $sec = 'none';
                   4312:                             } else {
                   4313:                                 $sec = $4;
                   4314:                             }
                   4315:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4316:                         }
1.811     albertel 4317:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4318:                         my $cid = $2.'_'.$3;
                   4319:                         if ($4 eq '') {
                   4320:                             $sec = 'none';
                   4321:                         } else {
                   4322:                             $sec = $4;
                   4323:                         }
                   4324:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4325:                     }
                   4326:                 }
                   4327:                 if (keys(%allroles) == 0) {
                   4328:                     return;
                   4329:                 }
                   4330:                 foreach my $key (@courses_and_groups) {
                   4331:                     my %content = %{$$access_hash{$key}};
                   4332:                     my $cnum = $content{'number'};
                   4333:                     my $cdom = $content{'domain'};
                   4334:                     my $cid = $cdom.'_'.$cnum;
                   4335:                     if (!exists($allroles{$cid})) {
                   4336:                         next;
                   4337:                     }    
                   4338:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4339:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4340:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4341:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4342:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4343:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4344:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4345:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4346:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4347:                                         if (grep/^all$/,@sections) {
                   4348:                                             return 'ok';
                   4349:                                         } else {
                   4350:                                             if (grep/^$sec$/,@sections) {
                   4351:                                                 return 'ok';
                   4352:                                             }
                   4353:                                         }
                   4354:                                     }
                   4355:                                 }
                   4356:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4357:                                     if (grep/^none$/,@groups) {
                   4358:                                         return 'ok';
                   4359:                                     }
                   4360:                                 } else {
                   4361:                                     if (grep/^all$/,@groups) {
                   4362:                                         return 'ok';
                   4363:                                     } 
                   4364:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4365:                                         if (grep/^$group$/,@groups) {
                   4366:                                             return 'ok';
                   4367:                                         }
                   4368:                                     }
                   4369:                                 } 
                   4370:                             }
                   4371:                         }
                   4372:                     }
                   4373:                 }
                   4374:             }
                   4375:             if ($guest) {
                   4376:                 return $guest;
                   4377:             }
                   4378:         }
                   4379:     }
                   4380:     return;
                   4381: }
                   4382: 
                   4383: sub course_group_datechecker {
                   4384:     my ($dates,$now,$status) = @_;
                   4385:     my ($start,$end) = split(/\./,$dates);
                   4386:     if (!$start && !$end) {
                   4387:         return 'ok';
                   4388:     }
                   4389:     if (grep/^active$/,@{$status}) {
                   4390:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4391:             return 'ok';
                   4392:         }
                   4393:     }
                   4394:     if (grep/^previous$/,@{$status}) {
                   4395:         if ($end > $now ) {
                   4396:             return 'ok';
                   4397:         }
                   4398:     }
                   4399:     if (grep/^future$/,@{$status}) {
                   4400:         if ($start > $now) {
                   4401:             return 'ok';
                   4402:         }
                   4403:     }
                   4404:     return; 
                   4405: }
                   4406: 
                   4407: sub parse_portfolio_url {
                   4408:     my ($url) = @_;
                   4409: 
                   4410:     my ($type,$udom,$unum,$group,$file_name);
                   4411:     
1.823     albertel 4412:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4413: 	$type = 1;
                   4414:         $udom = $1;
                   4415:         $unum = $2;
                   4416:         $file_name = $3;
1.823     albertel 4417:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4418: 	$type = 2;
                   4419:         $udom = $1;
                   4420:         $unum = $2;
                   4421:         $group = $3;
                   4422:         $file_name = $3.'/'.$4;
                   4423:     }
                   4424:     if (wantarray) {
                   4425: 	return ($type,$udom,$unum,$file_name,$group);
                   4426:     }
                   4427:     return $type;
                   4428: }
                   4429: 
                   4430: sub is_portfolio_url {
                   4431:     my ($url) = @_;
                   4432:     return scalar(&parse_portfolio_url($url));
                   4433: }
                   4434: 
1.798     raeburn  4435: sub is_portfolio_file {
                   4436:     my ($file) = @_;
1.820     raeburn  4437:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4438:         return 1;
                   4439:     }
                   4440:     return;
                   4441: }
                   4442: 
1.976     raeburn  4443: sub usertools_access {
1.985     raeburn  4444:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4445:     my ($access,%tools);
                   4446:     if ($context eq '') {
                   4447:         $context = 'tools';
                   4448:     }
                   4449:     if ($context eq 'requestcourses') {
                   4450:         %tools = (
                   4451:                       official   => 1,
                   4452:                       unofficial => 1,
                   4453:                  );
                   4454:     } else {
                   4455:         %tools = (
                   4456:                       aboutme   => 1,
                   4457:                       blog      => 1,
                   4458:                       portfolio => 1,
                   4459:                  );
                   4460:     }
1.976     raeburn  4461:     return if (!defined($tools{$tool}));
                   4462: 
                   4463:     if ((!defined($udom)) || (!defined($uname))) {
                   4464:         $udom = $env{'user.domain'};
                   4465:         $uname = $env{'user.name'};
                   4466:     }
                   4467: 
1.978     raeburn  4468:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4469:         if ($action ne 'reload') {
1.985     raeburn  4470:             if ($context eq 'requestcourses') {
                   4471:                 return $env{'environment.canrequest.'.$tool};
                   4472:             } else {
                   4473:                 return $env{'environment.availabletools.'.$tool};
                   4474:             }
                   4475:         }
1.976     raeburn  4476:     }
                   4477: 
                   4478:     my ($toolstatus,$inststatus);
                   4479: 
1.985     raeburn  4480:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4481:          ($action ne 'reload')) {
                   4482:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4483:         $inststatus = $env{'environment.inststatus'};
                   4484:     } else {
1.985     raeburn  4485:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
                   4486:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4487:         $inststatus = $userenv{'inststatus'};
                   4488:     }
                   4489: 
                   4490:     if ($toolstatus ne '') {
                   4491:         if ($toolstatus) {
                   4492:             $access = 1;
                   4493:         } else {
                   4494:             $access = 0;
                   4495:         }
                   4496:         return $access;
                   4497:     }
                   4498: 
                   4499:     my $is_adv = &is_advanced_user($udom,$uname);
                   4500:     my %domdef = &get_domain_defaults($udom);
                   4501:     if (ref($domdef{$tool}) eq 'HASH') {
                   4502:         if ($is_adv) {
                   4503:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4504:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4505:                     $access = 1;
                   4506:                 } else {
                   4507:                     $access = 0;
                   4508:                 }
                   4509:                 return $access;
                   4510:             }
                   4511:         }
                   4512:         if ($inststatus ne '') {
                   4513:             my ($hasaccess,$hasnoaccess);
                   4514:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4515:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4516:                     if ($domdef{$tool}{$affiliation}) {
                   4517:                         $hasaccess = 1;
                   4518:                     } else {
                   4519:                         $hasnoaccess = 1;
                   4520:                     }
                   4521:                 }
                   4522:             }
                   4523:             if ($hasaccess || $hasnoaccess) {
                   4524:                 if ($hasaccess) {
                   4525:                     $access = 1;
                   4526:                 } elsif ($hasnoaccess) {
                   4527:                     $access = 0; 
                   4528:                 }
                   4529:                 return $access;
                   4530:             }
                   4531:         } else {
                   4532:             if ($domdef{$tool}{'default'} ne '') {
                   4533:                 if ($domdef{$tool}{'default'}) {
                   4534:                     $access = 1;
                   4535:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4536:                     $access = 0;
                   4537:                 }
                   4538:                 return $access;
                   4539:             }
                   4540:         }
                   4541:     } else {
1.985     raeburn  4542:         if ($context eq 'tools') {
                   4543:             $access = 1;
                   4544:         } else {
                   4545:             $access = 0;
                   4546:         }
1.976     raeburn  4547:         return $access;
                   4548:     }
                   4549: }
                   4550: 
                   4551: sub is_advanced_user {
                   4552:     my ($udom,$uname) = @_;
                   4553:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4554:     my %allroles;
                   4555:     my $is_adv;
                   4556:     foreach my $role (keys(%roleshash)) {
                   4557:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4558:         my $area = '/'.$tdomain.'/'.$trest;
                   4559:         if ($sec ne '') {
                   4560:             $area .= '/'.$sec;
                   4561:         }
                   4562:         if (($area ne '') && ($trole ne '')) {
                   4563:             my $spec=$trole.'.'.$area;
                   4564:             if ($trole =~ /^cr\//) {
                   4565:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4566:             } elsif ($trole ne 'gr') {
                   4567:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4568:             }
                   4569:         }
                   4570:     }
                   4571:     foreach my $role (keys(%allroles)) {
                   4572:         last if ($is_adv);
                   4573:         foreach my $item (split(/:/,$allroles{$role})) {
                   4574:             if ($item ne '') {
                   4575:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4576:                 if ($privilege eq 'adv') {
                   4577:                     $is_adv = 1;
                   4578:                     last;
                   4579:                 }
                   4580:             }
                   4581:         }
                   4582:     }
                   4583:     return $is_adv;
                   4584: }
1.798     raeburn  4585: 
1.341     www      4586: # ---------------------------------------------- Custom access rule evaluation
                   4587: 
                   4588: sub customaccess {
                   4589:     my ($priv,$uri)=@_;
1.807     albertel 4590:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4591:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4592:     $udom = &LONCAPA::clean_domain($udom);
                   4593:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4594:     my $access=0;
1.800     albertel 4595:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4596: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4597: 	if ($type eq 'user') {
                   4598: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4599: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4600: 		if ($tdom) {
                   4601: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4602: 		}
1.896     albertel 4603: 		if ($tuname) {
                   4604: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4605: 		}
                   4606: 		$access=($effect eq 'allow');
                   4607: 		last;
                   4608: 	    }
                   4609: 	} else {
                   4610: 	    if ($role) {
                   4611: 		if ($role ne $urole) { next; }
                   4612: 	    }
                   4613: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4614: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4615: 		if ($tdom) {
                   4616: 		    if ($tdom ne $udom) { next; }
                   4617: 		}
                   4618: 		if ($tcrs) {
                   4619: 		    if ($tcrs ne $ucrs) { next; }
                   4620: 		}
                   4621: 		if ($tsec) {
                   4622: 		    if ($tsec ne $usec) { next; }
                   4623: 		}
                   4624: 		$access=($effect eq 'allow');
                   4625: 		last;
                   4626: 	    }
                   4627: 	    if ($realm eq '' && $role eq '') {
                   4628: 		$access=($effect eq 'allow');
                   4629: 	    }
1.402     bowersj2 4630: 	}
1.341     www      4631:     }
                   4632:     return $access;
                   4633: }
                   4634: 
1.103     harris41 4635: # ------------------------------------------------- Check for a user privilege
1.12      www      4636: 
                   4637: sub allowed {
1.810     raeburn  4638:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4639:     my $ver_orguri=$uri;
1.439     www      4640:     $uri=&deversion($uri);
1.152     www      4641:     my $orguri=$uri;
1.52      www      4642:     $uri=&declutter($uri);
1.809     raeburn  4643: 
1.810     raeburn  4644:     if ($priv eq 'evb') {
                   4645: # Evade communication block restrictions for specified role in a course
                   4646:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4647:             return $1;
                   4648:         } else {
                   4649:             return;
                   4650:         }
                   4651:     }
                   4652: 
1.620     albertel 4653:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4654: # Free bre access to adm and meta resources
1.775     albertel 4655:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4656: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4657: 	&& ($priv eq 'bre')) {
1.14      www      4658: 	return 'F';
1.159     www      4659:     }
                   4660: 
1.545     banghart 4661: # Free bre access to user's own portfolio contents
1.714     raeburn  4662:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4663:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4664: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4665:         my %setters;
                   4666:         my ($startblock,$endblock) = 
                   4667:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4668:         if ($startblock && $endblock) {
                   4669:             return 'B';
                   4670:         } else {
                   4671:             return 'F';
                   4672:         }
1.545     banghart 4673:     }
                   4674: 
1.762     raeburn  4675: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4676:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4677:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4678:         if (exists($env{'request.course.id'})) {
                   4679:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4680:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4681:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4682:                 my $courseprivid=$env{'request.course.id'};
                   4683:                 $courseprivid=~s/\_/\//;
                   4684:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4685:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4686:                     return $1; 
1.762     raeburn  4687:                 } else {
                   4688:                     if ($env{'request.course.sec'}) {
                   4689:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4690:                     }
                   4691:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4692:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4693:                         return $2;
                   4694:                     }
1.714     raeburn  4695:                 }
                   4696:             }
                   4697:         }
                   4698:     }
                   4699: 
1.159     www      4700: # Free bre to public access
                   4701: 
                   4702:     if ($priv eq 'bre') {
1.238     www      4703:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4704: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4705:            return 'F'; 
                   4706:         }
1.238     www      4707:         if ($copyright eq 'priv') {
                   4708:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4709: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4710: 		return '';
                   4711:             }
                   4712:         }
                   4713:         if ($copyright eq 'domain') {
                   4714:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4715: 	    unless (($env{'user.domain'} eq $1) ||
                   4716:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4717: 		return '';
                   4718:             }
1.262     matthew  4719:         }
1.620     albertel 4720:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4721:             # Library role, so allow browsing of resources in this domain.
                   4722:             return 'F';
1.238     www      4723:         }
1.341     www      4724:         if ($copyright eq 'custom') {
                   4725: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4726:         }
1.14      www      4727:     }
1.264     matthew  4728:     # Domain coordinator is trying to create a course
1.620     albertel 4729:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4730:         # uri is the requested domain in this case.
                   4731:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4732:         # a role of dc for the domain in question.
1.620     albertel 4733:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4734:     }
1.29      www      4735: 
1.52      www      4736:     my $thisallowed='';
                   4737:     my $statecond=0;
                   4738:     my $courseprivid='';
                   4739: 
                   4740: # Course
                   4741: 
1.620     albertel 4742:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4743:        $thisallowed.=$1;
                   4744:     }
1.29      www      4745: 
1.52      www      4746: # Domain
                   4747: 
1.620     albertel 4748:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4749:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4750:        $thisallowed.=$1;
                   4751:     }
1.52      www      4752: 
                   4753: # Course: uri itself is a course
1.66      www      4754:     my $courseuri=$uri;
                   4755:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4756:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4757: 
1.620     albertel 4758:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4759:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4760:        $thisallowed.=$1;
                   4761:     }
1.29      www      4762: 
1.665     albertel 4763: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4764: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4765:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4766: 	$thisallowed='';
1.671     raeburn  4767:         my ($match)=&is_on_map($uri);
                   4768:         if ($match) {
                   4769:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4770:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4771:                 $thisallowed.=$1;
                   4772:             }
                   4773:         } else {
1.705     albertel 4774:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4775:             if ($refuri) {
                   4776:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4777:                     $thisallowed='F';
1.671     raeburn  4778:                 } else {
                   4779:                     $refuri=&declutter($refuri);
                   4780:                     my ($match) = &is_on_map($refuri);
                   4781:                     if ($match) {
                   4782:                         $thisallowed='F';
                   4783:                     }
1.669     raeburn  4784:                 }
1.671     raeburn  4785:             }
                   4786:         }
1.314     www      4787:     }
1.492     albertel 4788: 
1.766     albertel 4789:     if ($priv eq 'bre'
                   4790: 	&& $thisallowed ne 'F' 
                   4791: 	&& $thisallowed ne '2'
                   4792: 	&& &is_portfolio_url($uri)) {
                   4793: 	$thisallowed = &portfolio_access($uri);
                   4794:     }
                   4795:     
1.52      www      4796: # Full access at system, domain or course-wide level? Exit.
1.29      www      4797:     if ($thisallowed=~/F/) {
                   4798: 	return 'F';
                   4799:     }
                   4800: 
1.52      www      4801: # If this is generating or modifying users, exit with special codes
1.29      www      4802: 
1.643     www      4803:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4804: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4805: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4806: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4807: 	    unless ($auname) { return $thisallowed; }
                   4808: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4809: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4810: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4811: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4812: 	}
1.52      www      4813: 	return $thisallowed;
                   4814:     }
                   4815: #
1.103     harris41 4816: # Gathered so far: system, domain and course wide privileges
1.52      www      4817: #
                   4818: # Course: See if uri or referer is an individual resource that is part of 
                   4819: # the course
                   4820: 
1.620     albertel 4821:     if ($env{'request.course.id'}) {
1.232     www      4822: 
1.620     albertel 4823:        $courseprivid=$env{'request.course.id'};
                   4824:        if ($env{'request.course.sec'}) {
                   4825:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4826:        }
                   4827:        $courseprivid=~s/\_/\//;
                   4828:        my $checkreferer=1;
1.232     www      4829:        my ($match,$cond)=&is_on_map($uri);
                   4830:        if ($match) {
                   4831:            $statecond=$cond;
1.620     albertel 4832:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4833:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4834:                $thisallowed.=$1;
                   4835:                $checkreferer=0;
                   4836:            }
1.29      www      4837:        }
1.83      www      4838:        
1.148     www      4839:        if ($checkreferer) {
1.620     albertel 4840: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4841:             unless ($refuri) {
1.800     albertel 4842:                 foreach my $key (keys(%env)) {
                   4843: 		    if ($key=~/^httpref\..*\*/) {
                   4844: 			my $pattern=$key;
1.156     www      4845:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4846:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4847:                         $pattern=~s/\//\\\//g;
1.152     www      4848:                         if ($orguri=~/$pattern/) {
1.800     albertel 4849: 			    $refuri=$env{$key};
1.148     www      4850:                         }
                   4851:                     }
1.191     harris41 4852:                 }
1.148     www      4853:             }
1.232     www      4854: 
1.148     www      4855:          if ($refuri) { 
1.152     www      4856: 	  $refuri=&declutter($refuri);
1.232     www      4857:           my ($match,$cond)=&is_on_map($refuri);
                   4858:             if ($match) {
                   4859:               my $refstatecond=$cond;
1.620     albertel 4860:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4861:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4862:                   $thisallowed.=$1;
1.53      www      4863:                   $uri=$refuri;
                   4864:                   $statecond=$refstatecond;
1.52      www      4865:               }
                   4866:           }
1.148     www      4867:         }
1.29      www      4868:        }
1.52      www      4869:    }
1.29      www      4870: 
1.52      www      4871: #
1.103     harris41 4872: # Gathered now: all privileges that could apply, and condition number
1.52      www      4873: # 
                   4874: #
                   4875: # Full or no access?
                   4876: #
1.29      www      4877: 
1.52      www      4878:     if ($thisallowed=~/F/) {
                   4879: 	return 'F';
                   4880:     }
1.29      www      4881: 
1.52      www      4882:     unless ($thisallowed) {
                   4883:         return '';
                   4884:     }
1.29      www      4885: 
1.52      www      4886: # Restrictions exist, deal with them
                   4887: #
                   4888: #   C:according to course preferences
                   4889: #   R:according to resource settings
                   4890: #   L:unless locked
                   4891: #   X:according to user session state
                   4892: #
                   4893: 
                   4894: # Possibly locked functionality, check all courses
1.54      www      4895: # Locks might take effect only after 10 minutes cache expiration for other
                   4896: # courses, and 2 minutes for current course
1.52      www      4897: 
                   4898:     my $envkey;
                   4899:     if ($thisallowed=~/L/) {
1.620     albertel 4900:         foreach $envkey (keys %env) {
1.54      www      4901:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4902:                my $courseid=$2;
                   4903:                my $roleid=$1.'.'.$2;
1.92      www      4904:                $courseid=~s/^\///;
1.54      www      4905:                my $expiretime=600;
1.620     albertel 4906:                if ($env{'request.role'} eq $roleid) {
1.54      www      4907: 		  $expiretime=120;
                   4908:                }
                   4909: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4910:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4911:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4912: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4913:                }
1.620     albertel 4914:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4915:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4916: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4917:                        &log($env{'user.domain'},$env{'user.name'},
                   4918:                             $env{'user.home'},
1.57      www      4919:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4920:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4921:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4922: 		       return '';
                   4923:                    }
                   4924:                }
1.620     albertel 4925:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4926:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4927: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4928:                        &log($env{'user.domain'},$env{'user.name'},
                   4929:                             $env{'user.home'},
1.57      www      4930:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4931:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4932:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4933: 		       return '';
                   4934:                    }
                   4935:                }
                   4936: 	   }
1.29      www      4937:        }
1.52      www      4938:     }
                   4939:    
                   4940: #
                   4941: # Rest of the restrictions depend on selected course
                   4942: #
                   4943: 
1.620     albertel 4944:     unless ($env{'request.course.id'}) {
1.766     albertel 4945: 	if ($thisallowed eq 'A') {
                   4946: 	    return 'A';
1.814     raeburn  4947:         } elsif ($thisallowed eq 'B') {
                   4948:             return 'B';
1.766     albertel 4949: 	} else {
                   4950: 	    return '1';
                   4951: 	}
1.52      www      4952:     }
1.29      www      4953: 
1.52      www      4954: #
                   4955: # Now user is definitely in a course
                   4956: #
1.53      www      4957: 
                   4958: 
                   4959: # Course preferences
                   4960: 
                   4961:    if ($thisallowed=~/C/) {
1.620     albertel 4962:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4963:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4964:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4965: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4966: 	   if ($priv ne 'pch') { 
                   4967: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4968: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4969: 			$env{'request.course.id'});
                   4970: 	   }
1.237     www      4971:            return '';
                   4972:        }
                   4973: 
1.620     albertel 4974:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4975: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4976: 	   if ($priv ne 'pch') { 
                   4977: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4978: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4979: 			$env{'request.course.id'});
                   4980: 	   }
1.54      www      4981:            return '';
                   4982:        }
1.53      www      4983:    }
                   4984: 
                   4985: # Resource preferences
                   4986: 
                   4987:    if ($thisallowed=~/R/) {
1.620     albertel 4988:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4989:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4990: 	   if ($priv ne 'pch') { 
                   4991: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4992: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4993: 	   }
                   4994: 	   return '';
1.54      www      4995:        }
1.53      www      4996:    }
1.30      www      4997: 
1.246     www      4998: # Restricted by state or randomout?
1.30      www      4999: 
1.52      www      5000:    if ($thisallowed=~/X/) {
1.620     albertel 5001:       if ($env{'acc.randomout'}) {
1.579     albertel 5002: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5003:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5004:             return ''; 
                   5005:          }
1.247     www      5006:       }
                   5007:       if (&condval($statecond)) {
1.52      www      5008: 	 return '2';
                   5009:       } else {
                   5010:          return '';
                   5011:       }
                   5012:    }
1.30      www      5013: 
1.766     albertel 5014:     if ($thisallowed eq 'A') {
                   5015: 	return 'A';
1.814     raeburn  5016:     } elsif ($thisallowed eq 'B') {
                   5017:         return 'B';
1.766     albertel 5018:     }
1.52      www      5019:    return 'F';
1.232     www      5020: }
                   5021: 
1.710     albertel 5022: sub split_uri_for_cond {
                   5023:     my $uri=&deversion(&declutter(shift));
                   5024:     my @uriparts=split(/\//,$uri);
                   5025:     my $filename=pop(@uriparts);
                   5026:     my $pathname=join('/',@uriparts);
                   5027:     return ($pathname,$filename);
                   5028: }
1.232     www      5029: # --------------------------------------------------- Is a resource on the map?
                   5030: 
                   5031: sub is_on_map {
1.710     albertel 5032:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5033:     #Trying to find the conditional for the file
1.620     albertel 5034:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5035: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5036:     if ($match) {
1.289     bowersj2 5037: 	return (1,$1);
                   5038:     } else {
1.434     www      5039: 	return (0,0);
1.289     bowersj2 5040:     }
1.12      www      5041: }
                   5042: 
1.427     www      5043: # --------------------------------------------------------- Get symb from alias
                   5044: 
                   5045: sub get_symb_from_alias {
                   5046:     my $symb=shift;
                   5047:     my ($map,$resid,$url)=&decode_symb($symb);
                   5048: # Already is a symb
                   5049:     if ($url) { return $symb; }
                   5050: # Must be an alias
                   5051:     my $aliassymb='';
                   5052:     my %bighash;
1.620     albertel 5053:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5054:                             &GDBM_READER(),0640)) {
                   5055:         my $rid=$bighash{'mapalias_'.$symb};
                   5056: 	if ($rid) {
                   5057: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5058: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5059: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5060: 	}
                   5061:         untie %bighash;
                   5062:     }
                   5063:     return $aliassymb;
                   5064: }
                   5065: 
1.12      www      5066: # ----------------------------------------------------------------- Define Role
                   5067: 
                   5068: sub definerole {
                   5069:   if (allowed('mcr','/')) {
                   5070:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5071:     foreach my $role (split(':',$sysrole)) {
                   5072: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5073:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5074:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5075: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5076:                return "refused:s:$crole&$cqual"; 
                   5077:             }
                   5078:         }
1.191     harris41 5079:     }
1.800     albertel 5080:     foreach my $role (split(':',$domrole)) {
                   5081: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5082:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5083:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5084: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5085:                return "refused:d:$crole&$cqual"; 
                   5086:             }
                   5087:         }
1.191     harris41 5088:     }
1.800     albertel 5089:     foreach my $role (split(':',$courole)) {
                   5090: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5091:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5092:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5093: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5094:                return "refused:c:$crole&$cqual"; 
                   5095:             }
                   5096:         }
1.191     harris41 5097:     }
1.620     albertel 5098:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5099:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5100: 	        "rolesdef_$rolename=".
                   5101:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5102:     return reply($command,$env{'user.home'});
1.12      www      5103:   } else {
                   5104:     return 'refused';
                   5105:   }
1.105     harris41 5106: }
                   5107: 
                   5108: # ---------------- Make a metadata query against the network of library servers
                   5109: 
                   5110: sub metadata_query {
1.244     matthew  5111:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5112:     my %rhash;
1.845     albertel 5113:     my %libserv = &all_library();
1.244     matthew  5114:     my @server_list = (defined($server_array) ? @$server_array
                   5115:                                               : keys(%libserv) );
                   5116:     for my $server (@server_list) {
1.118     harris41 5117: 	unless ($custom or $customshow) {
                   5118: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5119: 	    $rhash{$server}=$reply;
                   5120: 	}
                   5121: 	else {
                   5122: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5123: 			     &escape($custom).':'.&escape($customshow),
                   5124: 			     $server);
                   5125: 	    $rhash{$server}=$reply;
                   5126: 	}
1.112     harris41 5127:     }
1.118     harris41 5128:     return \%rhash;
1.240     www      5129: }
                   5130: 
                   5131: # ----------------------------------------- Send log queries and wait for reply
                   5132: 
                   5133: sub log_query {
                   5134:     my ($uname,$udom,$query,%filters)=@_;
                   5135:     my $uhome=&homeserver($uname,$udom);
                   5136:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5137:     my $uhost=&hostname($uhome);
1.800     albertel 5138:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5139:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5140:                        $uhome);
1.479     albertel 5141:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5142:     return get_query_reply($queryid);
                   5143: }
                   5144: 
1.818     raeburn  5145: # -------------------------- Update MySQL table for portfolio file
                   5146: 
                   5147: sub update_portfolio_table {
1.821     raeburn  5148:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5149:     if ($group ne '') {
                   5150:         $file_name =~s /^\Q$group\E//;
                   5151:     }
1.818     raeburn  5152:     my $homeserver = &homeserver($uname,$udom);
                   5153:     my $queryid=
1.821     raeburn  5154:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5155:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5156:     my $reply = &get_query_reply($queryid);
                   5157:     return $reply;
                   5158: }
                   5159: 
1.899     raeburn  5160: # -------------------------- Update MySQL allusers table
                   5161: 
                   5162: sub update_allusers_table {
                   5163:     my ($uname,$udom,$names) = @_;
                   5164:     my $homeserver = &homeserver($uname,$udom);
                   5165:     my $queryid=
                   5166:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5167:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5168:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5169:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5170:                'generation='.&escape($names->{'generation'}).'%%'.
                   5171:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5172:                'id='.&escape($names->{'id'}),$homeserver);
                   5173:     my $reply = &get_query_reply($queryid);
                   5174:     return $reply;
                   5175: }
                   5176: 
1.508     raeburn  5177: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5178: 
                   5179: sub fetch_enrollment_query {
1.511     raeburn  5180:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5181:     my $homeserver;
1.547     raeburn  5182:     my $maxtries = 1;
1.508     raeburn  5183:     if ($context eq 'automated') {
                   5184:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5185:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5186:     } else {
                   5187:         $homeserver = &homeserver($cnum,$dom);
                   5188:     }
1.838     albertel 5189:     my $host=&hostname($homeserver);
1.506     raeburn  5190:     my $cmd = '';
1.800     albertel 5191:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5192:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5193:     }
                   5194:     $cmd =~ s/%%$//;
                   5195:     $cmd = &escape($cmd);
                   5196:     my $query = 'fetchenrollment';
1.620     albertel 5197:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5198:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5199:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5200:         return 'error: '.$queryid;
                   5201:     }
1.506     raeburn  5202:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5203:     my $tries = 1;
                   5204:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5205:         $reply = &get_query_reply($queryid);
                   5206:         $tries ++;
                   5207:     }
1.526     raeburn  5208:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5209:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5210:     } else {
1.901     albertel 5211:         my @responses = split(/:/,$reply);
1.515     raeburn  5212:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5213:             foreach my $line (@responses) {
                   5214:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5215:                 $$replyref{$key} = $value;
                   5216:             }
                   5217:         } else {
1.506     raeburn  5218:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5219:             foreach my $line (@responses) {
                   5220:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5221:                 $$replyref{$key} = $value;
                   5222:                 if ($value > 0) {
1.800     albertel 5223:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5224:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5225:                         my $destname = $pathname.'/'.$filename;
                   5226:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5227:                         if ($xml_classlist =~ /^error/) {
                   5228:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5229:                         } else {
1.506     raeburn  5230:                             if ( open(FILE,">$destname") ) {
                   5231:                                 print FILE &unescape($xml_classlist);
                   5232:                                 close(FILE);
1.526     raeburn  5233:                             } else {
                   5234:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5235:                             }
                   5236:                         }
                   5237:                     }
                   5238:                 }
                   5239:             }
                   5240:         }
                   5241:         return 'ok';
                   5242:     }
                   5243:     return 'error';
                   5244: }
                   5245: 
1.242     www      5246: sub get_query_reply {
                   5247:     my $queryid=shift;
1.240     www      5248:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5249:     my $reply='';
                   5250:     for (1..100) {
                   5251: 	sleep 2;
                   5252:         if (-e $replyfile.'.end') {
1.448     albertel 5253: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5254: 		$reply = join('',<$fh>);
                   5255: 		close($fh);
1.240     www      5256: 	   } else { return 'error: reply_file_error'; }
1.242     www      5257:            return &unescape($reply);
                   5258: 	}
1.240     www      5259:     }
1.242     www      5260:     return 'timeout:'.$queryid;
1.240     www      5261: }
                   5262: 
                   5263: sub courselog_query {
1.241     www      5264: #
                   5265: # possible filters:
                   5266: # url: url or symb
                   5267: # username
                   5268: # domain
                   5269: # action: view, submit, grade
                   5270: # start: timestamp
                   5271: # end: timestamp
                   5272: #
1.240     www      5273:     my (%filters)=@_;
1.620     albertel 5274:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5275:     if ($filters{'url'}) {
                   5276: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5277:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5278:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5279:     }
1.620     albertel 5280:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5281:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5282:     return &log_query($cname,$cdom,'courselog',%filters);
                   5283: }
                   5284: 
                   5285: sub userlog_query {
1.858     raeburn  5286: #
                   5287: # possible filters:
                   5288: # action: log check role
                   5289: # start: timestamp
                   5290: # end: timestamp
                   5291: #
1.240     www      5292:     my ($uname,$udom,%filters)=@_;
                   5293:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5294: }
                   5295: 
1.506     raeburn  5296: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5297: 
                   5298: sub auto_run {
1.508     raeburn  5299:     my ($cnum,$cdom) = @_;
1.876     raeburn  5300:     my $response = 0;
                   5301:     my $settings;
                   5302:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5303:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5304:         $settings = $domconfig{'autoenroll'};
                   5305:         if ($settings->{'run'} eq '1') {
                   5306:             $response = 1;
                   5307:         }
                   5308:     } else {
1.934     raeburn  5309:         my $homeserver;
                   5310:         if (&is_course($cdom,$cnum)) {
                   5311:             $homeserver = &homeserver($cnum,$cdom);
                   5312:         } else {
                   5313:             $homeserver = &domain($cdom,'primary');
                   5314:         }
                   5315:         if ($homeserver ne 'no_host') {
                   5316:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5317:         }
1.876     raeburn  5318:     }
1.506     raeburn  5319:     return $response;
                   5320: }
1.776     albertel 5321: 
1.506     raeburn  5322: sub auto_get_sections {
1.508     raeburn  5323:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5324:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5325:     my @secs = ();
1.511     raeburn  5326:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5327:     unless ($response eq 'refused') {
1.901     albertel 5328:         @secs = split(/:/,$response);
1.506     raeburn  5329:     }
                   5330:     return @secs;
                   5331: }
1.776     albertel 5332: 
1.506     raeburn  5333: sub auto_new_course {
1.508     raeburn  5334:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5335:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5336:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5337:     return $response;
                   5338: }
1.776     albertel 5339: 
1.506     raeburn  5340: sub auto_validate_courseID {
1.508     raeburn  5341:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5342:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5343:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5344:     return $response;
                   5345: }
1.776     albertel 5346: 
1.506     raeburn  5347: sub auto_create_password {
1.873     raeburn  5348:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5349:     my ($homeserver,$response);
1.506     raeburn  5350:     my $create_passwd = 0;
                   5351:     my $authchk = '';
1.873     raeburn  5352:     if ($udom =~ /^$match_domain$/) {
                   5353:         $homeserver = &domain($udom,'primary');
                   5354:     }
                   5355:     if ($homeserver eq '') {
                   5356:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5357:             $homeserver = &homeserver($cnum,$cdom);
                   5358:         }
                   5359:     }
                   5360:     if ($homeserver eq '') {
                   5361:         $authchk = 'nodomain';
1.506     raeburn  5362:     } else {
1.873     raeburn  5363:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5364:         if ($response eq 'refused') {
                   5365:             $authchk = 'refused';
                   5366:         } else {
1.901     albertel 5367:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5368:         }
1.506     raeburn  5369:     }
                   5370:     return ($authparam,$create_passwd,$authchk);
                   5371: }
                   5372: 
1.706     raeburn  5373: sub auto_photo_permission {
                   5374:     my ($cnum,$cdom,$students) = @_;
                   5375:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5376:     my ($outcome,$perm_reqd,$conditions) = 
                   5377: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5378:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5379: 	return (undef,undef);
                   5380:     }
1.706     raeburn  5381:     return ($outcome,$perm_reqd,$conditions);
                   5382: }
                   5383: 
                   5384: sub auto_checkphotos {
                   5385:     my ($uname,$udom,$pid) = @_;
                   5386:     my $homeserver = &homeserver($uname,$udom);
                   5387:     my ($result,$resulttype);
                   5388:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5389: 				   &escape($uname).':'.&escape($pid),
                   5390: 				   $homeserver));
1.709     albertel 5391:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5392: 	return (undef,undef);
                   5393:     }
1.706     raeburn  5394:     if ($outcome) {
                   5395:         ($result,$resulttype) = split(/:/,$outcome);
                   5396:     } 
                   5397:     return ($result,$resulttype);
                   5398: }
                   5399: 
                   5400: sub auto_photochoice {
                   5401:     my ($cnum,$cdom) = @_;
                   5402:     my $homeserver = &homeserver($cnum,$cdom);
                   5403:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5404: 						       &escape($cdom),
                   5405: 						       $homeserver)));
1.709     albertel 5406:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5407: 	return (undef,undef);
                   5408:     }
1.706     raeburn  5409:     return ($update,$comment);
                   5410: }
                   5411: 
                   5412: sub auto_photoupdate {
                   5413:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5414:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5415:     my $host=&hostname($homeserver);
1.706     raeburn  5416:     my $cmd = '';
                   5417:     my $maxtries = 1;
1.800     albertel 5418:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5419:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5420:     }
                   5421:     $cmd =~ s/%%$//;
                   5422:     $cmd = &escape($cmd);
                   5423:     my $query = 'institutionalphotos';
                   5424:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5425:     unless ($queryid=~/^\Q$host\E\_/) {
                   5426:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5427:         return 'error: '.$queryid;
                   5428:     }
                   5429:     my $reply = &get_query_reply($queryid);
                   5430:     my $tries = 1;
                   5431:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5432:         $reply = &get_query_reply($queryid);
                   5433:         $tries ++;
                   5434:     }
                   5435:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5436:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5437:     } else {
                   5438:         my @responses = split(/:/,$reply);
                   5439:         my $outcome = shift(@responses); 
                   5440:         foreach my $item (@responses) {
                   5441:             my ($key,$value) = split(/=/,$item);
                   5442:             $$photo{$key} = $value;
                   5443:         }
                   5444:         return $outcome;
                   5445:     }
                   5446:     return 'error';
                   5447: }
                   5448: 
1.521     raeburn  5449: sub auto_instcode_format {
1.793     albertel 5450:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5451: 	$cat_order) = @_;
1.521     raeburn  5452:     my $courses = '';
1.772     raeburn  5453:     my @homeservers;
1.521     raeburn  5454:     if ($caller eq 'global') {
1.841     albertel 5455: 	my %servers = &get_servers($codedom,'library');
                   5456: 	foreach my $tryserver (keys(%servers)) {
                   5457: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5458: 		push(@homeservers,$tryserver);
                   5459: 	    }
1.584     raeburn  5460:         }
1.521     raeburn  5461:     } else {
1.772     raeburn  5462:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5463:     }
1.793     albertel 5464:     foreach my $code (keys(%{$instcodes})) {
                   5465:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5466:     }
                   5467:     chop($courses);
1.772     raeburn  5468:     my $ok_response = 0;
                   5469:     my $response;
                   5470:     while (@homeservers > 0 && $ok_response == 0) {
                   5471:         my $server = shift(@homeservers); 
                   5472:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5473:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5474:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5475: 		split(/:/,$response);
1.772     raeburn  5476:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5477:             push(@{$codetitles},&str2array($codetitles_str));
                   5478:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5479:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5480:             $ok_response = 1;
                   5481:         }
                   5482:     }
                   5483:     if ($ok_response) {
1.521     raeburn  5484:         return 'ok';
1.772     raeburn  5485:     } else {
                   5486:         return $response;
1.521     raeburn  5487:     }
                   5488: }
                   5489: 
1.792     raeburn  5490: sub auto_instcode_defaults {
                   5491:     my ($domain,$returnhash,$code_order) = @_;
                   5492:     my @homeservers;
1.841     albertel 5493: 
                   5494:     my %servers = &get_servers($domain,'library');
                   5495:     foreach my $tryserver (keys(%servers)) {
                   5496: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5497: 	    push(@homeservers,$tryserver);
                   5498: 	}
1.792     raeburn  5499:     }
1.841     albertel 5500: 
1.792     raeburn  5501:     my $response;
1.841     albertel 5502:     foreach my $server (@homeservers) {
1.792     raeburn  5503:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5504:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5505: 	
                   5506: 	foreach my $pair (split(/\&/,$response)) {
                   5507: 	    my ($name,$value)=split(/\=/,$pair);
                   5508: 	    if ($name eq 'code_order') {
                   5509: 		@{$code_order} = split(/\&/,&unescape($value));
                   5510: 	    } else {
                   5511: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5512: 	    }
                   5513: 	}
                   5514: 	return 'ok';
1.792     raeburn  5515:     }
1.841     albertel 5516: 
                   5517:     return $response;
1.792     raeburn  5518: } 
                   5519: 
1.777     albertel 5520: sub auto_validate_class_sec {
1.918     raeburn  5521:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5522:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5523:     my $ownerlist;
                   5524:     if (ref($owners) eq 'ARRAY') {
                   5525:         $ownerlist = join(',',@{$owners});
                   5526:     } else {
                   5527:         $ownerlist = $owners;
                   5528:     }
1.773     raeburn  5529:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5530:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5531:     return $response;
                   5532: }
                   5533: 
1.679     raeburn  5534: # ------------------------------------------------------- Course Group routines
                   5535: 
                   5536: sub get_coursegroups {
1.809     raeburn  5537:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5538:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5539: }
                   5540: 
1.679     raeburn  5541: sub modify_coursegroup {
                   5542:     my ($cdom,$cnum,$groupsettings) = @_;
                   5543:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5544: }
                   5545: 
1.809     raeburn  5546: sub toggle_coursegroup_status {
                   5547:     my ($cdom,$cnum,$group,$action) = @_;
                   5548:     my ($from_namespace,$to_namespace);
                   5549:     if ($action eq 'delete') {
                   5550:         $from_namespace = 'coursegroups';
                   5551:         $to_namespace = 'deleted_groups';
                   5552:     } else {
                   5553:         $from_namespace = 'deleted_groups';
                   5554:         $to_namespace = 'coursegroups';
                   5555:     }
                   5556:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5557:     if (my $tmp = &error(%curr_group)) {
                   5558:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5559:         return ('read error',$tmp);
                   5560:     } else {
                   5561:         my %savedsettings = %curr_group; 
1.809     raeburn  5562:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5563:         my $deloutcome;
                   5564:         if ($result eq 'ok') {
1.809     raeburn  5565:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5566:         } else {
                   5567:             return ('write error',$result);
                   5568:         }
                   5569:         if ($deloutcome eq 'ok') {
                   5570:             return 'ok';
                   5571:         } else {
                   5572:             return ('delete error',$deloutcome);
                   5573:         }
                   5574:     }
                   5575: }
                   5576: 
1.679     raeburn  5577: sub modify_group_roles {
1.957     raeburn  5578:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5579:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5580:     my $role = 'gr/'.&escape($userprivs);
                   5581:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5582:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5583:     if ($result eq 'ok') {
                   5584:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5585:     }
1.679     raeburn  5586:     return $result;
                   5587: }
                   5588: 
                   5589: sub modify_coursegroup_membership {
                   5590:     my ($cdom,$cnum,$membership) = @_;
                   5591:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5592:     return $result;
                   5593: }
                   5594: 
1.682     raeburn  5595: sub get_active_groups {
                   5596:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5597:     my $now = time;
                   5598:     my %groups = ();
                   5599:     foreach my $key (keys(%env)) {
1.811     albertel 5600:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5601:             my ($start,$end) = split(/\./,$env{$key});
                   5602:             if (($end!=0) && ($end<$now)) { next; }
                   5603:             if (($start!=0) && ($start>$now)) { next; }
                   5604:             if ($1 eq $cdom && $2 eq $cnum) {
                   5605:                 $groups{$3} = $env{$key} ;
                   5606:             }
                   5607:         }
                   5608:     }
                   5609:     return %groups;
                   5610: }
                   5611: 
1.683     raeburn  5612: sub get_group_membership {
                   5613:     my ($cdom,$cnum,$group) = @_;
                   5614:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5615: }
                   5616: 
                   5617: sub get_users_groups {
                   5618:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5619:     my @usersgroups;
1.683     raeburn  5620:     my $cachetime=1800;
                   5621: 
                   5622:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5623:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5624:     if (defined($cached)) {
1.734     albertel 5625:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5626:     } else {  
                   5627:         $grouplist = '';
1.816     raeburn  5628:         my $courseurl = &courseid_to_courseurl($courseid);
                   5629:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5630:         my $access_end = $env{'course.'.$courseid.
                   5631:                               '.default_enrollment_end_date'};
                   5632:         my $now = time;
                   5633:         foreach my $key (keys(%roleshash)) {
                   5634:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5635:                 my $group = $1;
                   5636:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5637:                     my $start = $2;
                   5638:                     my $end = $1;
                   5639:                     if ($start == -1) { next; } # deleted from group
                   5640:                     if (($start!=0) && ($start>$now)) { next; }
                   5641:                     if (($end!=0) && ($end<$now)) {
                   5642:                         if ($access_end && $access_end < $now) {
                   5643:                             if ($access_end - $end < 86400) {
                   5644:                                 push(@usersgroups,$group);
1.733     raeburn  5645:                             }
                   5646:                         }
1.817     raeburn  5647:                         next;
1.733     raeburn  5648:                     }
1.817     raeburn  5649:                     push(@usersgroups,$group);
1.683     raeburn  5650:                 }
                   5651:             }
                   5652:         }
1.817     raeburn  5653:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5654:         $grouplist = join(':',@usersgroups);
                   5655:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5656:     }
1.733     raeburn  5657:     return @usersgroups;
1.683     raeburn  5658: }
                   5659: 
                   5660: sub devalidate_getgroups_cache {
                   5661:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5662:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5663: 
1.683     raeburn  5664:     my $hashid="$udom:$uname:$courseid";
                   5665:     &devalidate_cache_new('getgroups',$hashid);
                   5666: }
                   5667: 
1.12      www      5668: # ------------------------------------------------------------------ Plain Text
                   5669: 
                   5670: sub plaintext {
1.742     raeburn  5671:     my ($short,$type,$cid) = @_;
1.758     albertel 5672:     if ($short =~ /^cr/) {
                   5673: 	return (split('/',$short))[-1];
                   5674:     }
1.742     raeburn  5675:     if (!defined($cid)) {
                   5676:         $cid = $env{'request.course.id'};
                   5677:     }
                   5678:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5679:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5680:                                           '.plaintext'});
                   5681:     }
                   5682:     my %rolenames = (
                   5683:                       Course => 'std',
                   5684:                       Group => 'alt1',
                   5685:                     );
                   5686:     if (defined($type) && 
                   5687:          defined($rolenames{$type}) && 
                   5688:          defined($prp{$short}{$rolenames{$type}})) {
                   5689:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5690:     } else {
                   5691:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5692:     }
1.12      www      5693: }
                   5694: 
                   5695: # ----------------------------------------------------------------- Assign Role
                   5696: 
                   5697: sub assignrole {
1.957     raeburn  5698:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5699:         $context)=@_;
1.21      www      5700:     my $mrole;
                   5701:     if ($role =~ /^cr\//) {
1.393     www      5702:         my $cwosec=$url;
1.811     albertel 5703:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5704: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5705:            &logthis('Refused custom assignrole: '.
                   5706:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5707: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5708:            return 'refused'; 
                   5709:         }
1.21      www      5710:         $mrole='cr';
1.678     raeburn  5711:     } elsif ($role =~ /^gr\//) {
                   5712:         my $cwogrp=$url;
1.811     albertel 5713:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5714:         unless (&allowed('mdg',$cwogrp)) {
                   5715:             &logthis('Refused group assignrole: '.
                   5716:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5717:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5718:             return 'refused';
                   5719:         }
                   5720:         $mrole='gr';
1.21      www      5721:     } else {
1.82      www      5722:         my $cwosec=$url;
1.811     albertel 5723:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5724:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5725:             my $refused;
                   5726:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5727:                 if (!(&allowed('c'.$role,$url))) {
                   5728:                     $refused = 1;
                   5729:                 }
                   5730:             } else {
                   5731:                 $refused = 1;
                   5732:             }
1.947     raeburn  5733:             if ($refused) {
                   5734:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5735:                     $refused = '';
                   5736:                 } else {
                   5737:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5738:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5739: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5740:                     return 'refused';
                   5741:                 }
1.932     raeburn  5742:             }
1.104     www      5743:         }
1.21      www      5744:         $mrole=$role;
                   5745:     }
1.620     albertel 5746:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5747:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5748:     if ($end) { $command.='_'.$end; }
1.21      www      5749:     if ($start) {
                   5750: 	if ($end) { 
1.81      www      5751:            $command.='_'.$start; 
1.21      www      5752:         } else {
1.81      www      5753:            $command.='_0_'.$start;
1.21      www      5754:         }
                   5755:     }
1.739     raeburn  5756:     my $origstart = $start;
                   5757:     my $origend = $end;
1.957     raeburn  5758:     my $delflag;
1.357     www      5759: # actually delete
                   5760:     if ($deleteflag) {
1.373     www      5761: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5762: # modify command to delete the role
1.620     albertel 5763:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5764:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5765: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5766: # set start and finish to negative values for userrolelog
                   5767:            $start=-1;
                   5768:            $end=-1;
1.957     raeburn  5769:            $delflag = 1;
1.357     www      5770:         }
                   5771:     }
                   5772: # send command
1.349     www      5773:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5774: # log new user role if status is ok
1.349     www      5775:     if ($answer eq 'ok') {
1.663     raeburn  5776: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5777: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5778:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5779:         unless ($role =~ /^gr/) {
                   5780:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5781:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5782:         }
1.349     www      5783:     }
                   5784:     return $answer;
1.169     harris41 5785: }
                   5786: 
                   5787: # -------------------------------------------------- Modify user authentication
1.197     www      5788: # Overrides without validation
                   5789: 
1.169     harris41 5790: sub modifyuserauth {
                   5791:     my ($udom,$uname,$umode,$upass)=@_;
                   5792:     my $uhome=&homeserver($uname,$udom);
1.197     www      5793:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5794:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5795:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5796:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5797:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5798: 		     &escape($upass),$uhome);
1.620     albertel 5799:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5800:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5801:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5802:     &log($udom,,$uname,$uhome,
1.620     albertel 5803:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5804:                                      $env{'user.name'}.', '.$umode.
1.197     www      5805:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5806:     unless ($reply eq 'ok') {
1.197     www      5807:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5808: 	return 'error: '.$reply;
                   5809:     }   
1.170     harris41 5810:     return 'ok';
1.80      www      5811: }
                   5812: 
1.81      www      5813: # --------------------------------------------------------------- Modify a user
1.80      www      5814: 
1.81      www      5815: sub modifyuser {
1.206     matthew  5816:     my ($udom,    $uname, $uid,
                   5817:         $umode,   $upass, $first,
                   5818:         $middle,  $last,  $gene,
1.963     raeburn  5819:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5820:     $udom= &LONCAPA::clean_domain($udom);
                   5821:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5822:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5823:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5824: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5825:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5826:                                      ' desiredhome not specified'). 
1.620     albertel 5827:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5828:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5829:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5830: # ----------------------------------------------------------------- Create User
1.406     albertel 5831:     if (($uhome eq 'no_host') && 
                   5832: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5833:         my $unhome='';
1.844     albertel 5834:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5835:             $unhome = $desiredhome;
1.620     albertel 5836: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5837: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5838:         } else { # load balancing routine for determining $unhome
1.81      www      5839:             my $loadm=10000000;
1.841     albertel 5840: 	    my %servers = &get_servers($udom,'library');
                   5841: 	    foreach my $tryserver (keys(%servers)) {
                   5842: 		my $answer=reply('load',$tryserver);
                   5843: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5844: 		    $loadm=$answer;
                   5845: 		    $unhome=$tryserver;
                   5846: 		}
1.80      www      5847: 	    }
                   5848:         }
                   5849:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5850: 	    return 'error: unable to find a home server for '.$uname.
                   5851:                    ' in domain '.$udom;
1.80      www      5852:         }
                   5853:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5854:                          &escape($upass),$unhome);
                   5855: 	unless ($reply eq 'ok') {
                   5856:             return 'error: '.$reply;
                   5857:         }   
1.230     stredwic 5858:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5859:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5860: 	    return 'error: unable verify users home machine.';
1.80      www      5861:         }
1.209     matthew  5862:     }   # End of creation of new user
1.80      www      5863: # ---------------------------------------------------------------------- Add ID
                   5864:     if ($uid) {
                   5865:        $uid=~tr/A-Z/a-z/;
                   5866:        my %uidhash=&idrget($udom,$uname);
1.196     www      5867:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5868:          && (!$forceid)) {
1.80      www      5869: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5870: 	      return 'error: user id "'.$uid.'" does not match '.
                   5871:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5872:           }
                   5873:        } else {
                   5874: 	  &idput($udom,($uname => $uid));
                   5875:        }
                   5876:     }
                   5877: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5878:     my @tmp=&get('environment',
1.899     raeburn  5879: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5880:                     'permanentemail','inststatus'],
1.134     albertel 5881: 		   $udom,$uname);
1.313     matthew  5882:     my %names;
                   5883:     if ($tmp[0] =~ m/^error:.*/) { 
                   5884:         %names=(); 
                   5885:     } else {
                   5886:         %names = @tmp;
                   5887:     }
1.388     www      5888: #
                   5889: # Make sure to not trash student environment if instructor does not bother
                   5890: # to supply name and email information
                   5891: #
                   5892:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5893:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5894:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5895:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5896:     if ($email) {
                   5897:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5898:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5899:     }
1.899     raeburn  5900:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5901:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5902:     my $reply = &put('environment', \%names, $udom,$uname);
                   5903:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5904:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5905:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5906:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5907:                  $umode.', '.$first.', '.$middle.', '.
                   5908: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5909:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5910:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5911:     } else {
                   5912:         $logmsg .= ' during self creation';
                   5913:     }
                   5914:     &logthis($logmsg);
1.134     albertel 5915:     return 'ok';
1.80      www      5916: }
                   5917: 
1.81      www      5918: # -------------------------------------------------------------- Modify student
1.80      www      5919: 
1.81      www      5920: sub modifystudent {
                   5921:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5922:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5923:         $selfenroll,$context)=@_;
1.455     albertel 5924:     if (!$cid) {
1.620     albertel 5925: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5926: 	    return 'not_in_class';
                   5927: 	}
1.80      www      5928:     }
                   5929: # --------------------------------------------------------------- Make the user
1.81      www      5930:     my $reply=&modifyuser
1.209     matthew  5931: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5932:          $desiredhome,$email);
1.80      www      5933:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5934:     # This will cause &modify_student_enrollment to get the uid from the
                   5935:     # students environment
                   5936:     $uid = undef if (!$forceid);
1.455     albertel 5937:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5938: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5939:     return $reply;
                   5940: }
                   5941: 
                   5942: sub modify_student_enrollment {
1.957     raeburn  5943:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5944:     my ($cdom,$cnum,$chome);
                   5945:     if (!$cid) {
1.620     albertel 5946: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5947: 	    return 'not_in_class';
                   5948: 	}
1.620     albertel 5949: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5950: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5951:     } else {
                   5952: 	($cdom,$cnum)=split(/_/,$cid);
                   5953:     }
1.620     albertel 5954:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5955:     if (!$chome) {
1.457     raeburn  5956: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5957:     }
1.455     albertel 5958:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5959:     # Make sure the user exists
1.81      www      5960:     my $uhome=&homeserver($uname,$udom);
                   5961:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5962: 	return 'error: no such user';
                   5963:     }
1.297     matthew  5964:     # Get student data if we were not given enough information
                   5965:     if (!defined($first)  || $first  eq '' || 
                   5966:         !defined($last)   || $last   eq '' || 
                   5967:         !defined($uid)    || $uid    eq '' || 
                   5968:         !defined($middle) || $middle eq '' || 
                   5969:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5970:         # They did not supply us with enough data to enroll the student, so
                   5971:         # we need to pick up more information.
1.297     matthew  5972:         my %tmp = &get('environment',
1.294     matthew  5973:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5974:                        ,$udom,$uname);
                   5975: 
1.800     albertel 5976:         #foreach my $key (keys(%tmp)) {
                   5977:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5978:         #}
1.294     matthew  5979:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5980:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5981:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5982:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5983:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5984:     }
1.556     albertel 5985:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5986:     my $reply=cput('classlist',
                   5987: 		   {"$uname:$udom" => 
1.515     raeburn  5988: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5989: 		   $cdom,$cnum);
1.81      www      5990:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5991: 	return 'error: '.$reply;
1.652     albertel 5992:     } else {
                   5993: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5994:     }
1.297     matthew  5995:     # Add student role to user
1.83      www      5996:     my $uurl='/'.$cid;
1.81      www      5997:     $uurl=~s/\_/\//g;
                   5998:     if ($usec) {
                   5999: 	$uurl.='/'.$usec;
                   6000:     }
1.957     raeburn  6001:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6002: }
                   6003: 
1.556     albertel 6004: sub format_name {
                   6005:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6006:     my $name;
                   6007:     if ($first ne 'lastname') {
                   6008: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6009:     } else {
                   6010: 	if ($lastname=~/\S/) {
                   6011: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6012: 	    $name=~s/\s+,/,/;
                   6013: 	} else {
                   6014: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6015: 	}
                   6016:     }
                   6017:     $name=~s/^\s+//;
                   6018:     $name=~s/\s+$//;
                   6019:     $name=~s/\s+/ /g;
                   6020:     return $name;
                   6021: }
                   6022: 
1.84      www      6023: # ------------------------------------------------- Write to course preferences
                   6024: 
                   6025: sub writecoursepref {
                   6026:     my ($courseid,%prefs)=@_;
                   6027:     $courseid=~s/^\///;
                   6028:     $courseid=~s/\_/\//g;
                   6029:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6030:     my $chome=homeserver($cnum,$cdomain);
                   6031:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6032: 	return 'error: no such course';
                   6033:     }
                   6034:     my $cstring='';
1.800     albertel 6035:     foreach my $pref (keys(%prefs)) {
                   6036: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6037:     }
1.84      www      6038:     $cstring=~s/\&$//;
                   6039:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6040: }
                   6041: 
                   6042: # ---------------------------------------------------------- Make/modify course
                   6043: 
                   6044: sub createcourse {
1.741     raeburn  6045:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6046:         $course_owner,$crstype)=@_;
1.84      www      6047:     $url=&declutter($url);
                   6048:     my $cid='';
1.264     matthew  6049:     unless (&allowed('ccc',$udom)) {
1.84      www      6050:         return 'refused';
                   6051:     }
                   6052: # ------------------------------------------------------------------- Create ID
1.674     www      6053:    my $uname=int(1+rand(9)).
                   6054:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6055:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6056:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6057: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6058:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6059:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6060:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6061:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6062:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6063:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6064:            return 'error: unable to generate unique course-ID';
                   6065:        } 
                   6066:    }
1.264     matthew  6067: # ------------------------------------------------ Check supplied server name
1.620     albertel 6068:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6069:     if (! &is_library($course_server)) {
1.264     matthew  6070:         return 'error:bad server name '.$course_server;
                   6071:     }
1.84      www      6072: # ------------------------------------------------------------- Make the course
                   6073:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6074:                       $course_server);
1.84      www      6075:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6076:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6077:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6078: 	return 'error: no such course';
                   6079:     }
1.271     www      6080: # ----------------------------------------------------------------- Course made
1.516     raeburn  6081: # log existence
1.918     raeburn  6082:     my $newcourse = {
                   6083:                     $udom.'_'.$uname => {
1.921     raeburn  6084:                                      description => $description,
                   6085:                                      inst_code   => $inst_code,
                   6086:                                      owner       => $course_owner,
                   6087:                                      type        => $crstype,
1.918     raeburn  6088:                                                 },
                   6089:                     };
1.921     raeburn  6090:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6091: # set toplevel url
1.271     www      6092:     my $topurl=$url;
                   6093:     unless ($nonstandard) {
                   6094: # ------------------------------------------ For standard courses, make top url
                   6095:         my $mapurl=&clutter($url);
1.278     www      6096:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6097:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6098: <map>
                   6099: <resource id="1" type="start"></resource>
                   6100: <resource id="2" src="$mapurl"></resource>
                   6101: <resource id="3" type="finish"></resource>
                   6102: <link index="1" from="1" to="2"></link>
                   6103: <link index="2" from="2" to="3"></link>
                   6104: </map>
                   6105: ENDINITMAP
                   6106:         $topurl=&declutter(
1.638     albertel 6107:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6108:                           );
                   6109:     }
                   6110: # ----------------------------------------------------------- Write preferences
1.84      www      6111:     &writecoursepref($udom.'_'.$uname,
                   6112:                      ('description' => $description,
1.271     www      6113:                       'url'         => $topurl));
1.84      www      6114:     return '/'.$udom.'/'.$uname;
                   6115: }
                   6116: 
1.813     albertel 6117: sub is_course {
                   6118:     my ($cdom,$cnum) = @_;
                   6119:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6120: 				undef,'.');
1.813     albertel 6121:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6122:         return 1;
                   6123:     }
                   6124:     return 0;
                   6125: }
                   6126: 
1.21      www      6127: # ---------------------------------------------------------- Assign Custom Role
                   6128: 
                   6129: sub assigncustomrole {
1.957     raeburn  6130:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6131:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6132:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6133: }
                   6134: 
                   6135: # ----------------------------------------------------------------- Revoke Role
                   6136: 
                   6137: sub revokerole {
1.957     raeburn  6138:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6139:     my $now=time;
1.965     raeburn  6140:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6141: }
                   6142: 
                   6143: # ---------------------------------------------------------- Revoke Custom Role
                   6144: 
                   6145: sub revokecustomrole {
1.957     raeburn  6146:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6147:     my $now=time;
1.357     www      6148:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6149:            $deleteflag,$selfenroll,$context);
1.17      www      6150: }
                   6151: 
1.533     banghart 6152: # ------------------------------------------------------------ Disk usage
1.535     albertel 6153: sub diskusage {
1.955     raeburn  6154:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6155:     $directorypath =~ s/\/$//;
                   6156:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6157:                        .&escape($getpropath).':'.&escape($uname).':'
                   6158:                        .&escape($udom),homeserver($uname,$udom));
                   6159:     if ($listing eq 'unknown_cmd') {
                   6160:         if ($getpropath) {
                   6161:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6162:         }
                   6163:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6164:     }
1.514     albertel 6165:     return $listing;
1.512     banghart 6166: }
                   6167: 
1.566     banghart 6168: sub is_locked {
                   6169:     my ($file_name, $domain, $user) = @_;
                   6170:     my @check;
                   6171:     my $is_locked;
                   6172:     push @check, $file_name;
1.613     albertel 6173:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6174: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6175:     my ($tmp)=keys(%locked);
                   6176:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6177:     
1.566     banghart 6178:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6179:         $is_locked = 'false';
                   6180:         foreach my $entry (@{$locked{$file_name}}) {
                   6181:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6182:                $is_locked = 'true';
                   6183:                last;
1.745     raeburn  6184:            }
                   6185:        }
1.566     banghart 6186:     } else {
                   6187:         $is_locked = 'false';
                   6188:     }
                   6189: }
                   6190: 
1.759     albertel 6191: sub declutter_portfile {
                   6192:     my ($file) = @_;
1.833     albertel 6193:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6194:     return $file;
                   6195: }
                   6196: 
1.559     banghart 6197: # ------------------------------------------------------------- Mark as Read Only
                   6198: 
                   6199: sub mark_as_readonly {
                   6200:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6201:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6202:     my ($tmp)=keys(%current_permissions);
                   6203:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6204:     foreach my $file (@{$files}) {
1.759     albertel 6205: 	$file = &declutter_portfile($file);
1.561     banghart 6206:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6207:     }
1.613     albertel 6208:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6209:     return;
                   6210: }
                   6211: 
1.572     banghart 6212: # ------------------------------------------------------------Save Selected Files
                   6213: 
                   6214: sub save_selected_files {
                   6215:     my ($user, $path, @files) = @_;
                   6216:     my $filename = $user."savedfiles";
1.573     banghart 6217:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6218:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6219:     foreach my $file (@files) {
1.620     albertel 6220:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6221:     }
                   6222:     foreach my $file (@other_files) {
1.574     banghart 6223:         print (OUT $file."\n");
1.572     banghart 6224:     }
1.574     banghart 6225:     close (OUT);
1.572     banghart 6226:     return 'ok';
                   6227: }
                   6228: 
1.574     banghart 6229: sub clear_selected_files {
                   6230:     my ($user) = @_;
                   6231:     my $filename = $user."savedfiles";
                   6232:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6233:     print (OUT undef);
                   6234:     close (OUT);
                   6235:     return ("ok");    
                   6236: }
                   6237: 
1.572     banghart 6238: sub files_in_path {
                   6239:     my ($user, $path) = @_;
                   6240:     my $filename = $user."savedfiles";
                   6241:     my %return_files;
1.574     banghart 6242:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6243:     while (my $line_in = <IN>) {
1.574     banghart 6244:         chomp ($line_in);
                   6245:         my @paths_and_file = split (m!/!, $line_in);
                   6246:         my $file_part = pop (@paths_and_file);
                   6247:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6248:         $path_part.='/';
                   6249:         my $path_and_file = $path_part.$file_part;
                   6250:         if ($path_part eq $path) {
                   6251:             $return_files{$file_part}= 'selected';
                   6252:         }
                   6253:     }
1.574     banghart 6254:     close (IN);
                   6255:     return (\%return_files);
1.572     banghart 6256: }
                   6257: 
                   6258: # called in portfolio select mode, to show files selected NOT in current directory
                   6259: sub files_not_in_path {
                   6260:     my ($user, $path) = @_;
                   6261:     my $filename = $user."savedfiles";
                   6262:     my @return_files;
                   6263:     my $path_part;
1.800     albertel 6264:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6265:     while (my $line = <IN>) {
1.572     banghart 6266:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6267:         my @paths_and_file = split(m|/|, $line);
                   6268:         my $file_part = pop(@paths_and_file);
                   6269:         chomp($file_part);
                   6270:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6271:         $path_part .= '/';
                   6272:         my $path_and_file = $path_part.$file_part;
                   6273:         if ($path_part ne $path) {
1.800     albertel 6274:             push(@return_files, ($path_and_file));
1.572     banghart 6275:         }
                   6276:     }
1.800     albertel 6277:     close(OUT);
1.574     banghart 6278:     return (@return_files);
1.572     banghart 6279: }
                   6280: 
1.745     raeburn  6281: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6282: 
1.745     raeburn  6283: sub get_portfile_permissions {
                   6284:     my ($domain,$user) = @_;
1.613     albertel 6285:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6286:     my ($tmp)=keys(%current_permissions);
                   6287:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6288:     return \%current_permissions;
                   6289: }
                   6290: 
                   6291: #---------------------------------------------Get portfolio file access controls
                   6292: 
1.749     raeburn  6293: sub get_access_controls {
1.745     raeburn  6294:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6295:     my %access;
                   6296:     my $real_file = $file;
                   6297:     $file =~ s/\.meta$//;
1.745     raeburn  6298:     if (defined($file)) {
1.749     raeburn  6299:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6300:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6301:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6302:             }
                   6303:         }
1.745     raeburn  6304:     } else {
1.749     raeburn  6305:         foreach my $key (keys(%{$current_permissions})) {
                   6306:             if ($key =~ /\0accesscontrol$/) {
                   6307:                 if (defined($group)) {
                   6308:                     if ($key !~ m-^\Q$group\E/-) {
                   6309:                         next;
                   6310:                     }
                   6311:                 }
                   6312:                 my ($fullpath) = split(/\0/,$key);
                   6313:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6314:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6315:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6316:                     }
                   6317:                 }
                   6318:             }
                   6319:         }
                   6320:     }
                   6321:     return %access;
                   6322: }
                   6323: 
                   6324: sub modify_access_controls {
                   6325:     my ($file_name,$changes,$domain,$user)=@_;
                   6326:     my ($outcome,$deloutcome);
                   6327:     my %store_permissions;
                   6328:     my %new_values;
                   6329:     my %new_control;
                   6330:     my %translation;
                   6331:     my @deletions = ();
                   6332:     my $now = time;
                   6333:     if (exists($$changes{'activate'})) {
                   6334:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6335:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6336:             my $numnew = scalar(@newitems);
                   6337:             for (my $i=0; $i<$numnew; $i++) {
                   6338:                 my $newkey = $newitems[$i];
                   6339:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6340:                 if ($newkey =~ /^\d+:/) { 
                   6341:                     $newkey =~ s/^(\d+)/$newid/;
                   6342:                     $translation{$1} = $newid;
                   6343:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6344:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6345:                     $translation{$1} = $newid;
                   6346:                 }
1.749     raeburn  6347:                 $new_values{$file_name."\0".$newkey} = 
                   6348:                                           $$changes{'activate'}{$newitems[$i]};
                   6349:                 $new_control{$newkey} = $now;
                   6350:             }
                   6351:         }
                   6352:     }
                   6353:     my %todelete;
                   6354:     my %changed_items;
                   6355:     foreach my $action ('delete','update') {
                   6356:         if (exists($$changes{$action})) {
                   6357:             if (ref($$changes{$action}) eq 'HASH') {
                   6358:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6359:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6360:                     if ($action eq 'delete') { 
                   6361:                         $todelete{$itemnum} = 1;
                   6362:                     } else {
                   6363:                         $changed_items{$itemnum} = $key;
                   6364:                     }
                   6365:                 }
1.745     raeburn  6366:             }
                   6367:         }
1.749     raeburn  6368:     }
                   6369:     # get lock on access controls for file.
                   6370:     my $lockhash = {
                   6371:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6372:                                                        ':'.$env{'user.domain'},
                   6373:                    }; 
                   6374:     my $tries = 0;
                   6375:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6376:    
                   6377:     while (($gotlock ne 'ok') && $tries <3) {
                   6378:         $tries ++;
                   6379:         sleep 1;
                   6380:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6381:     }
                   6382:     if ($gotlock eq 'ok') {
                   6383:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6384:         my ($tmp)=keys(%curr_permissions);
                   6385:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6386:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6387:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6388:             if (ref($curr_controls) eq 'HASH') {
                   6389:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6390:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6391:                     if (defined($todelete{$itemnum})) {
                   6392:                         push(@deletions,$file_name."\0".$control_item);
                   6393:                     } else {
                   6394:                         if (defined($changed_items{$itemnum})) {
                   6395:                             $new_control{$changed_items{$itemnum}} = $now;
                   6396:                             push(@deletions,$file_name."\0".$control_item);
                   6397:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6398:                         } else {
                   6399:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6400:                         }
                   6401:                     }
1.745     raeburn  6402:                 }
                   6403:             }
                   6404:         }
1.970     raeburn  6405:         my ($group);
                   6406:         if (&is_course($domain,$user)) {
                   6407:             ($group,my $file) = split(/\//,$file_name,2);
                   6408:         }
1.749     raeburn  6409:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6410:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6411:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6412:         #  remove lock
                   6413:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6414:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6415:         my $sqlresult =
1.970     raeburn  6416:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6417:                                     $group);
1.749     raeburn  6418:     } else {
                   6419:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6420:     }
1.749     raeburn  6421:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6422: }
                   6423: 
1.827     raeburn  6424: sub make_public_indefinitely {
                   6425:     my ($requrl) = @_;
                   6426:     my $now = time;
                   6427:     my $action = 'activate';
                   6428:     my $aclnum = 0;
                   6429:     if (&is_portfolio_url($requrl)) {
                   6430:         my (undef,$udom,$unum,$file_name,$group) =
                   6431:             &parse_portfolio_url($requrl);
                   6432:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6433:         my %access_controls = &get_access_controls($current_perms,
                   6434:                                                    $group,$file_name);
                   6435:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6436:             my ($num,$scope,$end,$start) = 
                   6437:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6438:             if ($scope eq 'public') {
                   6439:                 if ($start <= $now && $end == 0) {
                   6440:                     $action = 'none';
                   6441:                 } else {
                   6442:                     $action = 'update';
                   6443:                     $aclnum = $num;
                   6444:                 }
                   6445:                 last;
                   6446:             }
                   6447:         }
                   6448:         if ($action eq 'none') {
                   6449:              return 'ok';
                   6450:         } else {
                   6451:             my %changes;
                   6452:             my $newend = 0;
                   6453:             my $newstart = $now;
                   6454:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6455:             $changes{$action}{$newkey} = {
                   6456:                 type => 'public',
                   6457:                 time => {
                   6458:                     start => $newstart,
                   6459:                     end   => $newend,
                   6460:                 },
                   6461:             };
                   6462:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6463:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6464:             return $outcome;
                   6465:         }
                   6466:     } else {
                   6467:         return 'invalid';
                   6468:     }
                   6469: }
                   6470: 
1.745     raeburn  6471: #------------------------------------------------------Get Marked as Read Only
                   6472: 
                   6473: sub get_marked_as_readonly {
                   6474:     my ($domain,$user,$what,$group) = @_;
                   6475:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6476:     my @readonly_files;
1.629     banghart 6477:     my $cmp1=$what;
                   6478:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6479:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6480:         if (defined($group)) {
                   6481:             if ($file_name !~ m-^\Q$group\E/-) {
                   6482:                 next;
                   6483:             }
                   6484:         }
1.561     banghart 6485:         if (ref($value) eq "ARRAY"){
                   6486:             foreach my $stored_what (@{$value}) {
1.629     banghart 6487:                 my $cmp2=$stored_what;
1.759     albertel 6488:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6489:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6490:                 }
1.629     banghart 6491:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6492:                     push(@readonly_files, $file_name);
1.745     raeburn  6493:                     last;
1.563     banghart 6494:                 } elsif (!defined($what)) {
                   6495:                     push(@readonly_files, $file_name);
1.745     raeburn  6496:                     last;
1.561     banghart 6497:                 }
                   6498:             }
1.745     raeburn  6499:         }
1.561     banghart 6500:     }
                   6501:     return @readonly_files;
                   6502: }
1.577     banghart 6503: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6504: 
1.577     banghart 6505: sub get_marked_as_readonly_hash {
1.745     raeburn  6506:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6507:     my %readonly_files;
1.745     raeburn  6508:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6509:         if (defined($group)) {
                   6510:             if ($file_name !~ m-^\Q$group\E/-) {
                   6511:                 next;
                   6512:             }
                   6513:         }
1.577     banghart 6514:         if (ref($value) eq "ARRAY"){
                   6515:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6516:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6517:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6518:                         if ($lock_descriptor eq 'graded') {
                   6519:                             $readonly_files{$file_name} = 'graded';
                   6520:                         } elsif ($lock_descriptor eq 'handback') {
                   6521:                             $readonly_files{$file_name} = 'handback';
                   6522:                         } else {
                   6523:                             if (!exists($readonly_files{$file_name})) {
                   6524:                                 $readonly_files{$file_name} = 'locked';
                   6525:                             }
                   6526:                         }
1.745     raeburn  6527:                     }
1.750     banghart 6528:                 } 
1.577     banghart 6529:             }
                   6530:         } 
                   6531:     }
                   6532:     return %readonly_files;
                   6533: }
1.559     banghart 6534: # ------------------------------------------------------------ Unmark as Read Only
                   6535: 
                   6536: sub unmark_as_readonly {
1.629     banghart 6537:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6538:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6539:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6540:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6541:     my $symb_crs = $what;
                   6542:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6543:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6544:     my ($tmp)=keys(%current_permissions);
                   6545:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6546:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6547:     foreach my $file (@readonly_files) {
1.759     albertel 6548: 	my $clean_file = &declutter_portfile($file);
                   6549: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6550: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6551:         my @new_locks;
                   6552:         my @del_keys;
                   6553:         if (ref($current_locks) eq "ARRAY"){
                   6554:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6555:                 my $compare=$locker;
1.749     raeburn  6556:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6557:                     $compare=join('',@{$locker});
1.746     raeburn  6558:                     if ($compare ne $symb_crs) {
                   6559:                         push(@new_locks, $locker);
                   6560:                     }
1.563     banghart 6561:                 }
                   6562:             }
1.650     albertel 6563:             if (scalar(@new_locks) > 0) {
1.563     banghart 6564:                 $current_permissions{$file} = \@new_locks;
                   6565:             } else {
                   6566:                 push(@del_keys, $file);
1.613     albertel 6567:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6568:                 delete($current_permissions{$file});
1.563     banghart 6569:             }
                   6570:         }
1.561     banghart 6571:     }
1.613     albertel 6572:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6573:     return;
                   6574: }
1.512     banghart 6575: 
1.17      www      6576: # ------------------------------------------------------------ Directory lister
                   6577: 
                   6578: sub dirlist {
1.955     raeburn  6579:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6580:     $uri=~s/^\///;
                   6581:     $uri=~s/\/$//;
1.253     stredwic 6582:     my ($udom, $uname);
1.955     raeburn  6583:     if ($getuserdir) {
1.253     stredwic 6584:         $udom = $userdomain;
                   6585:         $uname = $username;
1.955     raeburn  6586:     } else {
                   6587:         (undef,$udom,$uname)=split(/\//,$uri);
                   6588:         if(defined($userdomain)) {
                   6589:             $udom = $userdomain;
                   6590:         }
                   6591:         if(defined($username)) {
                   6592:             $uname = $username;
                   6593:         }
1.253     stredwic 6594:     }
1.955     raeburn  6595:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6596: 
1.955     raeburn  6597:     $dirRoot = $perlvar{'lonDocRoot'};
                   6598:     if (defined($getpropath)) {
                   6599:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6600:         $dirRoot =~ s/\/$//;
1.955     raeburn  6601:     } elsif (defined($getuserdir)) {
                   6602:         my $subdir=$uname.'__';
                   6603:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6604:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6605:                    ."/$udom/$subdir/$uname";
                   6606:     } elsif (defined($alternateRoot)) {
                   6607:         $dirRoot = $alternateRoot;
1.751     banghart 6608:     }
1.253     stredwic 6609: 
                   6610:     if($udom) {
                   6611:         if($uname) {
1.955     raeburn  6612:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6613:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6614:                               .':'.&escape($uname).':'.&escape($udom),
                   6615:                               &homeserver($uname,$udom));
                   6616:             if ($listing eq 'unknown_cmd') {
                   6617:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6618:                                   &homeserver($uname,$udom));
                   6619:             } else {
                   6620:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6621:             }
1.605     matthew  6622:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6623:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6624: 				  &homeserver($uname,$udom));
1.605     matthew  6625:                 @listing_results = split(/:/,$listing);
                   6626:             } else {
                   6627:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6628:             }
                   6629:             return @listing_results;
1.955     raeburn  6630:         } elsif(!$alternateRoot) {
1.800     albertel 6631:             my %allusers;
1.841     albertel 6632: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6633:  	    foreach my $tryserver (keys(%servers)) {
                   6634:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6635:                                   &escape($udom),$tryserver);
                   6636:                 if ($listing eq 'unknown_cmd') {
                   6637: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6638: 				      $udom, $tryserver);
                   6639:                 } else {
                   6640:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6641:                 }
1.841     albertel 6642: 		if ($listing eq 'unknown_cmd') {
                   6643: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6644: 				      $udom, $tryserver);
                   6645: 		    @listing_results = split(/:/,$listing);
                   6646: 		} else {
                   6647: 		    @listing_results =
                   6648: 			map { &unescape($_); } split(/:/,$listing);
                   6649: 		}
                   6650: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6651: 		    $listing_results[0] ne 'empty'       &&
                   6652: 		    $listing_results[0] ne 'con_lost') {
                   6653: 		    foreach my $line (@listing_results) {
                   6654: 			my ($entry) = split(/&/,$line,2);
                   6655: 			$allusers{$entry} = 1;
                   6656: 		    }
                   6657: 		}
1.253     stredwic 6658:             }
                   6659:             my $alluserstr='';
1.800     albertel 6660:             foreach my $user (sort(keys(%allusers))) {
                   6661:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6662:             }
                   6663:             $alluserstr=~s/:$//;
                   6664:             return split(/:/,$alluserstr);
                   6665:         } else {
1.800     albertel 6666:             return ('missing user name');
1.253     stredwic 6667:         }
1.955     raeburn  6668:     } elsif(!defined($getpropath)) {
1.841     albertel 6669:         my @all_domains = sort(&all_domains());
1.955     raeburn  6670:         foreach my $domain (@all_domains) {
                   6671:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6672:         }
                   6673:         return @all_domains;
                   6674:     } else {
1.800     albertel 6675:         return ('missing domain');
1.275     stredwic 6676:     }
                   6677: }
                   6678: 
                   6679: # --------------------------------------------- GetFileTimestamp
                   6680: # This function utilizes dirlist and returns the date stamp for
                   6681: # when it was last modified.  It will also return an error of -1
                   6682: # if an error occurs
                   6683: 
                   6684: sub GetFileTimestamp {
1.955     raeburn  6685:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6686:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6687:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6688:     my ($fileStat) = 
                   6689:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6690:                                  undef,$getuserdir);
1.275     stredwic 6691:     my @stats = split('&', $fileStat);
                   6692:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6693:         # @stats contains first the filename, then the stat output
                   6694:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6695:     } else {
                   6696:         return -1;
1.253     stredwic 6697:     }
1.26      www      6698: }
                   6699: 
1.712     albertel 6700: sub stat_file {
                   6701:     my ($uri) = @_;
1.787     albertel 6702:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6703: 
1.955     raeburn  6704:     my ($udom,$uname,$file);
1.712     albertel 6705:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6706: 	($udom,$uname,$file) =
1.811     albertel 6707: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6708: 	$file = 'userfiles/'.$file;
                   6709:     }
                   6710:     if ($uri =~ m-^/res/-) {
                   6711: 	($udom,$uname) = 
1.807     albertel 6712: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6713: 	$file = $uri;
                   6714:     }
                   6715: 
                   6716:     if (!$udom || !$uname || !$file) {
                   6717: 	# unable to handle the uri
                   6718: 	return ();
                   6719:     }
1.956     raeburn  6720:     my $getpropath;
                   6721:     if ($file =~ /^userfiles\//) {
                   6722:         $getpropath = 1;
                   6723:     }
1.955     raeburn  6724:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6725:     my @stats = split('&', $result);
1.721     banghart 6726:     
1.712     albertel 6727:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6728: 	shift(@stats); #filename is first
                   6729: 	return @stats;
                   6730:     }
                   6731:     return ();
                   6732: }
                   6733: 
1.26      www      6734: # -------------------------------------------------------- Value of a Condition
                   6735: 
1.713     albertel 6736: # gets the value of a specific preevaluated condition
                   6737: #    stored in the string  $env{user.state.<cid>}
                   6738: # or looks up a condition reference in the bighash and if if hasn't
                   6739: # already been evaluated recurses into docondval to get the value of
                   6740: # the condition, then memoizing it to 
                   6741: #   $env{user.state.<cid>.<condition>}
1.40      www      6742: sub directcondval {
                   6743:     my $number=shift;
1.620     albertel 6744:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6745: 	&Apache::lonuserstate::evalstate();
                   6746:     }
1.713     albertel 6747:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6748: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6749:     } elsif ($number =~ /^_/) {
                   6750: 	my $sub_condition;
                   6751: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6752: 		&GDBM_READER(),0640)) {
                   6753: 	    $sub_condition=$bighash{'conditions'.$number};
                   6754: 	    untie(%bighash);
                   6755: 	}
                   6756: 	my $value = &docondval($sub_condition);
1.949     raeburn  6757: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6758: 	return $value;
                   6759:     }
1.620     albertel 6760:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6761:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6762:     } else {
                   6763:        return 2;
                   6764:     }
                   6765: }
                   6766: 
1.713     albertel 6767: # get the collection of conditions for this resource
1.26      www      6768: sub condval {
                   6769:     my $condidx=shift;
1.54      www      6770:     my $allpathcond='';
1.713     albertel 6771:     foreach my $cond (split(/\|/,$condidx)) {
                   6772: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6773: 	    $allpathcond.=
                   6774: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6775: 	}
1.191     harris41 6776:     }
1.54      www      6777:     $allpathcond=~s/\|$//;
1.713     albertel 6778:     return &docondval($allpathcond);
                   6779: }
                   6780: 
                   6781: #evaluates an expression of conditions
                   6782: sub docondval {
                   6783:     my ($allpathcond) = @_;
                   6784:     my $result=0;
                   6785:     if ($env{'request.course.id'}
                   6786: 	&& defined($allpathcond)) {
                   6787: 	my $operand='|';
                   6788: 	my @stack;
                   6789: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6790: 	    if ($chunk eq '(') {
                   6791: 		push @stack,($operand,$result);
                   6792: 	    } elsif ($chunk eq ')') {
                   6793: 		my $before=pop @stack;
                   6794: 		if (pop @stack eq '&') {
                   6795: 		    $result=$result>$before?$before:$result;
                   6796: 		} else {
                   6797: 		    $result=$result>$before?$result:$before;
                   6798: 		}
                   6799: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6800: 		$operand=$chunk;
                   6801: 	    } else {
                   6802: 		my $new=directcondval($chunk);
                   6803: 		if ($operand eq '&') {
                   6804: 		    $result=$result>$new?$new:$result;
                   6805: 		} else {
                   6806: 		    $result=$result>$new?$result:$new;
                   6807: 		}
                   6808: 	    }
                   6809: 	}
1.26      www      6810:     }
                   6811:     return $result;
1.421     albertel 6812: }
                   6813: 
                   6814: # ---------------------------------------------------- Devalidate courseresdata
                   6815: 
                   6816: sub devalidatecourseresdata {
                   6817:     my ($coursenum,$coursedomain)=@_;
                   6818:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6819:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6820: }
                   6821: 
1.763     www      6822: 
1.200     www      6823: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6824: #
                   6825: #  Parameters:
                   6826: #      $coursenum    - Number of the course.
                   6827: #      $coursedomain - Domain at which the course was created.
                   6828: #  Returns:
                   6829: #     A hash of the course parameters along (I think) with timestamps
                   6830: #     and version info.
1.877     foxr     6831: 
1.624     albertel 6832: sub get_courseresdata {
                   6833:     my ($coursenum,$coursedomain)=@_;
1.200     www      6834:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6835:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6836:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6837:     my %dumpreply;
1.417     albertel 6838:     unless (defined($cached)) {
1.624     albertel 6839: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6840: 	$result=\%dumpreply;
1.251     albertel 6841: 	my ($tmp) = keys(%dumpreply);
                   6842: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6843: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6844: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6845: 	    return $tmp;
1.416     albertel 6846: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6847: 	    $result=undef;
1.599     albertel 6848: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6849: 	}
                   6850:     }
1.624     albertel 6851:     return $result;
                   6852: }
                   6853: 
1.633     albertel 6854: sub devalidateuserresdata {
                   6855:     my ($uname,$udom)=@_;
                   6856:     my $hashid="$udom:$uname";
                   6857:     &devalidate_cache_new('userres',$hashid);
                   6858: }
                   6859: 
1.624     albertel 6860: sub get_userresdata {
                   6861:     my ($uname,$udom)=@_;
                   6862:     #most student don\'t have any data set, check if there is some data
                   6863:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6864: 
                   6865:     my $hashid="$udom:$uname";
                   6866:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6867:     if (!defined($cached)) {
                   6868: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6869: 	$result=\%resourcedata;
                   6870: 	&do_cache_new('userres',$hashid,$result,600);
                   6871:     }
                   6872:     my ($tmp)=keys(%$result);
                   6873:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6874: 	return $result;
                   6875:     }
                   6876:     #error 2 occurs when the .db doesn't exist
                   6877:     if ($tmp!~/error: 2 /) {
1.672     albertel 6878: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6879: 		 " Trying to get resource data for ".
                   6880: 		 $uname." at ".$udom.": ".
                   6881: 		 $tmp."</font>");
                   6882:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6883: 	#&EXT_cache_set($udom,$uname);
                   6884: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6885: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6886:     }
                   6887:     return $tmp;
                   6888: }
1.879     foxr     6889: #----------------------------------------------- resdata - return resource data
                   6890: #  Purpose:
                   6891: #    Return resource data for either users or for a course.
                   6892: #  Parameters:
                   6893: #     $name      - Course/user name.
                   6894: #     $domain    - Name of the domain the user/course is registered on.
                   6895: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6896: #     @which     - Array of names of resources desired.
                   6897: #  Returns:
                   6898: #     The value of the first reasource in @which that is found in the
                   6899: #     resource hash.
                   6900: #  Exceptional Conditions:
                   6901: #     If the $type passed in is not valid (not the string 'course' or 
                   6902: #     'user', an undefined  reference is returned.
                   6903: #     If none of the resources are found, an undef is returned
1.624     albertel 6904: sub resdata {
                   6905:     my ($name,$domain,$type,@which)=@_;
                   6906:     my $result;
                   6907:     if ($type eq 'course') {
                   6908: 	$result=&get_courseresdata($name,$domain);
                   6909:     } elsif ($type eq 'user') {
                   6910: 	$result=&get_userresdata($name,$domain);
                   6911:     }
                   6912:     if (!ref($result)) { return $result; }    
1.251     albertel 6913:     foreach my $item (@which) {
1.927     albertel 6914: 	if (defined($result->{$item->[0]})) {
                   6915: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6916: 	}
1.250     albertel 6917:     }
1.291     albertel 6918:     return undef;
1.200     www      6919: }
                   6920: 
1.379     matthew  6921: #
                   6922: # EXT resource caching routines
                   6923: #
                   6924: 
                   6925: sub clear_EXT_cache_status {
1.383     albertel 6926:     &delenv('cache.EXT.');
1.379     matthew  6927: }
                   6928: 
                   6929: sub EXT_cache_status {
                   6930:     my ($target_domain,$target_user) = @_;
1.383     albertel 6931:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6932:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6933:         # We know already the user has no data
                   6934:         return 1;
                   6935:     } else {
                   6936:         return 0;
                   6937:     }
                   6938: }
                   6939: 
                   6940: sub EXT_cache_set {
                   6941:     my ($target_domain,$target_user) = @_;
1.383     albertel 6942:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6943:     #&appenv({$cachename => time});
1.379     matthew  6944: }
                   6945: 
1.28      www      6946: # --------------------------------------------------------- Value of a Variable
1.58      www      6947: sub EXT {
1.715     albertel 6948: 
1.395     albertel 6949:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6950:     unless ($varname) { return ''; }
1.218     albertel 6951:     #get real user name/domain, courseid and symb
                   6952:     my $courseid;
1.359     albertel 6953:     my $publicuser;
1.427     www      6954:     if ($symbparm) {
                   6955: 	$symbparm=&get_symb_from_alias($symbparm);
                   6956:     }
1.218     albertel 6957:     if (!($uname && $udom)) {
1.790     albertel 6958:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6959:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6960:     } else {
1.620     albertel 6961: 	$courseid=$env{'request.course.id'};
1.218     albertel 6962:     }
1.48      www      6963:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6964:     my $rest;
1.320     albertel 6965:     if (defined($therest[0])) {
1.48      www      6966:        $rest=join('.',@therest);
                   6967:     } else {
                   6968:        $rest='';
                   6969:     }
1.320     albertel 6970: 
1.57      www      6971:     my $qualifierrest=$qualifier;
                   6972:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6973:     my $spacequalifierrest=$space;
                   6974:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6975:     if ($realm eq 'user') {
1.48      www      6976: # --------------------------------------------------------------- user.resource
                   6977: 	if ($space eq 'resource') {
1.651     albertel 6978: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6979: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6980: 		 &&
1.744     albertel 6981: 		 ($symbparm eq &symbread()) ) {	
                   6982: 		# if we are in the middle of processing the resource the
                   6983: 		# get the value we are planning on committing
                   6984:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6985:                     return $Apache::lonhomework::results{$qualifierrest};
                   6986:                 } else {
                   6987:                     return $Apache::lonhomework::history{$qualifierrest};
                   6988:                 }
1.335     albertel 6989: 	    } else {
1.359     albertel 6990: 		my %restored;
1.620     albertel 6991: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6992: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6993: 		} else {
                   6994: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6995: 		}
1.335     albertel 6996: 		return $restored{$qualifierrest};
                   6997: 	    }
1.48      www      6998: # ----------------------------------------------------------------- user.access
                   6999:         } elsif ($space eq 'access') {
1.218     albertel 7000: 	    # FIXME - not supporting calls for a specific user
1.48      www      7001:             return &allowed($qualifier,$rest);
                   7002: # ------------------------------------------ user.preferences, user.environment
                   7003:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7004: 	    if (($uname eq $env{'user.name'}) &&
                   7005: 		($udom eq $env{'user.domain'})) {
                   7006: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7007: 	    } else {
1.359     albertel 7008: 		my %returnhash;
                   7009: 		if (!$publicuser) {
                   7010: 		    %returnhash=&userenvironment($udom,$uname,
                   7011: 						 $qualifierrest);
                   7012: 		}
1.218     albertel 7013: 		return $returnhash{$qualifierrest};
                   7014: 	    }
1.48      www      7015: # ----------------------------------------------------------------- user.course
                   7016:         } elsif ($space eq 'course') {
1.218     albertel 7017: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7018:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7019: # ------------------------------------------------------------------- user.role
                   7020:         } elsif ($space eq 'role') {
1.218     albertel 7021: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7022:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7023:             if ($qualifier eq 'value') {
                   7024: 		return $role;
                   7025:             } elsif ($qualifier eq 'extent') {
                   7026:                 return $where;
                   7027:             }
                   7028: # ----------------------------------------------------------------- user.domain
                   7029:         } elsif ($space eq 'domain') {
1.218     albertel 7030:             return $udom;
1.48      www      7031: # ------------------------------------------------------------------- user.name
                   7032:         } elsif ($space eq 'name') {
1.218     albertel 7033:             return $uname;
1.48      www      7034: # ---------------------------------------------------- Any other user namespace
1.29      www      7035:         } else {
1.359     albertel 7036: 	    my %reply;
                   7037: 	    if (!$publicuser) {
                   7038: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7039: 	    }
                   7040: 	    return $reply{$qualifierrest};
1.48      www      7041:         }
1.236     www      7042:     } elsif ($realm eq 'query') {
                   7043: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7044:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7045: 						[$spacequalifierrest]);
1.620     albertel 7046: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7047:    } elsif ($realm eq 'request') {
1.48      www      7048: # ------------------------------------------------------------- request.browser
                   7049:         if ($space eq 'browser') {
1.430     www      7050: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7051: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7052: 		    return 1;
                   7053: 		} else {
                   7054: 		    return 0;
                   7055: 		}
                   7056: 	    } else {
1.620     albertel 7057: 		return $env{'browser.'.$qualifier};
1.430     www      7058: 	    }
1.57      www      7059: # ------------------------------------------------------------ request.filename
                   7060:         } else {
1.620     albertel 7061:             return $env{'request.'.$spacequalifierrest};
1.29      www      7062:         }
1.28      www      7063:     } elsif ($realm eq 'course') {
1.48      www      7064: # ---------------------------------------------------------- course.description
1.620     albertel 7065:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7066:     } elsif ($realm eq 'resource') {
1.165     www      7067: 
1.620     albertel 7068: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7069: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7070: 	}
1.693     albertel 7071: 
                   7072: 	if ($space eq 'title') {
                   7073: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7074: 	    return &gettitle($symbparm);
                   7075: 	}
                   7076: 	
                   7077: 	if ($space eq 'map') {
                   7078: 	    my ($map) = &decode_symb($symbparm);
                   7079: 	    return &symbread($map);
                   7080: 	}
1.905     albertel 7081: 	if ($space eq 'filename') {
                   7082: 	    if ($symbparm) {
                   7083: 		return &clutter((&decode_symb($symbparm))[2]);
                   7084: 	    }
                   7085: 	    return &hreflocation('',$env{'request.filename'});
                   7086: 	}
1.693     albertel 7087: 
                   7088: 	my ($section, $group, @groups);
1.593     albertel 7089: 	my ($courselevelm,$courselevel);
1.539     albertel 7090: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7091: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7092: 
1.218     albertel 7093: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7094: 
1.60      www      7095: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7096: 	    my $symbp=$symbparm;
1.735     albertel 7097: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7098: 
                   7099: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7100: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7101: 
1.620     albertel 7102: 	    if (($env{'user.name'} eq $uname) &&
                   7103: 		($env{'user.domain'} eq $udom)) {
                   7104: 		$section=$env{'request.course.sec'};
1.733     raeburn  7105:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7106:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7107: 	    } else {
1.539     albertel 7108: 		if (! defined($usection)) {
1.551     albertel 7109: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7110: 		} else {
                   7111: 		    $section = $usection;
                   7112: 		}
1.733     raeburn  7113:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7114: 	    }
                   7115: 
                   7116: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7117: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7118: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7119: 
1.593     albertel 7120: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7121: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7122: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7123: 
1.60      www      7124: # ----------------------------------------------------------- first, check user
1.624     albertel 7125: 
                   7126: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7127: 				       ([$courselevelr,'resource'],
                   7128: 					[$courselevelm,'map'     ],
                   7129: 					[$courselevel, 'course'  ]));
1.931     albertel 7130: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7131: 
1.594     albertel 7132: # ------------------------------------------------ second, check some of course
1.684     raeburn  7133:             my $coursereply;
1.691     raeburn  7134:             if (@groups > 0) {
                   7135:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7136:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7137:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7138:             }
1.96      www      7139: 
1.684     raeburn  7140: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7141: 				  $env{'course.'.$courseid.'.domain'},
                   7142: 				  'course',
                   7143: 				  ([$seclevelr,   'resource'],
                   7144: 				   [$seclevelm,   'map'     ],
                   7145: 				   [$seclevel,    'course'  ],
                   7146: 				   [$courselevelr,'resource']));
                   7147: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7148: 
1.60      www      7149: # ------------------------------------------------------ third, check map parms
1.218     albertel 7150: 	    my %parmhash=();
                   7151: 	    my $thisparm='';
                   7152: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7153: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7154: 		    &GDBM_READER(),0640)) {
1.218     albertel 7155: 		$thisparm=$parmhash{$symbparm};
                   7156: 		untie(%parmhash);
                   7157: 	    }
1.927     albertel 7158: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7159: 	}
1.594     albertel 7160: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7161: 
1.218     albertel 7162: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7163: 	my $filename;
                   7164: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7165: 	if ($symbparm) {
1.409     www      7166: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7167: 	} else {
1.620     albertel 7168: 	    $filename=$env{'request.filename'};
1.282     albertel 7169: 	}
                   7170: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7171: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7172: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7173: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7174: 
1.927     albertel 7175: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7176: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7177: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7178: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7179: 				     $env{'course.'.$courseid.'.domain'},
                   7180: 				     'course',
1.927     albertel 7181: 				     ([$courselevelm,'map'   ],
                   7182: 				      [$courselevel, 'course']));
                   7183: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7184: 	}
1.145     www      7185: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7186: 	unless ($space eq '0') {
1.336     albertel 7187: 	    my @parts=split(/_/,$space);
                   7188: 	    my $id=pop(@parts);
                   7189: 	    my $part=join('_',@parts);
                   7190: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7191: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7192: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7193: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7194: 	}
1.395     albertel 7195: 	if ($recurse) { return undef; }
                   7196: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7197: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7198: # ---------------------------------------------------- Any other user namespace
                   7199:     } elsif ($realm eq 'environment') {
                   7200: # ----------------------------------------------------------------- environment
1.620     albertel 7201: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7202: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7203: 	} else {
1.770     albertel 7204: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7205: 		return '';
                   7206: 	    }
1.219     albertel 7207: 	    my %returnhash=&userenvironment($udom,$uname,
                   7208: 					    $spacequalifierrest);
                   7209: 	    return $returnhash{$spacequalifierrest};
                   7210: 	}
1.28      www      7211:     } elsif ($realm eq 'system') {
1.48      www      7212: # ----------------------------------------------------------------- system.time
                   7213: 	if ($space eq 'time') {
                   7214: 	    return time;
                   7215:         }
1.696     albertel 7216:     } elsif ($realm eq 'server') {
                   7217: # ----------------------------------------------------------------- system.time
                   7218: 	if ($space eq 'name') {
                   7219: 	    return $ENV{'SERVER_NAME'};
                   7220:         }
1.28      www      7221:     }
1.48      www      7222:     return '';
1.61      www      7223: }
                   7224: 
1.927     albertel 7225: sub get_reply {
                   7226:     my ($reply_value) = @_;
1.940     raeburn  7227:     if (ref($reply_value) eq 'ARRAY') {
                   7228:         if (wantarray) {
                   7229: 	    return @$reply_value;
                   7230:         }
                   7231:         return $reply_value->[0];
                   7232:     } else {
                   7233:         return $reply_value;
1.927     albertel 7234:     }
                   7235: }
                   7236: 
1.691     raeburn  7237: sub check_group_parms {
                   7238:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7239:     my @groupitems = ();
                   7240:     my $resultitem;
1.927     albertel 7241:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7242:     foreach my $group (@{$groups}) {
                   7243:         foreach my $level (@levels) {
1.927     albertel 7244:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7245:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7246:         }
                   7247:     }
                   7248:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7249:                             $env{'course.'.$courseid.'.domain'},
                   7250:                                      'course',@groupitems);
                   7251:     return $coursereply;
                   7252: }
                   7253: 
                   7254: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7255:     my ($courseid,@groups) = @_;
                   7256:     @groups = sort(@groups);
1.691     raeburn  7257:     return @groups;
                   7258: }
                   7259: 
1.395     albertel 7260: sub packages_tab_default {
                   7261:     my ($uri,$varname)=@_;
                   7262:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7263: 
                   7264:     my (@extension,@specifics,$do_default);
                   7265:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7266: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7267: 	if ($pack_type eq 'default') {
                   7268: 	    $do_default=1;
                   7269: 	} elsif ($pack_type eq 'extension') {
                   7270: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7271: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7272: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7273: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7274: 	}
                   7275:     }
                   7276:     # first look for a package that matches the requested part id
                   7277:     foreach my $package (@specifics) {
                   7278: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7279: 	next if ($pack_part ne $part);
                   7280: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7281: 	    return $packagetab{"$pack_type&$name&default"};
                   7282: 	}
                   7283:     }
                   7284:     # look for any possible matching non extension_ package
                   7285:     foreach my $package (@specifics) {
                   7286: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7287: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7288: 	    return $packagetab{"$pack_type&$name&default"};
                   7289: 	}
1.585     albertel 7290: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7291: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7292: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7293: 	}
                   7294:     }
1.738     albertel 7295:     # look for any posible extension_ match
                   7296:     foreach my $package (@extension) {
                   7297: 	my ($package,$pack_type)=@{$package};
                   7298: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7299: 	    return $packagetab{"$pack_type&$name&default"};
                   7300: 	}
                   7301: 	if (defined($packagetab{$package."&$name&default"})) {
                   7302: 	    return $packagetab{$package."&$name&default"};
                   7303: 	}
                   7304:     }
                   7305:     # look for a global default setting
                   7306:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7307: 	return $packagetab{"default&$name&default"};
                   7308:     }
1.395     albertel 7309:     return undef;
                   7310: }
                   7311: 
1.334     albertel 7312: sub add_prefix_and_part {
                   7313:     my ($prefix,$part)=@_;
                   7314:     my $keyroot;
                   7315:     if (defined($prefix) && $prefix !~ /^__/) {
                   7316: 	# prefix that has a part already
                   7317: 	$keyroot=$prefix;
                   7318:     } elsif (defined($prefix)) {
                   7319: 	# prefix that is missing a part
                   7320: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7321:     } else {
                   7322: 	# no prefix at all
                   7323: 	if (defined($part)) { $keyroot='_'.$part; }
                   7324:     }
                   7325:     return $keyroot;
                   7326: }
                   7327: 
1.71      www      7328: # ---------------------------------------------------------------- Get metadata
                   7329: 
1.599     albertel 7330: my %metaentry;
1.71      www      7331: sub metadata {
1.176     www      7332:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7333:     $uri=&declutter($uri);
1.288     albertel 7334:     # if it is a non metadata possible uri return quickly
1.529     albertel 7335:     if (($uri eq '') || 
                   7336: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7337: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7338:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7339: 	return undef;
                   7340:     }
                   7341:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7342: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7343: 	return undef;
1.288     albertel 7344:     }
1.73      www      7345:     my $filename=$uri;
                   7346:     $uri=~s/\.meta$//;
1.172     www      7347: #
                   7348: # Is the metadata already cached?
1.177     www      7349: # Look at timestamp of caching
1.172     www      7350: # Everything is cached by the main uri, libraries are never directly cached
                   7351: #
1.428     albertel 7352:     if (!defined($liburi)) {
1.599     albertel 7353: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7354: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7355:     }
                   7356:     {
1.172     www      7357: #
                   7358: # Is this a recursive call for a library?
                   7359: #
1.599     albertel 7360: #	if (! exists($metacache{$uri})) {
                   7361: #	    $metacache{$uri}={};
                   7362: #	}
1.924     albertel 7363: 	my $cachetime = 60*60;
1.171     www      7364:         if ($liburi) {
                   7365: 	    $liburi=&declutter($liburi);
                   7366:             $filename=$liburi;
1.401     bowersj2 7367:         } else {
1.599     albertel 7368: 	    &devalidate_cache_new('meta',$uri);
                   7369: 	    undef(%metaentry);
1.401     bowersj2 7370: 	}
1.140     www      7371:         my %metathesekeys=();
1.73      www      7372:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7373: 	my $metastring;
1.924     albertel 7374: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7375: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7376: 	    $metastring = 
1.929     albertel 7377: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7378: 					  ('grade_target' => 'meta'));
                   7379: 	    $cachetime = 1; # only want this cached in the child not long term
                   7380: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7381: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7382: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7383: 	    $metastring=&getfile($file);
1.489     albertel 7384: 	}
1.208     albertel 7385:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7386:         my $token;
1.140     www      7387:         undef %metathesekeys;
1.71      www      7388:         while ($token=$parser->get_token) {
1.339     albertel 7389: 	    if ($token->[0] eq 'S') {
                   7390: 		if (defined($token->[2]->{'package'})) {
1.172     www      7391: #
                   7392: # This is a package - get package info
                   7393: #
1.339     albertel 7394: 		    my $package=$token->[2]->{'package'};
                   7395: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7396: 		    if (defined($token->[2]->{'id'})) { 
                   7397: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7398: 		    }
1.599     albertel 7399: 		    if ($metaentry{':packages'}) {
                   7400: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7401: 		    } else {
1.599     albertel 7402: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7403: 		    }
1.736     albertel 7404: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7405: 			my $part=$keyroot;
                   7406: 			$part=~s/^\_//;
1.736     albertel 7407: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7408: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7409: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7410: 			    # ignore package.tab specified default values
                   7411:                             # here &package_tab_default() will fetch those
                   7412: 			    if ($subp eq 'default') { next; }
1.736     albertel 7413: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7414: 			    my $unikey;
                   7415: 			    if ($pack =~ /_0$/) {
                   7416: 				$unikey='parameter_0_'.$name;
                   7417: 				$part=0;
                   7418: 			    } else {
                   7419: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7420: 			    }
1.339     albertel 7421: 			    if ($subp eq 'display') {
                   7422: 				$value.=' [Part: '.$part.']';
                   7423: 			    }
1.599     albertel 7424: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7425: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7426: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7427: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7428: 			    }
1.599     albertel 7429: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7430: 				$metaentry{':'.$unikey}=
                   7431: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7432: 			    }
1.339     albertel 7433: 			}
                   7434: 		    }
                   7435: 		} else {
1.172     www      7436: #
                   7437: # This is not a package - some other kind of start tag
1.339     albertel 7438: #
                   7439: 		    my $entry=$token->[1];
                   7440: 		    my $unikey;
                   7441: 		    if ($entry eq 'import') {
                   7442: 			$unikey='';
                   7443: 		    } else {
                   7444: 			$unikey=$entry;
                   7445: 		    }
                   7446: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7447: 
                   7448: 		    if (defined($token->[2]->{'id'})) { 
                   7449: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7450: 		    }
1.175     www      7451: 
1.339     albertel 7452: 		    if ($entry eq 'import') {
1.175     www      7453: #
                   7454: # Importing a library here
1.339     albertel 7455: #
                   7456: 			if ($depthcount<20) {
                   7457: 			    my $location=$parser->get_text('/import');
                   7458: 			    my $dir=$filename;
                   7459: 			    $dir=~s|[^/]*$||;
                   7460: 			    $location=&filelocation($dir,$location);
1.736     albertel 7461: 			    my $metadata = 
                   7462: 				&metadata($uri,'keys', $location,$unikey,
                   7463: 					  $depthcount+1);
                   7464: 			    foreach my $meta (split(',',$metadata)) {
                   7465: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7466: 				$metathesekeys{$meta}=1;
1.339     albertel 7467: 			    }
                   7468: 			}
                   7469: 		    } else { 
                   7470: 			
                   7471: 			if (defined($token->[2]->{'name'})) { 
                   7472: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7473: 			}
                   7474: 			$metathesekeys{$unikey}=1;
1.736     albertel 7475: 			foreach my $param (@{$token->[3]}) {
                   7476: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7477: 				$token->[2]->{$param};
1.339     albertel 7478: 			}
                   7479: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7480: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7481: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7482: 		 # only ws inside the tag, and not in default, so use default
                   7483: 		 # as value
1.599     albertel 7484: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7485: 			} elsif ( $internaltext =~ /\S/ ) {
                   7486: 		  # something interesting inside the tag
                   7487: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7488: 			} else {
1.908     albertel 7489: 		  # no interesting values, don't set a default
1.339     albertel 7490: 			}
1.172     www      7491: # end of not-a-package not-a-library import
1.339     albertel 7492: 		    }
1.172     www      7493: # end of not-a-package start tag
1.339     albertel 7494: 		}
1.172     www      7495: # the next is the end of "start tag"
1.339     albertel 7496: 	    }
                   7497: 	}
1.483     albertel 7498: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7499: 	$extension = lc($extension);
                   7500: 	if ($extension eq 'htm') { $extension='html'; }
                   7501: 
1.737     albertel 7502: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7503: 	    #no specific packages #how's our extension
                   7504: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7505: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7506: 					 \%metathesekeys);
                   7507: 	}
1.883     albertel 7508: 
                   7509: 	if (!exists($metaentry{':packages'})
                   7510: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7511: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7512: 		#no specific packages well let's get default then
                   7513: 		if ($key!~/^default&/) { next; }
1.488     albertel 7514: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7515: 					     \%metathesekeys);
                   7516: 	    }
                   7517: 	}
1.338     www      7518: # are there custom rights to evaluate
1.599     albertel 7519: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7520: 
1.338     www      7521:     #
                   7522:     # Importing a rights file here
1.339     albertel 7523:     #
                   7524: 	    unless ($depthcount) {
1.599     albertel 7525: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7526: 		my $dir=$filename;
                   7527: 		$dir=~s|[^/]*$||;
                   7528: 		$location=&filelocation($dir,$location);
1.736     albertel 7529: 		my $rights_metadata =
                   7530: 		    &metadata($uri,'keys',$location,'_rights',
                   7531: 			      $depthcount+1);
                   7532: 		foreach my $rights (split(',',$rights_metadata)) {
                   7533: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7534: 		    $metathesekeys{$rights}=1;
1.339     albertel 7535: 		}
                   7536: 	    }
                   7537: 	}
1.737     albertel 7538: 	# uniqifiy package listing
                   7539: 	my %seen;
                   7540: 	my @uniq_packages =
                   7541: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7542: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7543: 
                   7544: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7545: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7546: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7547: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7548: # this is the end of "was not already recently cached
1.71      www      7549:     }
1.599     albertel 7550:     return $metaentry{':'.$what};
1.261     albertel 7551: }
                   7552: 
1.488     albertel 7553: sub metadata_create_package_def {
1.483     albertel 7554:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7555:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7556:     if ($subp eq 'default') { next; }
                   7557:     
1.599     albertel 7558:     if (defined($metaentry{':packages'})) {
                   7559: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7560:     } else {
1.599     albertel 7561: 	$metaentry{':packages'}=$package;
1.483     albertel 7562:     }
                   7563:     my $value=$packagetab{$key};
                   7564:     my $unikey;
                   7565:     $unikey='parameter_0_'.$name;
1.599     albertel 7566:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7567:     $$metathesekeys{$unikey}=1;
1.599     albertel 7568:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7569: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7570:     }
1.599     albertel 7571:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7572: 	$metaentry{':'.$unikey}=
                   7573: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7574:     }
                   7575: }
                   7576: 
1.261     albertel 7577: sub metadata_generate_part0 {
                   7578:     my ($metadata,$metacache,$uri) = @_;
                   7579:     my %allnames;
1.737     albertel 7580:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7581: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7582: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7583: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7584: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7585: 	    $allnames{$name}=$part;
                   7586: 	  }
                   7587: 	}
                   7588:     }
                   7589:     foreach my $name (keys(%allnames)) {
                   7590:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7591:       my $key=":parameter_0_$name";
1.261     albertel 7592:       $$metacache{"$key.part"}='0';
                   7593:       $$metacache{"$key.name"}=$name;
1.428     albertel 7594:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7595: 					   $allnames{$name}.'_'.$name.
                   7596: 					   '.type'};
1.428     albertel 7597:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7598: 			     '.display'};
1.644     www      7599:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7600:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7601:       $$metacache{"$key.display"}=$olddis;
                   7602:     }
1.71      www      7603: }
                   7604: 
1.764     albertel 7605: # ------------------------------------------------------ Devalidate title cache
                   7606: 
                   7607: sub devalidate_title_cache {
                   7608:     my ($url)=@_;
                   7609:     if (!$env{'request.course.id'}) { return; }
                   7610:     my $symb=&symbread($url);
                   7611:     if (!$symb) { return; }
                   7612:     my $key=$env{'request.course.id'}."\0".$symb;
                   7613:     &devalidate_cache_new('title',$key);
                   7614: }
                   7615: 
1.301     www      7616: # ------------------------------------------------- Get the title of a resource
                   7617: 
                   7618: sub gettitle {
                   7619:     my $urlsymb=shift;
                   7620:     my $symb=&symbread($urlsymb);
1.534     albertel 7621:     if ($symb) {
1.620     albertel 7622: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7623: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7624: 	if (defined($cached)) { 
                   7625: 	    return $result;
                   7626: 	}
1.534     albertel 7627: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7628: 	my $title='';
1.907     albertel 7629: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7630: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7631: 	} else {
                   7632: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7633: 		    &GDBM_READER(),0640)) {
                   7634: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7635: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7636: 		untie(%bighash);
                   7637: 	    }
1.534     albertel 7638: 	}
                   7639: 	$title=~s/\&colon\;/\:/gs;
                   7640: 	if ($title) {
1.599     albertel 7641: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7642: 	}
                   7643: 	$urlsymb=$url;
                   7644:     }
                   7645:     my $title=&metadata($urlsymb,'title');
                   7646:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7647:     return $title;
1.301     www      7648: }
1.613     albertel 7649: 
1.614     albertel 7650: sub get_slot {
                   7651:     my ($which,$cnum,$cdom)=@_;
                   7652:     if (!$cnum || !$cdom) {
1.790     albertel 7653: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7654: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7655: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7656:     }
1.703     albertel 7657:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7658:     my %slotinfo;
                   7659:     if (exists($remembered{$key})) {
                   7660: 	$slotinfo{$which} = $remembered{$key};
                   7661:     } else {
                   7662: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7663: 	&Apache::lonhomework::showhash(%slotinfo);
                   7664: 	my ($tmp)=keys(%slotinfo);
                   7665: 	if ($tmp=~/^error:/) { return (); }
                   7666: 	$remembered{$key} = $slotinfo{$which};
                   7667:     }
1.616     albertel 7668:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7669: 	return %{$slotinfo{$which}};
                   7670:     }
                   7671:     return $slotinfo{$which};
1.614     albertel 7672: }
1.31      www      7673: # ------------------------------------------------- Update symbolic store links
                   7674: 
                   7675: sub symblist {
                   7676:     my ($mapname,%newhash)=@_;
1.438     www      7677:     $mapname=&deversion(&declutter($mapname));
1.31      www      7678:     my %hash;
1.620     albertel 7679:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7680:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7681:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7682: 	    foreach my $url (keys %newhash) {
                   7683: 		next if ($url eq 'last_known'
                   7684: 			 && $env{'form.no_update_last_known'});
                   7685: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7686: 						    $newhash{$url}->[1],
                   7687: 						    $newhash{$url}->[0]);
1.191     harris41 7688:             }
1.31      www      7689:             if (untie(%hash)) {
                   7690: 		return 'ok';
                   7691:             }
                   7692:         }
                   7693:     }
                   7694:     return 'error';
1.212     www      7695: }
                   7696: 
                   7697: # --------------------------------------------------------------- Verify a symb
                   7698: 
                   7699: sub symbverify {
1.510     www      7700:     my ($symb,$thisurl)=@_;
                   7701:     my $thisfn=$thisurl;
1.439     www      7702:     $thisfn=&declutter($thisfn);
1.215     www      7703: # direct jump to resource in page or to a sequence - will construct own symbs
                   7704:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7705: # check URL part
1.409     www      7706:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7707: 
1.431     www      7708:     unless ($url eq $thisfn) { return 0; }
1.213     www      7709: 
1.216     www      7710:     $symb=&symbclean($symb);
1.510     www      7711:     $thisurl=&deversion($thisurl);
1.439     www      7712:     $thisfn=&deversion($thisfn);
1.213     www      7713: 
                   7714:     my %bighash;
                   7715:     my $okay=0;
1.431     www      7716: 
1.620     albertel 7717:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7718:                             &GDBM_READER(),0640)) {
1.510     www      7719:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7720:         unless ($ids) { 
1.510     www      7721:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7722:         }
                   7723:         if ($ids) {
                   7724: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7725: 	    foreach my $id (split(/\,/,$ids)) {
                   7726: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7727:                if (
                   7728:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7729:    eq $symb) { 
1.620     albertel 7730: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7731: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7732: 		       $okay=1; 
                   7733: 		   }
                   7734: 	       }
1.216     www      7735: 	   }
                   7736:         }
1.213     www      7737: 	untie(%bighash);
                   7738:     }
                   7739:     return $okay;
1.31      www      7740: }
                   7741: 
1.210     www      7742: # --------------------------------------------------------------- Clean-up symb
                   7743: 
                   7744: sub symbclean {
                   7745:     my $symb=shift;
1.568     albertel 7746:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7747: # remove version from map
                   7748:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7749: 
1.210     www      7750: # remove version from URL
                   7751:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7752: 
1.507     www      7753: # remove wrapper
                   7754: 
1.510     www      7755:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7756:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7757:     return $symb;
1.409     www      7758: }
                   7759: 
                   7760: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7761: 
                   7762: sub encode_symb {
                   7763:     my ($map,$resid,$url)=@_;
                   7764:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7765: }
1.409     www      7766: 
                   7767: sub decode_symb {
1.568     albertel 7768:     my $symb=shift;
                   7769:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7770:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7771:     return (&fixversion($map),$resid,&fixversion($url));
                   7772: }
                   7773: 
                   7774: sub fixversion {
                   7775:     my $fn=shift;
1.609     banghart 7776:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7777:     my %bighash;
                   7778:     my $uri=&clutter($fn);
1.620     albertel 7779:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7780: # is this cached?
1.599     albertel 7781:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7782:     if (defined($cached)) { return $result; }
                   7783: # unfortunately not cached, or expired
1.620     albertel 7784:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7785: 	    &GDBM_READER(),0640)) {
                   7786:  	if ($bighash{'version_'.$uri}) {
                   7787:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7788:  	    unless (($version eq 'mostrecent') || 
                   7789: 		    ($version==&getversion($uri))) {
1.440     www      7790:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7791:  	    }
                   7792:  	}
                   7793:  	untie %bighash;
1.413     www      7794:     }
1.599     albertel 7795:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7796: }
                   7797: 
                   7798: sub deversion {
                   7799:     my $url=shift;
                   7800:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7801:     return $url;
1.210     www      7802: }
                   7803: 
1.31      www      7804: # ------------------------------------------------------ Return symb list entry
                   7805: 
                   7806: sub symbread {
1.249     www      7807:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7808:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7809:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7810: # no filename provided? try from environment
1.44      www      7811:     unless ($thisfn) {
1.620     albertel 7812:         if ($env{'request.symb'}) {
                   7813: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7814: 	}
1.620     albertel 7815: 	$thisfn=$env{'request.filename'};
1.44      www      7816:     }
1.569     albertel 7817:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7818: # is that filename actually a symb? Verify, clean, and return
                   7819:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7820: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7821: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7822: 	}
1.242     www      7823:     }
1.44      www      7824:     $thisfn=declutter($thisfn);
1.31      www      7825:     my %hash;
1.37      www      7826:     my %bighash;
                   7827:     my $syval='';
1.620     albertel 7828:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7829:         my $targetfn = $thisfn;
1.609     banghart 7830:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7831:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7832:         }
1.687     albertel 7833: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7834: 	    $targetfn=$1;
                   7835: 	}
1.620     albertel 7836:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7837:                       &GDBM_READER(),0640)) {
1.481     raeburn  7838: 	    $syval=$hash{$targetfn};
1.37      www      7839:             untie(%hash);
                   7840:         }
                   7841: # ---------------------------------------------------------- There was an entry
                   7842:         if ($syval) {
1.601     albertel 7843: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7844: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7845: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7846: 		    #return $env{$cache_str}='';
1.601     albertel 7847: 		#}    
                   7848: 		#$syval.=$1;
                   7849: 	    #}
1.37      www      7850:         } else {
                   7851: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7852:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7853:                             &GDBM_READER(),0640)) {
1.37      www      7854: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7855:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7856:               unless ($ids) { 
                   7857:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7858:               }
                   7859:               unless ($ids) {
                   7860: # alias?
                   7861: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7862:               }
1.37      www      7863:               if ($ids) {
                   7864: # ------------------------------------------------------------------- Has ID(s)
                   7865:                  my @possibilities=split(/\,/,$ids);
1.39      www      7866:                  if ($#possibilities==0) {
                   7867: # ----------------------------------------------- There is only one possibility
1.37      www      7868: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7869: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7870: 						    $resid,$thisfn);
1.249     www      7871:                  } elsif (!$donotrecurse) {
1.39      www      7872: # ------------------------------------------ There is more than one possibility
                   7873:                      my $realpossible=0;
1.800     albertel 7874:                      foreach my $id (@possibilities) {
                   7875: 			 my $file=$bighash{'src_'.$id};
1.39      www      7876:                          if (&allowed('bre',$file)) {
1.800     albertel 7877:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7878:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7879: 				$realpossible++;
1.626     albertel 7880:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7881: 						    $resid,$thisfn);
1.39      www      7882:                             }
                   7883: 			 }
1.191     harris41 7884:                      }
1.39      www      7885: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7886:                  } else {
                   7887:                      $syval='';
1.37      www      7888:                  }
                   7889: 	      }
                   7890:               untie(%bighash)
1.481     raeburn  7891:            }
1.31      www      7892:         }
1.62      www      7893:         if ($syval) {
1.620     albertel 7894: 	    return $env{$cache_str}=$syval;
1.62      www      7895:         }
1.31      www      7896:     }
1.949     raeburn  7897:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7898:     return $env{$cache_str}='';
1.31      www      7899: }
                   7900: 
                   7901: # ---------------------------------------------------------- Return random seed
                   7902: 
1.32      www      7903: sub numval {
                   7904:     my $txt=shift;
                   7905:     $txt=~tr/A-J/0-9/;
                   7906:     $txt=~tr/a-j/0-9/;
                   7907:     $txt=~tr/K-T/0-9/;
                   7908:     $txt=~tr/k-t/0-9/;
                   7909:     $txt=~tr/U-Z/0-5/;
                   7910:     $txt=~tr/u-z/0-5/;
                   7911:     $txt=~s/\D//g;
1.564     albertel 7912:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7913:     return int($txt);
1.368     albertel 7914: }
                   7915: 
1.484     albertel 7916: sub numval2 {
                   7917:     my $txt=shift;
                   7918:     $txt=~tr/A-J/0-9/;
                   7919:     $txt=~tr/a-j/0-9/;
                   7920:     $txt=~tr/K-T/0-9/;
                   7921:     $txt=~tr/k-t/0-9/;
                   7922:     $txt=~tr/U-Z/0-5/;
                   7923:     $txt=~tr/u-z/0-5/;
                   7924:     $txt=~s/\D//g;
                   7925:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7926:     my $total;
                   7927:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7928:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7929:     return int($total);
                   7930: }
                   7931: 
1.575     albertel 7932: sub numval3 {
                   7933:     use integer;
                   7934:     my $txt=shift;
                   7935:     $txt=~tr/A-J/0-9/;
                   7936:     $txt=~tr/a-j/0-9/;
                   7937:     $txt=~tr/K-T/0-9/;
                   7938:     $txt=~tr/k-t/0-9/;
                   7939:     $txt=~tr/U-Z/0-5/;
                   7940:     $txt=~tr/u-z/0-5/;
                   7941:     $txt=~s/\D//g;
                   7942:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7943:     my $total;
                   7944:     foreach my $val (@txts) { $total+=$val; }
                   7945:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7946:     return $total;
                   7947: }
                   7948: 
1.675     albertel 7949: sub digest {
                   7950:     my ($data)=@_;
                   7951:     my $digest=&Digest::MD5::md5($data);
                   7952:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7953:     my ($e,$f);
                   7954:     {
                   7955:         use integer;
                   7956:         $e=($a+$b);
                   7957:         $f=($c+$d);
                   7958:         if ($_64bit) {
                   7959:             $e=(($e<<32)>>32);
                   7960:             $f=(($f<<32)>>32);
                   7961:         }
                   7962:     }
                   7963:     if (wantarray) {
                   7964: 	return ($e,$f);
                   7965:     } else {
                   7966: 	my $g;
                   7967: 	{
                   7968: 	    use integer;
                   7969: 	    $g=($e+$f);
                   7970: 	    if ($_64bit) {
                   7971: 		$g=(($g<<32)>>32);
                   7972: 	    }
                   7973: 	}
                   7974: 	return $g;
                   7975:     }
                   7976: }
                   7977: 
1.368     albertel 7978: sub latest_rnd_algorithm_id {
1.675     albertel 7979:     return '64bit5';
1.366     albertel 7980: }
1.32      www      7981: 
1.503     albertel 7982: sub get_rand_alg {
                   7983:     my ($courseid)=@_;
1.790     albertel 7984:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7985:     if ($courseid) {
1.620     albertel 7986: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7987:     }
                   7988:     return &latest_rnd_algorithm_id();
                   7989: }
                   7990: 
1.562     albertel 7991: sub validCODE {
                   7992:     my ($CODE)=@_;
                   7993:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7994:     return 0;
                   7995: }
                   7996: 
1.491     albertel 7997: sub getCODE {
1.620     albertel 7998:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7999:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8000: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8001: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8002: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8003:     }
                   8004:     return undef;
                   8005: }
                   8006: 
1.31      www      8007: sub rndseed {
1.155     albertel 8008:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8009:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8010:     if (!defined($symb)) {
1.366     albertel 8011: 	unless ($symb=$wsymb) { return time; }
                   8012:     }
                   8013:     if (!$courseid) { $courseid=$wcourseid; }
                   8014:     if (!$domain) { $domain=$wdomain; }
                   8015:     if (!$username) { $username=$wusername }
1.503     albertel 8016:     my $which=&get_rand_alg();
1.803     albertel 8017: 
1.491     albertel 8018:     if (defined(&getCODE())) {
1.675     albertel 8019: 	if ($which eq '64bit5') {
                   8020: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8021: 	} elsif ($which eq '64bit4') {
1.575     albertel 8022: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8023: 	} else {
                   8024: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8025: 	}
1.675     albertel 8026:     } elsif ($which eq '64bit5') {
                   8027: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8028:     } elsif ($which eq '64bit4') {
                   8029: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8030:     } elsif ($which eq '64bit3') {
                   8031: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8032:     } elsif ($which eq '64bit2') {
                   8033: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8034:     } elsif ($which eq '64bit') {
                   8035: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8036:     }
                   8037:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8038: }
                   8039: 
                   8040: sub rndseed_32bit {
                   8041:     my ($symb,$courseid,$domain,$username)=@_;
                   8042:     {
                   8043: 	use integer;
                   8044: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8045: 	my $symbseed=numval($symb) << 22;
                   8046: 	my $namechck=unpack("%32C*",$username) << 17;
                   8047: 	my $nameseed=numval($username) << 12;
                   8048: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8049: 	my $courseseed=unpack("%32C*",$courseid);
                   8050: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8051: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8052: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8053: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8054: 	return $num;
                   8055:     }
                   8056: }
                   8057: 
                   8058: sub rndseed_64bit {
                   8059:     my ($symb,$courseid,$domain,$username)=@_;
                   8060:     {
                   8061: 	use integer;
                   8062: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8063: 	my $symbseed=numval($symb) << 10;
                   8064: 	my $namechck=unpack("%32S*",$username);
                   8065: 	
                   8066: 	my $nameseed=numval($username) << 21;
                   8067: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8068: 	my $courseseed=unpack("%32S*",$courseid);
                   8069: 	
                   8070: 	my $num1=$symbchck+$symbseed+$namechck;
                   8071: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8072: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8073: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8074: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8075: 	return "$num1,$num2";
1.155     albertel 8076:     }
1.366     albertel 8077: }
                   8078: 
1.443     albertel 8079: sub rndseed_64bit2 {
                   8080:     my ($symb,$courseid,$domain,$username)=@_;
                   8081:     {
                   8082: 	use integer;
                   8083: 	# strings need to be an even # of cahracters long, it it is odd the
                   8084:         # last characters gets thrown away
                   8085: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8086: 	my $symbseed=numval($symb) << 10;
                   8087: 	my $namechck=unpack("%32S*",$username.' ');
                   8088: 	
                   8089: 	my $nameseed=numval($username) << 21;
1.501     albertel 8090: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8091: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8092: 	
                   8093: 	my $num1=$symbchck+$symbseed+$namechck;
                   8094: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8095: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8096: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8097: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8098: 	return "$num1,$num2";
                   8099:     }
                   8100: }
                   8101: 
                   8102: sub rndseed_64bit3 {
                   8103:     my ($symb,$courseid,$domain,$username)=@_;
                   8104:     {
                   8105: 	use integer;
                   8106: 	# strings need to be an even # of cahracters long, it it is odd the
                   8107:         # last characters gets thrown away
                   8108: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8109: 	my $symbseed=numval2($symb) << 10;
                   8110: 	my $namechck=unpack("%32S*",$username.' ');
                   8111: 	
                   8112: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8113: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8114: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8115: 	
                   8116: 	my $num1=$symbchck+$symbseed+$namechck;
                   8117: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8118: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8119: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8120: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8121: 	
1.503     albertel 8122: 	return "$num1:$num2";
1.443     albertel 8123:     }
                   8124: }
                   8125: 
1.575     albertel 8126: sub rndseed_64bit4 {
                   8127:     my ($symb,$courseid,$domain,$username)=@_;
                   8128:     {
                   8129: 	use integer;
                   8130: 	# strings need to be an even # of cahracters long, it it is odd the
                   8131:         # last characters gets thrown away
                   8132: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8133: 	my $symbseed=numval3($symb) << 10;
                   8134: 	my $namechck=unpack("%32S*",$username.' ');
                   8135: 	
                   8136: 	my $nameseed=numval3($username) << 21;
                   8137: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8138: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8139: 	
                   8140: 	my $num1=$symbchck+$symbseed+$namechck;
                   8141: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8142: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8143: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8144: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8145: 	
                   8146: 	return "$num1:$num2";
                   8147:     }
                   8148: }
                   8149: 
1.675     albertel 8150: sub rndseed_64bit5 {
                   8151:     my ($symb,$courseid,$domain,$username)=@_;
                   8152:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8153:     return "$num1:$num2";
                   8154: }
                   8155: 
1.366     albertel 8156: sub rndseed_CODE_64bit {
                   8157:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8158:     {
1.366     albertel 8159: 	use integer;
1.443     albertel 8160: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8161: 	my $symbseed=numval2($symb);
1.491     albertel 8162: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8163: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8164: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8165: 	my $num1=$symbseed+$CODEchck;
                   8166: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8167: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8168: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8169: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8170: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8171: 	return "$num1:$num2";
1.366     albertel 8172:     }
                   8173: }
                   8174: 
1.575     albertel 8175: sub rndseed_CODE_64bit4 {
                   8176:     my ($symb,$courseid,$domain,$username)=@_;
                   8177:     {
                   8178: 	use integer;
                   8179: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8180: 	my $symbseed=numval3($symb);
                   8181: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8182: 	my $CODEseed=numval3(&getCODE());
                   8183: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8184: 	my $num1=$symbseed+$CODEchck;
                   8185: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8186: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8187: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8188: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8189: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8190: 	return "$num1:$num2";
                   8191:     }
                   8192: }
                   8193: 
1.675     albertel 8194: sub rndseed_CODE_64bit5 {
                   8195:     my ($symb,$courseid,$domain,$username)=@_;
                   8196:     my $code = &getCODE();
                   8197:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8198:     return "$num1:$num2";
                   8199: }
                   8200: 
1.366     albertel 8201: sub setup_random_from_rndseed {
                   8202:     my ($rndseed)=@_;
1.503     albertel 8203:     if ($rndseed =~/([,:])/) {
                   8204: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8205: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8206:     } else {
                   8207: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8208:     }
1.36      albertel 8209: }
                   8210: 
1.474     albertel 8211: sub latest_receipt_algorithm_id {
1.835     albertel 8212:     return 'receipt3';
1.474     albertel 8213: }
                   8214: 
1.480     www      8215: sub recunique {
                   8216:     my $fucourseid=shift;
                   8217:     my $unique;
1.835     albertel 8218:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8219: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8220: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8221:     } else {
                   8222: 	$unique=$perlvar{'lonReceipt'};
                   8223:     }
                   8224:     return unpack("%32C*",$unique);
                   8225: }
                   8226: 
                   8227: sub recprefix {
                   8228:     my $fucourseid=shift;
                   8229:     my $prefix;
1.835     albertel 8230:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8231: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8232: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8233:     } else {
                   8234: 	$prefix=$perlvar{'lonHostID'};
                   8235:     }
                   8236:     return unpack("%32C*",$prefix);
                   8237: }
                   8238: 
1.76      www      8239: sub ireceipt {
1.474     albertel 8240:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8241: 
                   8242:     my $return =&recprefix($fucourseid).'-';
                   8243: 
                   8244:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8245: 	$env{'request.state'} eq 'construct') {
                   8246: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8247: 	return $return;
                   8248:     }
                   8249: 
1.76      www      8250:     my $cuname=unpack("%32C*",$funame);
                   8251:     my $cudom=unpack("%32C*",$fudom);
                   8252:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8253:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8254:     my $cunique=&recunique($fucourseid);
1.474     albertel 8255:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8256:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8257: 
1.790     albertel 8258: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8259: 			       
                   8260: 	$return.= ($cunique%$cuname+
                   8261: 		   $cunique%$cudom+
                   8262: 		   $cusymb%$cuname+
                   8263: 		   $cusymb%$cudom+
                   8264: 		   $cucourseid%$cuname+
                   8265: 		   $cucourseid%$cudom+
                   8266: 		   $cpart%$cuname+
                   8267: 		   $cpart%$cudom);
                   8268:     } else {
                   8269: 	$return.= ($cunique%$cuname+
                   8270: 		   $cunique%$cudom+
                   8271: 		   $cusymb%$cuname+
                   8272: 		   $cusymb%$cudom+
                   8273: 		   $cucourseid%$cuname+
                   8274: 		   $cucourseid%$cudom);
                   8275:     }
                   8276:     return $return;
1.76      www      8277: }
                   8278: 
                   8279: sub receipt {
1.474     albertel 8280:     my ($part)=@_;
1.790     albertel 8281:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8282:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8283: }
1.260     ng       8284: 
1.790     albertel 8285: sub whichuser {
                   8286:     my ($passedsymb)=@_;
                   8287:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8288:     if (defined($env{'form.grade_symb'})) {
                   8289: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8290: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8291: 	if (!$allowed &&
                   8292: 	    exists($env{'request.course.sec'}) &&
                   8293: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8294: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8295: 			      '/'.$env{'request.course.sec'});
                   8296: 	}
                   8297: 	if ($allowed) {
                   8298: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8299: 	    $courseid=$tmp_courseid;
                   8300: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8301: 	    ($name)=&get_env_multiple('form.grade_username');
                   8302: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8303: 	}
                   8304:     }
                   8305:     if (!$passedsymb) {
                   8306: 	$symb=&symbread();
                   8307:     } else {
                   8308: 	$symb=$passedsymb;
                   8309:     }
                   8310:     $courseid=$env{'request.course.id'};
                   8311:     $domain=$env{'user.domain'};
                   8312:     $name=$env{'user.name'};
                   8313:     if ($name eq 'public' && $domain eq 'public') {
                   8314: 	if (!defined($env{'form.username'})) {
                   8315: 	    $env{'form.username'}.=time.rand(10000000);
                   8316: 	}
                   8317: 	$name.=$env{'form.username'};
                   8318:     }
                   8319:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8320: 
                   8321: }
                   8322: 
1.36      albertel 8323: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8324: # returns either the contents of the file or 
                   8325: # -1 if the file doesn't exist
1.481     raeburn  8326: #
                   8327: # if the target is a file that was uploaded via DOCS, 
                   8328: # a check will be made to see if a current copy exists on the local server,
                   8329: # if it does this will be served, otherwise a copy will be retrieved from
                   8330: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8331: # the local server.   
1.472     albertel 8332: 
1.36      albertel 8333: sub getfile {
1.538     albertel 8334:     my ($file) = @_;
1.609     banghart 8335:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8336:     &repcopy($file);
                   8337:     return &readfile($file);
                   8338: }
                   8339: 
                   8340: sub repcopy_userfile {
                   8341:     my ($file)=@_;
1.609     banghart 8342:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8343:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8344:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8345: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8346:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8347:     if (-e "$file") {
1.828     www      8348: # we already have a local copy, check it out
1.538     albertel 8349: 	my @fileinfo = stat($file);
1.828     www      8350: 	my $rtncode;
                   8351: 	my $info;
1.538     albertel 8352: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8353: 	if ($lwpresp ne 'ok') {
1.828     www      8354: # there is no such file anymore, even though we had a local copy
1.482     albertel 8355: 	    if ($rtncode eq '404') {
1.538     albertel 8356: 		unlink($file);
1.482     albertel 8357: 	    }
                   8358: 	    return -1;
                   8359: 	}
                   8360: 	if ($info < $fileinfo[9]) {
1.828     www      8361: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8362: 	    return 'ok';
1.828     www      8363: 	} else {
                   8364: # the file is outdated, get rid of it
                   8365: 	    unlink($file);
1.482     albertel 8366: 	}
1.828     www      8367:     }
                   8368: # one way or the other, at this point, we don't have the file
                   8369: # construct the correct path for the file
                   8370:     my @parts = ($cdom,$cnum); 
                   8371:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8372: 	push @parts, split(/\//,$1);
                   8373:     }
                   8374:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8375:     foreach my $part (@parts) {
                   8376: 	$path .= '/'.$part;
                   8377: 	if (!-e $path) {
                   8378: 	    mkdir($path,0770);
1.482     albertel 8379: 	}
                   8380:     }
1.828     www      8381: # now the path exists for sure
                   8382: # get a user agent
                   8383:     my $ua=new LWP::UserAgent;
                   8384:     my $transferfile=$file.'.in.transfer';
                   8385: # FIXME: this should flock
                   8386:     if (-e $transferfile) { return 'ok'; }
                   8387:     my $request;
                   8388:     $uri=~s/^\///;
1.980     raeburn  8389:     my $homeserver = &homeserver($cnum,$cdom);
                   8390:     my $protocol = $protocol{$homeserver};
                   8391:     $protocol = 'http' if ($protocol ne 'https');
                   8392:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8393:     my $response=$ua->request($request,$transferfile);
                   8394: # did it work?
                   8395:     if ($response->is_error()) {
                   8396: 	unlink($transferfile);
                   8397: 	&logthis("Userfile repcopy failed for $uri");
                   8398: 	return -1;
                   8399:     }
                   8400: # worked, rename the transfer file
                   8401:     rename($transferfile,$file);
1.607     raeburn  8402:     return 'ok';
1.481     raeburn  8403: }
                   8404: 
1.517     albertel 8405: sub tokenwrapper {
                   8406:     my $uri=shift;
1.980     raeburn  8407:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8408:     $uri=~s|^/||;
1.620     albertel 8409:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8410:     my $token=$1;
1.552     albertel 8411:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8412:     if ($udom && $uname && $file) {
                   8413: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8414:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8415:         my $homeserver = &homeserver($uname,$udom);
                   8416:         my $protocol = $protocol{$homeserver};
                   8417:         $protocol = 'http' if ($protocol ne 'https');
                   8418:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8419:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8420:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8421:     } else {
                   8422:         return '/adm/notfound.html';
                   8423:     }
                   8424: }
                   8425: 
1.828     www      8426: # call with reqtype HEAD: get last modification time
                   8427: # call with reqtype GET: get the file contents
                   8428: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8429: #
1.481     raeburn  8430: sub getuploaded {
                   8431:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8432:     $uri=~s/^\///;
1.980     raeburn  8433:     my $homeserver = &homeserver($cnum,$cdom);
                   8434:     my $protocol = $protocol{$homeserver};
                   8435:     $protocol = 'http' if ($protocol ne 'https');
                   8436:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8437:     my $ua=new LWP::UserAgent;
                   8438:     my $request=new HTTP::Request($reqtype,$uri);
                   8439:     my $response=$ua->request($request);
                   8440:     $$rtncode = $response->code;
1.482     albertel 8441:     if (! $response->is_success()) {
                   8442: 	return 'failed';
                   8443:     }      
                   8444:     if ($reqtype eq 'HEAD') {
1.486     www      8445: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8446:     } elsif ($reqtype eq 'GET') {
                   8447: 	$$info = $response->content;
1.472     albertel 8448:     }
1.482     albertel 8449:     return 'ok';
1.36      albertel 8450: }
                   8451: 
1.481     raeburn  8452: sub readfile {
                   8453:     my $file = shift;
                   8454:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8455:     my $fh;
                   8456:     open($fh,"<$file");
                   8457:     my $a='';
1.800     albertel 8458:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8459:     return $a;
                   8460: }
                   8461: 
1.36      albertel 8462: sub filelocation {
1.590     banghart 8463:     my ($dir,$file) = @_;
                   8464:     my $location;
                   8465:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8466: 
                   8467:     if ($file =~ m-^/adm/-) {
                   8468: 	$file=~s-^/adm/wrapper/-/-;
                   8469: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8470:     }
1.882     albertel 8471: 
1.590     banghart 8472:     if ($file=~m:^/~:) { # is a contruction space reference
                   8473:         $location = $file;
                   8474:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8475:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8476: 	# is a correct contruction space reference
                   8477:         $location = $file;
1.956     raeburn  8478:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8479:         $location = $file;
1.609     banghart 8480:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8481:         my ($udom,$uname,$filename)=
1.811     albertel 8482:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8483:         my $home=&homeserver($uname,$udom);
                   8484:         my $is_me=0;
                   8485:         my @ids=&current_machine_ids();
                   8486:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8487:         if ($is_me) {
1.955     raeburn  8488:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8489:         } else {
                   8490:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8491:   	      $udom.'/'.$uname.'/'.$filename;
                   8492:         }
1.882     albertel 8493:     } elsif ($file =~ m-^/adm/-) {
                   8494: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8495:     } else {
                   8496:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8497:         $file=~s:^/res/:/:;
                   8498:         if ( !( $file =~ m:^/:) ) {
                   8499:             $location = $dir. '/'.$file;
                   8500:         } else {
                   8501:             $location = '/home/httpd/html/res'.$file;
                   8502:         }
1.59      albertel 8503:     }
1.590     banghart 8504:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8505:     while ($location=~m{/\.\./}) {
                   8506: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8507: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8508: 	} else {
                   8509: 	    $location=~ s{/\.\./}{/}g;
                   8510: 	}
                   8511:     } #remove dir/..
1.590     banghart 8512:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8513:     return $location;
1.46      www      8514: }
1.36      albertel 8515: 
1.46      www      8516: sub hreflocation {
                   8517:     my ($dir,$file)=@_;
1.980     raeburn  8518:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8519: 	$file=filelocation($dir,$file);
1.700     albertel 8520:     } elsif ($file=~m-^/adm/-) {
                   8521: 	$file=~s-^/adm/wrapper/-/-;
                   8522: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8523:     }
                   8524:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8525: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8526:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8527: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8528:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8529: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8530: 	    -/uploaded/$1/$2/-x;
1.46      www      8531:     }
1.913     albertel 8532:     if ($file=~ m{^/userfiles/}) {
                   8533: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8534:     }
1.462     albertel 8535:     return $file;
1.465     albertel 8536: }
                   8537: 
                   8538: sub current_machine_domains {
1.853     albertel 8539:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8540: }
                   8541: 
                   8542: sub machine_domains {
                   8543:     my ($hostname) = @_;
1.465     albertel 8544:     my @domains;
1.838     albertel 8545:     my %hostname = &all_hostnames();
1.465     albertel 8546:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8547: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8548: 	if ($hostname eq $name) {
1.844     albertel 8549: 	    push(@domains,&host_domain($id));
1.465     albertel 8550: 	}
                   8551:     }
                   8552:     return @domains;
                   8553: }
                   8554: 
                   8555: sub current_machine_ids {
1.853     albertel 8556:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8557: }
                   8558: 
                   8559: sub machine_ids {
                   8560:     my ($hostname) = @_;
                   8561:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8562:     my @ids;
1.888     albertel 8563:     my %name_to_host = &all_names();
1.889     albertel 8564:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8565: 	return @{ $name_to_host{$hostname} };
                   8566:     }
                   8567:     return;
1.31      www      8568: }
                   8569: 
1.824     raeburn  8570: sub additional_machine_domains {
                   8571:     my @domains;
                   8572:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8573:     while( my $line = <$fh>) {
                   8574:         $line =~ s/\s//g;
                   8575:         push(@domains,$line);
                   8576:     }
                   8577:     return @domains;
                   8578: }
                   8579: 
                   8580: sub default_login_domain {
                   8581:     my $domain = $perlvar{'lonDefDomain'};
                   8582:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8583:     foreach my $posdom (&current_machine_domains(),
                   8584:                         &additional_machine_domains()) {
                   8585:         if (lc($posdom) eq lc($testdomain)) {
                   8586:             $domain=$posdom;
                   8587:             last;
                   8588:         }
                   8589:     }
                   8590:     return $domain;
                   8591: }
                   8592: 
1.31      www      8593: # ------------------------------------------------------------- Declutters URLs
                   8594: 
                   8595: sub declutter {
                   8596:     my $thisfn=shift;
1.569     albertel 8597:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8598:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8599:     $thisfn=~s/^\///;
1.697     albertel 8600:     $thisfn=~s|^adm/wrapper/||;
                   8601:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8602:     $thisfn=~s/^res\///;
1.235     www      8603:     $thisfn=~s/\?.+$//;
1.268     www      8604:     return $thisfn;
                   8605: }
                   8606: 
                   8607: # ------------------------------------------------------------- Clutter up URLs
                   8608: 
                   8609: sub clutter {
                   8610:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8611:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8612: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8613:        $thisfn='/res'.$thisfn; 
                   8614:     }
1.694     albertel 8615:     if ($thisfn !~m|/adm|) {
1.695     albertel 8616: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8617: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8618: 	} else {
                   8619: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8620: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8621: 	    if ($embstyle eq 'ssi'
                   8622: 		|| ($embstyle eq 'hdn')
                   8623: 		|| ($embstyle eq 'rat')
                   8624: 		|| ($embstyle eq 'prv')
                   8625: 		|| ($embstyle eq 'ign')) {
                   8626: 		#do nothing with these
                   8627: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8628: 		|| ($embstyle eq 'emb')
                   8629: 		|| ($embstyle eq 'wrp')) {
                   8630: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8631: 	    } elsif ($embstyle eq 'unk'
                   8632: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8633: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8634: 	    } else {
1.718     www      8635: #		&logthis("Got a blank emb style");
1.695     albertel 8636: 	    }
1.694     albertel 8637: 	}
                   8638:     }
1.31      www      8639:     return $thisfn;
1.12      www      8640: }
                   8641: 
1.787     albertel 8642: sub clutter_with_no_wrapper {
                   8643:     my $uri = &clutter(shift);
                   8644:     if ($uri =~ m-^/adm/-) {
                   8645: 	$uri =~ s-^/adm/wrapper/-/-;
                   8646: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8647:     }
                   8648:     return $uri;
                   8649: }
                   8650: 
1.557     albertel 8651: sub freeze_escape {
                   8652:     my ($value)=@_;
                   8653:     if (ref($value)) {
                   8654: 	$value=&nfreeze($value);
                   8655: 	return '__FROZEN__'.&escape($value);
                   8656:     }
                   8657:     return &escape($value);
                   8658: }
                   8659: 
1.11      www      8660: 
1.557     albertel 8661: sub thaw_unescape {
                   8662:     my ($value)=@_;
                   8663:     if ($value =~ /^__FROZEN__/) {
                   8664: 	substr($value,0,10,undef);
                   8665: 	$value=&unescape($value);
                   8666: 	return &thaw($value);
                   8667:     }
                   8668:     return &unescape($value);
                   8669: }
                   8670: 
1.436     albertel 8671: sub correct_line_ends {
                   8672:     my ($result)=@_;
                   8673:     $$result =~s/\r\n/\n/mg;
                   8674:     $$result =~s/\r/\n/mg;
1.415     albertel 8675: }
1.1       albertel 8676: # ================================================================ Main Program
                   8677: 
1.184     www      8678: sub goodbye {
1.204     albertel 8679:    &logthis("Starting Shut down");
1.443     albertel 8680: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8681:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8682: #converted
1.599     albertel 8683: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8684:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8685: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8686: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8687: #1.1 only
1.870     albertel 8688: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8689: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8690: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8691: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8692:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8693:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8694:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8695:    &flushcourselogs();
                   8696:    &logthis("Shutting down");
                   8697: }
                   8698: 
1.852     albertel 8699: sub get_dns {
1.869     albertel 8700:     my ($url,$func,$ignore_cache) = @_;
                   8701:     if (!$ignore_cache) {
                   8702: 	my ($content,$cached)=
                   8703: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8704: 	if ($cached) {
                   8705: 	    &$func($content);
                   8706: 	    return;
                   8707: 	}
                   8708:     }
                   8709: 
                   8710:     my %alldns;
1.852     albertel 8711:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8712:     foreach my $dns (<$config>) {
                   8713: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8714:         my $line = $1;
                   8715:         my ($host,$protocol) = split(/:/,$line);
                   8716:         if ($protocol ne 'https') {
                   8717:             $protocol = 'http';
                   8718:         }
                   8719: 	$alldns{$host} = $protocol;
1.869     albertel 8720:     }
                   8721:     while (%alldns) {
                   8722: 	my ($dns) = keys(%alldns);
1.852     albertel 8723: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8724: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8725: 	my $response=$ua->request($request);
1.979     raeburn  8726:         delete($alldns{$dns});
1.852     albertel 8727: 	next if ($response->is_error());
                   8728: 	my @content = split("\n",$response->content);
1.869     albertel 8729: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8730: 	&$func(\@content);
1.869     albertel 8731: 	return;
1.852     albertel 8732:     }
                   8733:     close($config);
1.871     albertel 8734:     my $which = (split('/',$url))[3];
                   8735:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8736:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8737:     my @content = <$config>;
                   8738:     &$func(\@content);
                   8739:     return;
1.852     albertel 8740: }
1.327     albertel 8741: # ------------------------------------------------------------ Read domain file
                   8742: {
1.852     albertel 8743:     my $loaded;
1.846     albertel 8744:     my %domain;
                   8745: 
1.852     albertel 8746:     sub parse_domain_tab {
                   8747: 	my ($lines) = @_;
                   8748: 	foreach my $line (@$lines) {
                   8749: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8750: 
1.846     albertel 8751: 	    chomp($line);
1.852     albertel 8752: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8753: 	    my %this_domain;
                   8754: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8755: 			       'lang_def', 'city', 'longi', 'lati',
                   8756: 			       'primary') {
                   8757: 		$this_domain{$field} = shift(@elements);
                   8758: 	    }
                   8759: 	    $domain{$name} = \%this_domain;
1.852     albertel 8760: 	}
                   8761:     }
1.864     albertel 8762: 
                   8763:     sub reset_domain_info {
                   8764: 	undef($loaded);
                   8765: 	undef(%domain);
                   8766:     }
                   8767: 
1.852     albertel 8768:     sub load_domain_tab {
1.869     albertel 8769: 	my ($ignore_cache) = @_;
                   8770: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8771: 	my $fh;
                   8772: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8773: 	    my @lines = <$fh>;
                   8774: 	    &parse_domain_tab(\@lines);
1.448     albertel 8775: 	}
1.852     albertel 8776: 	close($fh);
                   8777: 	$loaded = 1;
1.327     albertel 8778:     }
1.846     albertel 8779: 
                   8780:     sub domain {
1.852     albertel 8781: 	&load_domain_tab() if (!$loaded);
                   8782: 
1.846     albertel 8783: 	my ($name,$what) = @_;
                   8784: 	return if ( !exists($domain{$name}) );
                   8785: 
                   8786: 	if (!$what) {
                   8787: 	    return $domain{$name}{'description'};
                   8788: 	}
                   8789: 	return $domain{$name}{$what};
                   8790:     }
1.974     raeburn  8791: 
                   8792:     sub domain_info {
                   8793:         &load_domain_tab() if (!$loaded);
                   8794:         return %domain;
                   8795:     }
                   8796: 
1.327     albertel 8797: }
                   8798: 
                   8799: 
1.1       albertel 8800: # ------------------------------------------------------------- Read hosts file
                   8801: {
1.838     albertel 8802:     my %hostname;
1.844     albertel 8803:     my %hostdom;
1.845     albertel 8804:     my %libserv;
1.852     albertel 8805:     my $loaded;
1.888     albertel 8806:     my %name_to_host;
1.852     albertel 8807: 
                   8808:     sub parse_hosts_tab {
                   8809: 	my ($file) = @_;
                   8810: 	foreach my $configline (@$file) {
                   8811: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8812: 	    next if ($configline =~ /^\^/);
                   8813: 	    chomp($configline);
1.968     raeburn  8814: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8815: 	    $name=~s/\s//g;
                   8816: 	    if ($id && $domain && $role && $name) {
                   8817: 		$hostname{$id}=$name;
1.888     albertel 8818: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8819: 		$hostdom{$id}=$domain;
                   8820: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8821:                 if (defined($protocol)) {
                   8822:                     if ($protocol eq 'https') {
                   8823:                         $protocol{$id} = $protocol;
                   8824:                     } else {
                   8825:                         $protocol{$id} = 'http'; 
                   8826:                     }
1.968     raeburn  8827:                 } else {
1.969     raeburn  8828:                     $protocol{$id} = 'http';
1.968     raeburn  8829:                 }
1.852     albertel 8830: 	    }
                   8831: 	}
                   8832:     }
1.864     albertel 8833:     
                   8834:     sub reset_hosts_info {
1.897     albertel 8835: 	&purge_remembered();
1.864     albertel 8836: 	&reset_domain_info();
                   8837: 	&reset_hosts_ip_info();
1.892     albertel 8838: 	undef(%name_to_host);
1.864     albertel 8839: 	undef(%hostname);
                   8840: 	undef(%hostdom);
                   8841: 	undef(%libserv);
                   8842: 	undef($loaded);
                   8843:     }
1.1       albertel 8844: 
1.852     albertel 8845:     sub load_hosts_tab {
1.869     albertel 8846: 	my ($ignore_cache) = @_;
                   8847: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8848: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8849: 	my @config = <$config>;
                   8850: 	&parse_hosts_tab(\@config);
                   8851: 	close($config);
                   8852: 	$loaded=1;
1.1       albertel 8853:     }
1.852     albertel 8854: 
1.838     albertel 8855:     sub hostname {
1.852     albertel 8856: 	&load_hosts_tab() if (!$loaded);
                   8857: 
1.838     albertel 8858: 	my ($lonid) = @_;
                   8859: 	return $hostname{$lonid};
                   8860:     }
1.845     albertel 8861: 
1.838     albertel 8862:     sub all_hostnames {
1.852     albertel 8863: 	&load_hosts_tab() if (!$loaded);
                   8864: 
1.838     albertel 8865: 	return %hostname;
                   8866:     }
1.845     albertel 8867: 
1.888     albertel 8868:     sub all_names {
                   8869: 	&load_hosts_tab() if (!$loaded);
                   8870: 
                   8871: 	return %name_to_host;
                   8872:     }
                   8873: 
1.974     raeburn  8874:     sub all_host_domain {
                   8875:         &load_hosts_tab() if (!$loaded);
                   8876:         return %hostdom;
                   8877:     }
                   8878: 
1.845     albertel 8879:     sub is_library {
1.852     albertel 8880: 	&load_hosts_tab() if (!$loaded);
                   8881: 
1.845     albertel 8882: 	return exists($libserv{$_[0]});
                   8883:     }
                   8884: 
                   8885:     sub all_library {
1.852     albertel 8886: 	&load_hosts_tab() if (!$loaded);
                   8887: 
1.845     albertel 8888: 	return %libserv;
                   8889:     }
                   8890: 
1.841     albertel 8891:     sub get_servers {
1.852     albertel 8892: 	&load_hosts_tab() if (!$loaded);
                   8893: 
1.841     albertel 8894: 	my ($domain,$type) = @_;
                   8895: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8896: 	                                          : %hostname;
                   8897: 	my %result;
1.842     albertel 8898: 	if (ref($domain) eq 'ARRAY') {
                   8899: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8900: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8901: 		    $result{$host} = $hostname;
                   8902: 		}
                   8903: 	    }
                   8904: 	} else {
                   8905: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8906: 		if ($hostdom{$host} eq $domain) {
                   8907: 		    $result{$host} = $hostname;
                   8908: 		}
1.841     albertel 8909: 	    }
                   8910: 	}
                   8911: 	return %result;
                   8912:     }
1.845     albertel 8913: 
1.844     albertel 8914:     sub host_domain {
1.852     albertel 8915: 	&load_hosts_tab() if (!$loaded);
                   8916: 
1.844     albertel 8917: 	my ($lonid) = @_;
                   8918: 	return $hostdom{$lonid};
                   8919:     }
                   8920: 
1.841     albertel 8921:     sub all_domains {
1.852     albertel 8922: 	&load_hosts_tab() if (!$loaded);
                   8923: 
1.841     albertel 8924: 	my %seen;
                   8925: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8926: 	return @uniq;
                   8927:     }
1.1       albertel 8928: }
                   8929: 
1.847     albertel 8930: { 
                   8931:     my %iphost;
1.856     albertel 8932:     my %name_to_ip;
                   8933:     my %lonid_to_ip;
1.869     albertel 8934: 
1.847     albertel 8935:     sub get_hosts_from_ip {
                   8936: 	my ($ip) = @_;
                   8937: 	my %iphosts = &get_iphost();
                   8938: 	if (ref($iphosts{$ip})) {
                   8939: 	    return @{$iphosts{$ip}};
                   8940: 	}
                   8941: 	return;
1.839     albertel 8942:     }
1.864     albertel 8943:     
                   8944:     sub reset_hosts_ip_info {
                   8945: 	undef(%iphost);
                   8946: 	undef(%name_to_ip);
                   8947: 	undef(%lonid_to_ip);
                   8948:     }
1.856     albertel 8949: 
                   8950:     sub get_host_ip {
                   8951: 	my ($lonid) = @_;
                   8952: 	if (exists($lonid_to_ip{$lonid})) {
                   8953: 	    return $lonid_to_ip{$lonid};
                   8954: 	}
                   8955: 	my $name=&hostname($lonid);
                   8956:    	my $ip = gethostbyname($name);
                   8957: 	return if (!$ip || length($ip) ne 4);
                   8958: 	$ip=inet_ntoa($ip);
                   8959: 	$name_to_ip{$name}   = $ip;
                   8960: 	$lonid_to_ip{$lonid} = $ip;
                   8961: 	return $ip;
                   8962:     }
1.847     albertel 8963:     
                   8964:     sub get_iphost {
1.869     albertel 8965: 	my ($ignore_cache) = @_;
1.894     albertel 8966: 
1.869     albertel 8967: 	if (!$ignore_cache) {
                   8968: 	    if (%iphost) {
                   8969: 		return %iphost;
                   8970: 	    }
                   8971: 	    my ($ip_info,$cached)=
                   8972: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8973: 	    if ($cached) {
                   8974: 		%iphost      = %{$ip_info->[0]};
                   8975: 		%name_to_ip  = %{$ip_info->[1]};
                   8976: 		%lonid_to_ip = %{$ip_info->[2]};
                   8977: 		return %iphost;
                   8978: 	    }
                   8979: 	}
1.894     albertel 8980: 
                   8981: 	# get yesterday's info for fallback
                   8982: 	my %old_name_to_ip;
                   8983: 	my ($ip_info,$cached)=
                   8984: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8985: 	if ($cached) {
                   8986: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8987: 	}
                   8988: 
1.888     albertel 8989: 	my %name_to_host = &all_names();
                   8990: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8991: 	    my $ip;
                   8992: 	    if (!exists($name_to_ip{$name})) {
                   8993: 		$ip = gethostbyname($name);
                   8994: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8995: 		    if (defined($old_name_to_ip{$name})) {
                   8996: 			$ip = $old_name_to_ip{$name};
                   8997: 			&logthis("Can't find $name defaulting to old $ip");
                   8998: 		    } else {
                   8999: 			&logthis("Name $name no IP found");
                   9000: 			next;
                   9001: 		    }
                   9002: 		} else {
                   9003: 		    $ip=inet_ntoa($ip);
1.847     albertel 9004: 		}
                   9005: 		$name_to_ip{$name} = $ip;
                   9006: 	    } else {
                   9007: 		$ip = $name_to_ip{$name};
1.653     albertel 9008: 	    }
1.888     albertel 9009: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9010: 		$lonid_to_ip{$id} = $ip;
                   9011: 	    }
                   9012: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9013: 	}
1.869     albertel 9014: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9015: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9016: 				      48*60*60);
1.869     albertel 9017: 
1.847     albertel 9018: 	return %iphost;
1.598     albertel 9019:     }
                   9020: }
                   9021: 
1.986     foxr     9022: #
                   9023: #  Given a DNS returns the loncapa host name for that DNS 
                   9024: # 
                   9025: sub host_from_dns {
                   9026:     my ($dns) = @_;
                   9027:     my @hosts;
                   9028:     my $ip;
                   9029: 
                   9030:     $ip = gethostbyname($dns);	# Initial translation to IP is in net order.
                   9031:     if (length($ip) == 4) { 
                   9032: 	$ip   = &IO::Socket::inet_ntoa($ip);
                   9033: 	@hosts = get_hosts_from_ip($ip);
                   9034: 	return $hosts[0];
                   9035:     }
                   9036:     return undef;
                   9037: }
                   9038: 
1.862     albertel 9039: BEGIN {
                   9040: 
                   9041: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9042:     unless ($readit) {
                   9043: {
                   9044:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9045:     %perlvar = (%perlvar,%{$configvars});
                   9046: }
                   9047: 
                   9048: 
1.1       albertel 9049: # ------------------------------------------------------ Read spare server file
                   9050: {
1.448     albertel 9051:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9052: 
                   9053:     while (my $configline=<$config>) {
                   9054:        chomp($configline);
1.284     matthew  9055:        if ($configline) {
1.784     albertel 9056: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9057: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9058: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9059:        }
                   9060:     }
1.448     albertel 9061:     close($config);
1.1       albertel 9062: }
1.11      www      9063: # ------------------------------------------------------------ Read permissions
                   9064: {
1.448     albertel 9065:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9066: 
                   9067:     while (my $configline=<$config>) {
1.448     albertel 9068: 	chomp($configline);
                   9069: 	if ($configline) {
                   9070: 	    my ($role,$perm)=split(/ /,$configline);
                   9071: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9072: 	}
1.11      www      9073:     }
1.448     albertel 9074:     close($config);
1.11      www      9075: }
                   9076: 
                   9077: # -------------------------------------------- Read plain texts for permissions
                   9078: {
1.448     albertel 9079:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9080: 
                   9081:     while (my $configline=<$config>) {
1.448     albertel 9082: 	chomp($configline);
                   9083: 	if ($configline) {
1.742     raeburn  9084: 	    my ($short,@plain)=split(/:/,$configline);
                   9085:             %{$prp{$short}} = ();
                   9086: 	    if (@plain > 0) {
                   9087:                 $prp{$short}{'std'} = $plain[0];
                   9088:                 for (my $i=1; $i<@plain; $i++) {
                   9089:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9090:                 }
                   9091:             }
1.448     albertel 9092: 	}
1.135     www      9093:     }
1.448     albertel 9094:     close($config);
1.135     www      9095: }
                   9096: 
                   9097: # ---------------------------------------------------------- Read package table
                   9098: {
1.448     albertel 9099:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9100: 
                   9101:     while (my $configline=<$config>) {
1.483     albertel 9102: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9103: 	chomp($configline);
                   9104: 	my ($short,$plain)=split(/:/,$configline);
                   9105: 	my ($pack,$name)=split(/\&/,$short);
                   9106: 	if ($plain ne '') {
                   9107: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9108: 	    $packagetab{$short}=$plain; 
                   9109: 	}
1.11      www      9110:     }
1.448     albertel 9111:     close($config);
1.329     matthew  9112: }
                   9113: 
                   9114: # ------------- set up temporary directory
                   9115: {
                   9116:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9117: 
1.11      www      9118: }
                   9119: 
1.794     albertel 9120: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9121: 				'compress_threshold'=> 20_000,
                   9122:  			        });
1.185     www      9123: 
1.281     www      9124: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9125: $dumpcount=0;
1.958     www      9126: $locknum=0;
1.22      www      9127: 
1.163     harris41 9128: &logtouch();
1.672     albertel 9129: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9130: $readit=1;
1.564     albertel 9131:     {
                   9132: 	use integer;
                   9133: 	my $test=(2**32)+1;
1.568     albertel 9134: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9135: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9136:     }
1.195     www      9137: }
1.1       albertel 9138: }
1.179     www      9139: 
1.1       albertel 9140: 1;
1.191     harris41 9141: __END__
                   9142: 
1.243     albertel 9143: =pod
                   9144: 
1.191     harris41 9145: =head1 NAME
                   9146: 
1.243     albertel 9147: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9148: 
                   9149: =head1 SYNOPSIS
                   9150: 
1.243     albertel 9151: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9152: 
                   9153:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9154: 
1.243     albertel 9155: Common parameters:
                   9156: 
                   9157: =over 4
                   9158: 
                   9159: =item *
                   9160: 
                   9161: $uname : an internal username (if $cname expecting a course Id specifically)
                   9162: 
                   9163: =item *
                   9164: 
                   9165: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9166: 
                   9167: =item *
                   9168: 
                   9169: $symb : a resource instance identifier
                   9170: 
                   9171: =item *
                   9172: 
                   9173: $namespace : the name of a .db file that contains the data needed or
                   9174: being set.
                   9175: 
                   9176: =back
                   9177: 
1.394     bowersj2 9178: =head1 OVERVIEW
1.191     harris41 9179: 
1.394     bowersj2 9180: lonnet provides subroutines which interact with the
                   9181: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9182: about classes, users, and resources.
1.243     albertel 9183: 
                   9184: For many of these objects you can also use this to store data about
                   9185: them or modify them in various ways.
1.191     harris41 9186: 
1.394     bowersj2 9187: =head2 Symbs
1.191     harris41 9188: 
1.394     bowersj2 9189: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9190: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9191: map, the resource number of the resource in the map, and the URL of
                   9192: the resource itself. The latter is somewhat redundant, but might help
                   9193: if maps change.
                   9194: 
                   9195: An example is
                   9196: 
                   9197:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9198: 
                   9199: The respective map entry is
                   9200: 
                   9201:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9202:   title="Problem 2">
                   9203:  </resource>
                   9204: 
                   9205: Symbs are used by the random number generator, as well as to store and
                   9206: restore data specific to a certain instance of for example a problem.
                   9207: 
                   9208: =head2 Storing And Retrieving Data
                   9209: 
                   9210: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9211: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9212: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9213: is is the non-critical message twin of cstore. These functions are for
                   9214: handlers to store a perl hash to a user's permanent data space in an
                   9215: easy manner, and to retrieve it again on another call. It is expected
                   9216: that a handler would use this once at the beginning to retrieve data,
                   9217: and then again once at the end to send only the new data back.
                   9218: 
                   9219: The data is stored in the user's data directory on the user's
                   9220: homeserver under the ID of the course.
                   9221: 
                   9222: The hash that is returned by restore will have all of the previous
                   9223: value for all of the elements of the hash.
                   9224: 
                   9225: Example:
                   9226: 
                   9227:  #creating a hash
                   9228:  my %hash;
                   9229:  $hash{'foo'}='bar';
                   9230: 
                   9231:  #storing it
                   9232:  &Apache::lonnet::cstore(\%hash);
                   9233: 
                   9234:  #changing a value
                   9235:  $hash{'foo'}='notbar';
                   9236: 
                   9237:  #adding a new value
                   9238:  $hash{'bar'}='foo';
                   9239:  &Apache::lonnet::cstore(\%hash);
                   9240: 
                   9241:  #retrieving the hash
                   9242:  my %history=&Apache::lonnet::restore();
                   9243: 
                   9244:  #print the hash
                   9245:  foreach my $key (sort(keys(%history))) {
                   9246:    print("\%history{$key} = $history{$key}");
                   9247:  }
                   9248: 
                   9249: Will print out:
1.191     harris41 9250: 
1.394     bowersj2 9251:  %history{1:foo} = bar
                   9252:  %history{1:keys} = foo:timestamp
                   9253:  %history{1:timestamp} = 990455579
                   9254:  %history{2:bar} = foo
                   9255:  %history{2:foo} = notbar
                   9256:  %history{2:keys} = foo:bar:timestamp
                   9257:  %history{2:timestamp} = 990455580
                   9258:  %history{bar} = foo
                   9259:  %history{foo} = notbar
                   9260:  %history{timestamp} = 990455580
                   9261:  %history{version} = 2
                   9262: 
                   9263: Note that the special hash entries C<keys>, C<version> and
                   9264: C<timestamp> were added to the hash. C<version> will be equal to the
                   9265: total number of versions of the data that have been stored. The
                   9266: C<timestamp> attribute will be the UNIX time the hash was
                   9267: stored. C<keys> is available in every historical section to list which
                   9268: keys were added or changed at a specific historical revision of a
                   9269: hash.
                   9270: 
                   9271: B<Warning>: do not store the hash that restore returns directly. This
                   9272: will cause a mess since it will restore the historical keys as if the
                   9273: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9274: 
1.394     bowersj2 9275: Calling convention:
1.191     harris41 9276: 
1.394     bowersj2 9277:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9278:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9279: 
1.394     bowersj2 9280: For more detailed information, see lonnet specific documentation.
1.191     harris41 9281: 
1.394     bowersj2 9282: =head1 RETURN MESSAGES
1.191     harris41 9283: 
1.394     bowersj2 9284: =over 4
1.191     harris41 9285: 
1.394     bowersj2 9286: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9287: 
1.394     bowersj2 9288: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9289: when the connection is brought back up
1.191     harris41 9290: 
1.394     bowersj2 9291: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9292: for later delivery
1.191     harris41 9293: 
1.967     bisitz   9294: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9295: 
1.394     bowersj2 9296: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9297: that was requested
1.191     harris41 9298: 
1.243     albertel 9299: =back
1.191     harris41 9300: 
1.243     albertel 9301: =head1 PUBLIC SUBROUTINES
1.191     harris41 9302: 
1.243     albertel 9303: =head2 Session Environment Functions
1.191     harris41 9304: 
1.243     albertel 9305: =over 4
1.191     harris41 9306: 
1.394     bowersj2 9307: =item * 
                   9308: X<appenv()>
1.949     raeburn  9309: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9310: the user envirnoment file, and will be restored for each access this
1.620     albertel 9311: user makes during this session, also modifies the %env for the current
1.949     raeburn  9312: process. Optional rolesarrayref - if defined contains a reference to an array
                   9313: of roles which are exempt from the restriction on modifying user.role entries 
                   9314: in the user's environment.db and in %env.    
1.191     harris41 9315: 
                   9316: =item *
1.394     bowersj2 9317: X<delenv()>
1.987   ! raeburn  9318: B<delenv($delthis,$regexp)>: removes all items from the session
        !          9319: environment file that begin with $delthis. If the 
        !          9320: optional second arg - $regexp - is true, $delthis is treated as a 
        !          9321: regular expression, otherwise \Q$delthis\E is used. 
        !          9322: The values are also deleted from the current processes %env.
1.191     harris41 9323: 
1.795     albertel 9324: =item * get_env_multiple($name) 
                   9325: 
                   9326: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9327: values may be defined and end up as an array ref.
                   9328: 
                   9329: returns an array of values
                   9330: 
1.243     albertel 9331: =back
                   9332: 
                   9333: =head2 User Information
1.191     harris41 9334: 
1.243     albertel 9335: =over 4
1.191     harris41 9336: 
                   9337: =item *
1.394     bowersj2 9338: X<queryauthenticate()>
                   9339: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9340: authentication scheme
                   9341: 
                   9342: =item *
1.394     bowersj2 9343: X<authenticate()>
                   9344: B<authenticate($uname,$upass,$udom)>: try to
                   9345: authenticate user from domain's lib servers (first use the current
                   9346: one). C<$upass> should be the users password.
1.191     harris41 9347: 
                   9348: =item *
1.394     bowersj2 9349: X<homeserver()>
                   9350: B<homeserver($uname,$udom)>: find the server which has
                   9351: the user's directory and files (there must be only one), this caches
                   9352: the answer, and also caches if there is a borken connection.
1.191     harris41 9353: 
                   9354: =item *
1.394     bowersj2 9355: X<idget()>
                   9356: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9357: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9358: username, and only 1 username per ID in a specific domain) (returns
                   9359: hash: id=>name,id=>name)
1.191     harris41 9360: 
                   9361: =item *
1.394     bowersj2 9362: X<idrget()>
                   9363: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9364: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9365: 
                   9366: =item *
1.394     bowersj2 9367: X<idput()>
                   9368: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9369: 
                   9370: =item *
1.394     bowersj2 9371: X<rolesinit()>
                   9372: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9373: 
                   9374: =item *
1.551     albertel 9375: X<getsection()>
                   9376: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9377: course $cname, return section name/number or '' for "not in course"
                   9378: and '-1' for "no section"
                   9379: 
                   9380: =item *
1.394     bowersj2 9381: X<userenvironment()>
                   9382: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9383: passed in @what from the requested user's environment, returns a hash
                   9384: 
1.858     raeburn  9385: =item * 
                   9386: X<userlog_query()>
1.859     albertel 9387: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9388: activity.log file. %filters defines filters applied when parsing the
                   9389: log file. These can be start or end timestamps, or the type of action
                   9390: - log to look for Login or Logout events, check for Checkin or
                   9391: Checkout, role for role selection. The response is in the form
                   9392: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9393: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9394: 
1.243     albertel 9395: =back
                   9396: 
                   9397: =head2 User Roles
                   9398: 
                   9399: =over 4
                   9400: 
                   9401: =item *
                   9402: 
1.810     raeburn  9403: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9404:  F: full access
                   9405:  U,I,K: authentication modes (cxx only)
                   9406:  '': forbidden
                   9407:  1: user needs to choose course
                   9408:  2: browse allowed
1.766     albertel 9409:  A: passphrase authentication needed
1.243     albertel 9410: 
                   9411: =item *
                   9412: 
                   9413: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9414: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9415: and course level
                   9416: 
                   9417: =item *
                   9418: 
                   9419: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9420: explanation of a user role term
                   9421: 
1.832     raeburn  9422: =item *
                   9423: 
1.935     raeburn  9424: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9425: All arguments are optional. Returns a hash of a roles, either for
                   9426: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9427: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9428: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9429: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9430: For each key, value is set to colon-separated start and end times for
                   9431: the role.  If no username and domain are specified, will default to
1.934     raeburn  9432: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9433: of role statuses (active, future or previous), roles 
                   9434: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9435: to restrict the list of roles reported. If no array ref is 
                   9436: provided for types, will default to return only active roles.
1.834     albertel 9437: 
1.243     albertel 9438: =back
                   9439: 
                   9440: =head2 User Modification
                   9441: 
                   9442: =over 4
                   9443: 
                   9444: =item *
                   9445: 
1.957     raeburn  9446: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9447: user for the level given by URL.  Optional start and end dates (leave empty
                   9448: string or zero for "no date")
1.191     harris41 9449: 
                   9450: =item *
                   9451: 
1.243     albertel 9452: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9453: change a users, password, possible return values are: ok,
                   9454: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9455: refused
1.191     harris41 9456: 
                   9457: =item *
                   9458: 
1.243     albertel 9459: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9460: 
                   9461: =item *
                   9462: 
1.963     raeburn  9463: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9464:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9465: modify user
1.191     harris41 9466: 
                   9467: =item *
                   9468: 
1.286     matthew  9469: modifystudent
                   9470: 
1.957     raeburn  9471: modify a student's enrollment and identification information.
1.286     matthew  9472: The course id is resolved based on the current users environment.  
                   9473: This means the envoking user must be a course coordinator or otherwise
                   9474: associated with a course.
                   9475: 
1.297     matthew  9476: This call is essentially a wrapper for lonnet::modifyuser and
                   9477: lonnet::modify_student_enrollment
1.286     matthew  9478: 
                   9479: Inputs: 
                   9480: 
                   9481: =over 4
                   9482: 
1.957     raeburn  9483: =item B<$udom> Student's loncapa domain
1.286     matthew  9484: 
1.957     raeburn  9485: =item B<$uname> Student's loncapa login name
1.286     matthew  9486: 
1.964     bisitz   9487: =item B<$uid> Student/Employee ID
1.286     matthew  9488: 
1.957     raeburn  9489: =item B<$umode> Student's authentication mode
1.286     matthew  9490: 
1.957     raeburn  9491: =item B<$upass> Student's password
1.286     matthew  9492: 
1.957     raeburn  9493: =item B<$first> Student's first name
1.286     matthew  9494: 
1.957     raeburn  9495: =item B<$middle> Student's middle name
1.286     matthew  9496: 
1.957     raeburn  9497: =item B<$last> Student's last name
1.286     matthew  9498: 
1.957     raeburn  9499: =item B<$gene> Student's generation
1.286     matthew  9500: 
1.957     raeburn  9501: =item B<$usec> Student's section in course
1.286     matthew  9502: 
                   9503: =item B<$end> Unix time of the roles expiration
                   9504: 
                   9505: =item B<$start> Unix time of the roles start date
                   9506: 
                   9507: =item B<$forceid> If defined, allow $uid to be changed
                   9508: 
                   9509: =item B<$desiredhome> server to use as home server for student
                   9510: 
1.957     raeburn  9511: =item B<$email> Student's permanent e-mail address
                   9512: 
                   9513: =item B<$type> Type of enrollment (auto or manual)
                   9514: 
1.963     raeburn  9515: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9516: 
                   9517: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9518: 
1.963     raeburn  9519: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9520: 
1.963     raeburn  9521: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9522: 
1.963     raeburn  9523: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9524: 
1.286     matthew  9525: =back
1.297     matthew  9526: 
                   9527: =item *
                   9528: 
                   9529: modify_student_enrollment
                   9530: 
                   9531: Change a students enrollment status in a class.  The environment variable
                   9532: 'role.request.course' must be defined for this function to proceed.
                   9533: 
                   9534: Inputs:
                   9535: 
                   9536: =over 4
                   9537: 
                   9538: =item $udom, students domain
                   9539: 
                   9540: =item $uname, students name
                   9541: 
                   9542: =item $uid, students user id
                   9543: 
                   9544: =item $first, students first name
                   9545: 
                   9546: =item $middle
                   9547: 
                   9548: =item $last
                   9549: 
                   9550: =item $gene
                   9551: 
                   9552: =item $usec
                   9553: 
                   9554: =item $end
                   9555: 
                   9556: =item $start
                   9557: 
1.957     raeburn  9558: =item $type
                   9559: 
                   9560: =item $locktype
                   9561: 
                   9562: =item $cid
                   9563: 
                   9564: =item $selfenroll
                   9565: 
                   9566: =item $context
                   9567: 
1.297     matthew  9568: =back
                   9569: 
1.191     harris41 9570: 
                   9571: =item *
                   9572: 
1.243     albertel 9573: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9574: custom role; give a custom role to a user for the level given by URL.  Specify
                   9575: name and domain of role author, and role name
1.191     harris41 9576: 
                   9577: =item *
                   9578: 
1.243     albertel 9579: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9580: 
                   9581: =item *
                   9582: 
1.243     albertel 9583: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9584: 
                   9585: =back
                   9586: 
                   9587: =head2 Course Infomation
                   9588: 
                   9589: =over 4
1.191     harris41 9590: 
                   9591: =item *
                   9592: 
1.631     albertel 9593: coursedescription($courseid) : returns a hash of information about the
                   9594: specified course id, including all environment settings for the
                   9595: course, the description of the course will be in the hash under the
                   9596: key 'description'
1.191     harris41 9597: 
                   9598: =item *
                   9599: 
1.624     albertel 9600: resdata($name,$domain,$type,@which) : request for current parameter
                   9601: setting for a specific $type, where $type is either 'course' or 'user',
                   9602: @what should be a list of parameters to ask about. This routine caches
                   9603: answers for 5 minutes.
1.243     albertel 9604: 
1.877     foxr     9605: =item *
                   9606: 
                   9607: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9608: data base, returning a hash that is keyed by the resource name and has
                   9609: values that are the resource value.  I believe that the timestamps and
                   9610: versions are also returned.
                   9611: 
                   9612: 
1.243     albertel 9613: =back
                   9614: 
                   9615: =head2 Course Modification
                   9616: 
                   9617: =over 4
1.191     harris41 9618: 
                   9619: =item *
                   9620: 
1.243     albertel 9621: writecoursepref($courseid,%prefs) : write preferences (environment
                   9622: database) for a course
1.191     harris41 9623: 
                   9624: =item *
                   9625: 
1.243     albertel 9626: createcourse($udom,$description,$url) : make/modify course
                   9627: 
                   9628: =back
                   9629: 
                   9630: =head2 Resource Subroutines
                   9631: 
                   9632: =over 4
1.191     harris41 9633: 
                   9634: =item *
                   9635: 
1.243     albertel 9636: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9637: 
                   9638: =item *
                   9639: 
1.243     albertel 9640: repcopy($filename) : subscribes to the requested file, and attempts to
                   9641: replicate from the owning library server, Might return
1.607     raeburn  9642: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9643: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9644: resource. Expects the local filesystem pathname
                   9645: (/home/httpd/html/res/....)
                   9646: 
                   9647: =back
                   9648: 
                   9649: =head2 Resource Information
                   9650: 
                   9651: =over 4
1.191     harris41 9652: 
                   9653: =item *
                   9654: 
1.243     albertel 9655: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9656: a vairety of different possible values, $varname should be a request
                   9657: string, and the other parameters can be used to specify who and what
                   9658: one is asking about.
                   9659: 
                   9660: Possible values for $varname are environment.lastname (or other item
                   9661: from the envirnment hash), user.name (or someother aspect about the
                   9662: user), resource.0.maxtries (or some other part and parameter of a
                   9663: resource)
1.204     albertel 9664: 
                   9665: =item *
                   9666: 
1.243     albertel 9667: directcondval($number) : get current value of a condition; reads from a state
                   9668: string
1.204     albertel 9669: 
                   9670: =item *
                   9671: 
1.243     albertel 9672: condval($condidx) : value of condition index based on state
1.204     albertel 9673: 
                   9674: =item *
                   9675: 
1.243     albertel 9676: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9677: resource's metadata, $what should be either a specific key, or either
                   9678: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9679: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9680: 
                   9681: this function automatically caches all requests
1.191     harris41 9682: 
                   9683: =item *
                   9684: 
1.243     albertel 9685: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9686: network of library servers; returns file handle of where SQL and regex results
                   9687: will be stored for query
1.191     harris41 9688: 
                   9689: =item *
                   9690: 
1.243     albertel 9691: symbread($filename) : return symbolic list entry (filename argument optional);
                   9692: returns the data handle
1.191     harris41 9693: 
                   9694: =item *
                   9695: 
1.243     albertel 9696: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9697: a possible symb for the URL in $thisfn, and if is an encryypted
                   9698: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9699: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9700: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9701: 
1.191     harris41 9702: 
                   9703: =item *
                   9704: 
1.243     albertel 9705: symbclean($symb) : removes versions numbers from a symb, returns the
                   9706: cleaned symb
1.191     harris41 9707: 
                   9708: =item *
                   9709: 
1.243     albertel 9710: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9711: course map, user must be in a course for it to work.
1.191     harris41 9712: 
                   9713: =item *
                   9714: 
1.243     albertel 9715: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9716: 
                   9717: =item *
                   9718: 
1.243     albertel 9719: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9720: a random seed, all arguments are optional, if they aren't sent it uses the
                   9721: environment to derive them. Note: if symb isn't sent and it can't get one
                   9722: from &symbread it will use the current time as its return value
1.191     harris41 9723: 
                   9724: =item *
                   9725: 
1.243     albertel 9726: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9727: unfakeable, receipt
1.191     harris41 9728: 
                   9729: =item *
                   9730: 
1.620     albertel 9731: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9732: 
                   9733: =item *
                   9734: 
1.243     albertel 9735: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9736: 
                   9737: =item *
                   9738: 
1.243     albertel 9739: 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 9740: 
                   9741: =item *
                   9742: 
1.243     albertel 9743: 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 9744: 
                   9745: =item *
                   9746: 
1.243     albertel 9747: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9748: 
                   9749: =item *
                   9750: 
1.243     albertel 9751: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9752: forcing spreadsheet to reevaluate the resource scores next time.
                   9753: 
                   9754: =back
                   9755: 
                   9756: =head2 Storing/Retreiving Data
                   9757: 
                   9758: =over 4
1.191     harris41 9759: 
                   9760: =item *
                   9761: 
1.243     albertel 9762: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9763: for this url; hashref needs to be given and should be a \%hashname; the
                   9764: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9765: be derived from the env
1.191     harris41 9766: 
                   9767: =item *
                   9768: 
1.243     albertel 9769: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9770: uses critical subroutine
1.191     harris41 9771: 
                   9772: =item *
                   9773: 
1.243     albertel 9774: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9775: all args are optional
1.191     harris41 9776: 
                   9777: =item *
                   9778: 
1.717     albertel 9779: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9780: dumps the complete (or key matching regexp) namespace into a hash
                   9781: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9782: normally &store()ed into
                   9783: 
                   9784: $range should be either an integer '100' (give me the first 100
                   9785:                                            matching records)
                   9786:               or be  two integers sperated by a - with no spaces
                   9787:                  '30-50' (give me the 30th through the 50th matching
                   9788:                           records)
                   9789: 
                   9790: 
                   9791: =item *
                   9792: 
                   9793: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9794: replaces a &store() version of data with a replacement set of data
                   9795: for a particular resource in a namespace passed in the $storehash hash 
                   9796: reference
                   9797: 
                   9798: =item *
                   9799: 
1.243     albertel 9800: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9801: works very similar to store/cstore, but all data is stored in a
                   9802: temporary location and can be reset using tmpreset, $storehash should
                   9803: be a hash reference, returns nothing on success
1.191     harris41 9804: 
                   9805: =item *
                   9806: 
1.243     albertel 9807: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9808: similar to restore, but all data is stored in a temporary location and
                   9809: can be reset using tmpreset. Returns a hash of values on success,
                   9810: error string otherwise.
1.191     harris41 9811: 
                   9812: =item *
                   9813: 
1.243     albertel 9814: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9815: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9816: 
                   9817: =item *
                   9818: 
1.243     albertel 9819: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9820: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9821: 
                   9822: =item *
                   9823: 
1.243     albertel 9824: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9825: namesp ($udom and $uname are optional)
1.191     harris41 9826: 
                   9827: =item *
                   9828: 
1.702     albertel 9829: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9830: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9831: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9832: 
1.702     albertel 9833: $range should be either an integer '100' (give me the first 100
                   9834:                                            matching records)
                   9835:               or be  two integers sperated by a - with no spaces
                   9836:                  '30-50' (give me the 30th through the 50th matching
                   9837:                           records)
1.449     matthew  9838: =item *
                   9839: 
                   9840: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9841: $store can be a scalar, an array reference, or if the amount to be 
                   9842: incremented is > 1, a hash reference.
                   9843: 
                   9844: ($udom and $uname are optional)
1.191     harris41 9845: 
                   9846: =item *
                   9847: 
1.243     albertel 9848: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9849: ($udom and $uname are optional)
1.191     harris41 9850: 
                   9851: =item *
                   9852: 
1.243     albertel 9853: cput($namespace,$storehash,$udom,$uname) : critical put
                   9854: ($udom and $uname are optional)
1.191     harris41 9855: 
                   9856: =item *
                   9857: 
1.748     albertel 9858: newput($namespace,$storehash,$udom,$uname) :
                   9859: 
                   9860: Attempts to store the items in the $storehash, but only if they don't
                   9861: currently exist, if this succeeds you can be certain that you have 
                   9862: successfully created a new key value pair in the $namespace db.
                   9863: 
                   9864: 
                   9865: Args:
                   9866:  $namespace: name of database to store values to
                   9867:  $storehash: hashref to store to the db
                   9868:  $udom: (optional) domain of user containing the db
                   9869:  $uname: (optional) name of user caontaining the db
                   9870: 
                   9871: Returns:
                   9872:  'ok' -> succeeded in storing all keys of $storehash
                   9873:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9874:                         least <key> already existed in the db (other
                   9875:                         requested keys may also already exist)
1.967     bisitz   9876:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9877:  'con_lost' -> unable to contact request server
                   9878:  'refused' -> action was not allowed by remote machine
                   9879: 
                   9880: 
                   9881: =item *
                   9882: 
1.243     albertel 9883: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9884: reference filled in from namesp (encrypts the return communication)
                   9885: ($udom and $uname are optional)
1.191     harris41 9886: 
                   9887: =item *
                   9888: 
1.243     albertel 9889: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9890: critical subroutine
                   9891: 
1.806     raeburn  9892: =item *
                   9893: 
1.860     raeburn  9894: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9895: array reference filled in from namespace found in domain level on either
                   9896: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9897: 
                   9898: =item *
                   9899: 
1.860     raeburn  9900: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9901: domain level either on specified domain server ($uhome) or primary domain 
                   9902: server ($udom and $uhome are optional)
1.806     raeburn  9903: 
1.943     raeburn  9904: =item * 
                   9905: 
                   9906: get_domain_defaults($target_domain) : returns hash with defaults for
                   9907: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9908: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9909: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9910: Values are retrieved from cache (if current), or from domain's configuration.db
                   9911: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9912: or lonTabs/domain.tab. 
                   9913: 
                   9914: %domdefaults = &get_auth_defaults($target_domain);
                   9915: 
1.243     albertel 9916: =back
                   9917: 
                   9918: =head2 Network Status Functions
                   9919: 
                   9920: =over 4
1.191     harris41 9921: 
                   9922: =item *
                   9923: 
                   9924: dirlist($uri) : return directory list based on URI
                   9925: 
                   9926: =item *
                   9927: 
1.243     albertel 9928: spareserver() : find server with least workload from spare.tab
                   9929: 
1.986     foxr     9930: 
                   9931: =item *
                   9932: 
                   9933: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   9934: if there is no corresponding loncapa host.
                   9935: 
1.243     albertel 9936: =back
                   9937: 
1.986     foxr     9938: 
1.243     albertel 9939: =head2 Apache Request
                   9940: 
                   9941: =over 4
1.191     harris41 9942: 
                   9943: =item *
                   9944: 
1.243     albertel 9945: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9946: localhost, posts hash
                   9947: 
                   9948: =back
                   9949: 
                   9950: =head2 Data to String to Data
                   9951: 
                   9952: =over 4
1.191     harris41 9953: 
                   9954: =item *
                   9955: 
1.243     albertel 9956: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9957: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9958: 
                   9959: =item *
                   9960: 
1.243     albertel 9961: hashref2str($hashref) : convert a hashref into a string complete with
                   9962: escaping and '=' and '&' separators, supports elements that are
                   9963: arrayrefs and hashrefs
1.191     harris41 9964: 
                   9965: =item *
                   9966: 
1.243     albertel 9967: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9968: with escaping and '&' separators, supports elements that are arrayrefs
                   9969: and hashrefs
1.191     harris41 9970: 
                   9971: =item *
                   9972: 
1.243     albertel 9973: str2hash($string) : convert string to hash using unescaping and
                   9974: splitting on '=' and '&', supports elements that are arrayrefs and
                   9975: hashrefs
1.191     harris41 9976: 
                   9977: =item *
                   9978: 
1.243     albertel 9979: str2array($string) : convert string to hash using unescaping and
                   9980: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9981: 
                   9982: =back
                   9983: 
                   9984: =head2 Logging Routines
                   9985: 
                   9986: =over 4
                   9987: 
                   9988: These routines allow one to make log messages in the lonnet.log and
                   9989: lonnet.perm logfiles.
1.191     harris41 9990: 
                   9991: =item *
                   9992: 
1.243     albertel 9993: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9994: 
                   9995: =item *
                   9996: 
1.243     albertel 9997: logthis() : append message to the normal lonnet.log file, it gets
                   9998: preiodically rolled over and deleted.
1.191     harris41 9999: 
                   10000: =item *
                   10001: 
1.243     albertel 10002: logperm() : append a permanent message to lonnet.perm.log, this log
                   10003: file never gets deleted by any automated portion of the system, only
                   10004: messages of critical importance should go in here.
                   10005: 
                   10006: =back
                   10007: 
                   10008: =head2 General File Helper Routines
                   10009: 
                   10010: =over 4
1.191     harris41 10011: 
                   10012: =item *
                   10013: 
1.481     raeburn  10014: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10015: (a) files in /uploaded
                   10016:   (i) If a local copy of the file exists - 
                   10017:       compares modification date of local copy with last-modified date for 
                   10018:       definitive version stored on home server for course. If local copy is 
                   10019:       stale, requests a new version from the home server and stores it. 
                   10020:       If the original has been removed from the home server, then local copy 
                   10021:       is unlinked.
                   10022:   (ii) If local copy does not exist -
                   10023:       requests the file from the home server and stores it. 
                   10024:   
                   10025:   If $caller is 'uploadrep':  
                   10026:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10027:     for request for files originally uploaded via DOCS. 
                   10028:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10029:   
                   10030:   Otherwise:
                   10031:      This indicates a call from the content generation phase of the request.
                   10032:      -  returns the entire contents of the file or -1.
                   10033:      
                   10034: (b) files in /res
                   10035:    - returns the entire contents of a file or -1; 
                   10036:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10037: 
1.712     albertel 10038: 
                   10039: =item *
                   10040: 
                   10041: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10042:                   reference
                   10043: 
                   10044: returns either a stat() list of data about the file or an empty list
                   10045: if the file doesn't exist or couldn't find out about it (connection
                   10046: problems or user unknown)
                   10047: 
1.191     harris41 10048: =item *
                   10049: 
1.243     albertel 10050: filelocation($dir,$file) : returns file system location of a file
                   10051: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10052: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10053: and a file of ../bob will become /a/bob)
1.191     harris41 10054: 
                   10055: =item *
                   10056: 
                   10057: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10058: filelocation except for hrefs
                   10059: 
                   10060: =item *
                   10061: 
                   10062: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10063: 
1.243     albertel 10064: =back
                   10065: 
1.608     albertel 10066: =head2 Usererfile file routines (/uploaded*)
                   10067: 
                   10068: =over 4
                   10069: 
                   10070: =item *
                   10071: 
                   10072: userfileupload(): main rotine for putting a file in a user or course's
                   10073:                   filespace, arguments are,
                   10074: 
1.620     albertel 10075:  formname - required - this is the name of the element in $env where the
1.608     albertel 10076:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10077:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10078:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10079:  coursedoc - if true, store the file in the course of the active role
                   10080:              of the current user
                   10081:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10082:          if undefined, it will be placed in "unknown"
                   10083: 
                   10084:  (This routine calls clean_filename() to remove any dangerous
                   10085:  characters from the filename, and then calls finuserfileupload() to
                   10086:  complete the transaction)
                   10087: 
                   10088:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10089:  and /adm/notfound.html if unsuccessful
                   10090: 
                   10091: =item *
                   10092: 
                   10093: clean_filename(): routine for cleaing a filename up for storage in
                   10094:                  userfile space, argument is:
                   10095: 
                   10096:  filename - proposed filename
                   10097: 
                   10098: returns: the new clean filename
                   10099: 
                   10100: =item *
                   10101: 
                   10102: finishuserfileupload(): routine that creaes and sends the file to
                   10103: userspace, probably shouldn't be called directly
                   10104: 
                   10105:   docuname: username or courseid of destination for the file
                   10106:   docudom: domain of user/course of destination for the file
                   10107:   formname: same as for userfileupload()
                   10108:   fname: filename (inculding subdirectories) for the file
                   10109: 
                   10110:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10111:  and /adm/notfound.html if unsuccessful
                   10112: 
                   10113: =item *
                   10114: 
                   10115: renameuserfile(): renames an existing userfile to a new name
                   10116: 
                   10117:   Args:
                   10118:    docuname: username or courseid of destination for the file
                   10119:    docudom: domain of user/course of destination for the file
                   10120:    old: current file name (including any subdirs under userfiles)
                   10121:    new: desired file name (including any subdirs under userfiles)
                   10122: 
                   10123: =item *
                   10124: 
                   10125: mkdiruserfile(): creates a directory is a userfiles dir
                   10126: 
                   10127:   Args:
                   10128:    docuname: username or courseid of destination for the file
                   10129:    docudom: domain of user/course of destination for the file
                   10130:    dir: dir to create (including any subdirs under userfiles)
                   10131: 
                   10132: =item *
                   10133: 
                   10134: removeuserfile(): removes a file that exists in userfiles
                   10135: 
                   10136:   Args:
                   10137:    docuname: username or courseid of destination for the file
                   10138:    docudom: domain of user/course of destination for the file
                   10139:    fname: filname to delete (including any subdirs under userfiles)
                   10140: 
                   10141: =item *
                   10142: 
                   10143: removeuploadedurl(): convience function for removeuserfile()
                   10144: 
                   10145:   Args:
                   10146:    url:  a full /uploaded/... url to delete
                   10147: 
1.747     albertel 10148: =item * 
                   10149: 
                   10150: get_portfile_permissions():
                   10151:   Args:
                   10152:     domain: domain of user or course contain the portfolio files
                   10153:     user: name of user or num of course contain the portfolio files
                   10154:   Returns:
                   10155:     hashref of a dump of the proper file_permissions.db
                   10156:    
                   10157: 
                   10158: =item * 
                   10159: 
                   10160: get_access_controls():
                   10161: 
                   10162: Args:
                   10163:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10164:   group: (optional) the group you want the files associated with
                   10165:   file: (optional) the file you want access info on
                   10166: 
                   10167: Returns:
1.749     raeburn  10168:     a hash (keys are file names) of hashes containing
                   10169:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10170:         values are XML containing access control settings (see below) 
1.747     albertel 10171: 
                   10172: Internal notes:
                   10173: 
1.749     raeburn  10174:  access controls are stored in file_permissions.db as key=value pairs.
                   10175:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10176:         where scope -> public,guest,course,group,domains or users.
                   10177:               end -> UNIX time for end of access (0 -> no end date)
                   10178:               start -> UNIX time for start of access
                   10179: 
                   10180:     value -> XML description of access control
                   10181:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10182:             <start></start>
                   10183:             <end></end>
                   10184: 
                   10185:             <password></password>  for scope type = guest
                   10186: 
                   10187:             <domain></domain>     for scope type = course or group
                   10188:             <number></number>
                   10189:             <roles id="">
                   10190:              <role></role>
                   10191:              <access></access>
                   10192:              <section></section>
                   10193:              <group></group>
                   10194:             </roles>
                   10195: 
                   10196:             <dom></dom>         for scope type = domains
                   10197: 
                   10198:             <users>             for scope type = users
                   10199:              <user>
                   10200:               <uname></uname>
                   10201:               <udom></udom>
                   10202:              </user>
                   10203:             </users>
                   10204:            </scope> 
                   10205:               
                   10206:  Access data is also aggregated for each file in an additional key=value pair:
                   10207:  key -> path to file/file_name\0accesscontrol 
                   10208:  value -> reference to hash
                   10209:           hash contains key = value pairs
                   10210:           where key = uniqueID:scope_end_start
                   10211:                 value = UNIX time record was last updated
                   10212: 
                   10213:           Used to improve speed of look-ups of access controls for each file.  
                   10214:  
                   10215:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10216: 
                   10217: modify_access_controls():
                   10218: 
                   10219: Modifies access controls for a portfolio file
                   10220: Args
                   10221: 1. file name
                   10222: 2. reference to hash of required changes,
                   10223: 3. domain
                   10224: 4. username
                   10225:   where domain,username are the domain of the portfolio owner 
                   10226:   (either a user or a course) 
                   10227: 
                   10228: Returns:
                   10229: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10230: 2. result of deletions ('ok' or 'error', with error message).
                   10231: 3. reference to hash of any new or updated access controls.
                   10232: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10233:    key = integer (inbound ID)
                   10234:    value = uniqueID  
1.747     albertel 10235: 
1.608     albertel 10236: =back
                   10237: 
1.243     albertel 10238: =head2 HTTP Helper Routines
                   10239: 
                   10240: =over 4
                   10241: 
1.191     harris41 10242: =item *
                   10243: 
                   10244: escape() : unpack non-word characters into CGI-compatible hex codes
                   10245: 
                   10246: =item *
                   10247: 
                   10248: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10249: 
1.243     albertel 10250: =back
                   10251: 
                   10252: =head1 PRIVATE SUBROUTINES
                   10253: 
                   10254: =head2 Underlying communication routines (Shouldn't call)
                   10255: 
                   10256: =over 4
                   10257: 
                   10258: =item *
                   10259: 
                   10260: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10261: 
                   10262: =item *
                   10263: 
                   10264: reply() : uses subreply to send a message to remote machine, logs all failures
                   10265: 
                   10266: =item *
                   10267: 
                   10268: critical() : passes a critical message to another server; if cannot
                   10269: get through then place message in connection buffer directory and
                   10270: returns con_delayed, if incapable of saving message, returns
                   10271: con_failed
                   10272: 
                   10273: =item *
                   10274: 
                   10275: reconlonc() : tries to reconnect lonc client processes.
                   10276: 
                   10277: =back
                   10278: 
                   10279: =head2 Resource Access Logging
                   10280: 
                   10281: =over 4
                   10282: 
                   10283: =item *
                   10284: 
                   10285: flushcourselogs() : flush (save) buffer logs and access logs
                   10286: 
                   10287: =item *
                   10288: 
                   10289: courselog($what) : save message for course in hash
                   10290: 
                   10291: =item *
                   10292: 
                   10293: courseacclog($what) : save message for course using &courselog().  Perform
                   10294: special processing for specific resource types (problems, exams, quizzes, etc).
                   10295: 
1.191     harris41 10296: =item *
                   10297: 
                   10298: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10299: as a PerlChildExitHandler
1.243     albertel 10300: 
                   10301: =back
                   10302: 
                   10303: =head2 Other
                   10304: 
                   10305: =over 4
                   10306: 
                   10307: =item *
                   10308: 
                   10309: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10310: 
                   10311: =back
                   10312: 
                   10313: =cut
1.877     foxr     10314: 

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