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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.989   ! raeburn     4: # $Id: lonnet.pm,v 1.988 2009/03/01 01:12:23 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
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.989   ! raeburn  1008:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
        !          1009:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
        !          1010:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
        !          1011:         %returnhash = %{$domdefs{'inststatustypes'}};
        !          1012:         @order = @{$domdefs{'inststatusorder'}};
        !          1013:     } else {
        !          1014:         if (defined(&domain($udom,'primary'))) {
        !          1015:             my $uhome=&domain($udom,'primary');
        !          1016:             my $rep=&reply("inst_usertypes:$udom",$uhome);
        !          1017:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
        !          1018:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
        !          1019:                 return (\%returnhash,\@order);
        !          1020:             }
        !          1021:             my ($hashitems,$orderitems) = split(/:/,$rep); 
        !          1022:             my @pairs=split(/\&/,$hashitems);
        !          1023:             foreach my $item (@pairs) {
        !          1024:                 my ($key,$value)=split(/=/,$item,2);
        !          1025:                 $key = &unescape($key);
        !          1026:                 next if ($key =~ /^error: 2 /);
        !          1027:                 $returnhash{$key}=&thaw_unescape($value);
        !          1028:             }
        !          1029:             my @esc_order = split(/\&/,$orderitems);
        !          1030:             foreach my $item (@esc_order) {
        !          1031:                 push(@order,&unescape($item));
        !          1032:             }
        !          1033:         } else {
        !          1034:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1035:         }
                   1036:     }
                   1037:     return (\%returnhash,\@order);
                   1038: }
                   1039: 
1.868     raeburn  1040: sub is_domainimage {
                   1041:     my ($url) = @_;
                   1042:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1043:         if (&domain($1) ne '') {
                   1044:             return '1';
                   1045:         }
                   1046:     }
                   1047:     return;
                   1048: }
                   1049: 
1.899     raeburn  1050: sub inst_directory_query {
                   1051:     my ($srch) = @_;
                   1052:     my $udom = $srch->{'srchdomain'};
                   1053:     my %results;
                   1054:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1055:     my $outcome;
1.899     raeburn  1056:     if ($homeserver ne '') {
1.904     albertel 1057: 	my $queryid=&reply("querysend:instdirsearch:".
                   1058: 			   &escape($srch->{'srchby'}).':'.
                   1059: 			   &escape($srch->{'srchterm'}).':'.
                   1060: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1061: 	my $host=&hostname($homeserver);
                   1062: 	if ($queryid !~/^\Q$host\E\_/) {
                   1063: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1064: 	    return;
                   1065: 	}
                   1066: 	my $response = &get_query_reply($queryid);
                   1067: 	my $maxtries = 5;
                   1068: 	my $tries = 1;
                   1069: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1070: 	    $response = &get_query_reply($queryid);
                   1071: 	    $tries ++;
                   1072: 	}
                   1073: 
                   1074:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1075:             if ($response eq 'unavailable') {
                   1076:                 $outcome = $response;
                   1077:             } else {
                   1078:                 $outcome = 'ok';
                   1079:                 my @matches = split(/\n/,$response);
                   1080:                 foreach my $match (@matches) {
                   1081:                     my ($key,$value) = split(/=/,$match);
                   1082:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1083:                 }
1.899     raeburn  1084:             }
                   1085:         }
                   1086:     }
1.909     raeburn  1087:     return ($outcome,%results);
1.899     raeburn  1088: }
                   1089: 
                   1090: sub usersearch {
                   1091:     my ($srch) = @_;
                   1092:     my $dom = $srch->{'srchdomain'};
                   1093:     my %results;
                   1094:     my %libserv = &all_library();
                   1095:     my $query = 'usersearch';
                   1096:     foreach my $tryserver (keys(%libserv)) {
                   1097:         if (&host_domain($tryserver) eq $dom) {
                   1098:             my $host=&hostname($tryserver);
                   1099:             my $queryid=
1.911     raeburn  1100:                 &reply("querysend:".&escape($query).':'.
                   1101:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1102:                        &escape($srch->{'srchtype'}).':'.
                   1103:                        &escape($srch->{'srchterm'}),$tryserver);
                   1104:             if ($queryid !~/^\Q$host\E\_/) {
                   1105:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1106:                 next;
1.899     raeburn  1107:             }
                   1108:             my $reply = &get_query_reply($queryid);
                   1109:             my $maxtries = 1;
                   1110:             my $tries = 1;
                   1111:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1112:                 $reply = &get_query_reply($queryid);
                   1113:                 $tries ++;
                   1114:             }
                   1115:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1116:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1117:             } else {
1.911     raeburn  1118:                 my @matches;
                   1119:                 if ($reply =~ /\n/) {
                   1120:                     @matches = split(/\n/,$reply);
                   1121:                 } else {
                   1122:                     @matches = split(/\&/,$reply);
                   1123:                 }
1.899     raeburn  1124:                 foreach my $match (@matches) {
                   1125:                     my ($uname,$udom,%userhash);
1.911     raeburn  1126:                     foreach my $entry (split(/:/,$match)) {
                   1127:                         my ($key,$value) =
                   1128:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1129:                         $userhash{$key} = $value;
                   1130:                         if ($key eq 'username') {
                   1131:                             $uname = $value;
                   1132:                         } elsif ($key eq 'domain') {
                   1133:                             $udom = $value;
1.911     raeburn  1134:                         }
1.899     raeburn  1135:                     }
                   1136:                     $results{$uname.':'.$udom} = \%userhash;
                   1137:                 }
                   1138:             }
                   1139:         }
                   1140:     }
                   1141:     return %results;
                   1142: }
                   1143: 
1.912     raeburn  1144: sub get_instuser {
                   1145:     my ($udom,$uname,$id) = @_;
                   1146:     my $homeserver = &domain($udom,'primary');
                   1147:     my ($outcome,%results);
                   1148:     if ($homeserver ne '') {
                   1149:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1150:                            &escape($id).':'.&escape($udom),$homeserver);
                   1151:         my $host=&hostname($homeserver);
                   1152:         if ($queryid !~/^\Q$host\E\_/) {
                   1153:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1154:             return;
                   1155:         }
                   1156:         my $response = &get_query_reply($queryid);
                   1157:         my $maxtries = 5;
                   1158:         my $tries = 1;
                   1159:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1160:             $response = &get_query_reply($queryid);
                   1161:             $tries ++;
                   1162:         }
                   1163:         if (!&error($response) && $response ne 'refused') {
                   1164:             if ($response eq 'unavailable') {
                   1165:                 $outcome = $response;
                   1166:             } else {
                   1167:                 $outcome = 'ok';
                   1168:                 my @matches = split(/\n/,$response);
                   1169:                 foreach my $match (@matches) {
                   1170:                     my ($key,$value) = split(/=/,$match);
                   1171:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1172:                 }
                   1173:             }
                   1174:         }
                   1175:     }
                   1176:     my %userinfo;
                   1177:     if (ref($results{$uname}) eq 'HASH') {
                   1178:         %userinfo = %{$results{$uname}};
                   1179:     } 
                   1180:     return ($outcome,%userinfo);
                   1181: }
                   1182: 
                   1183: sub inst_rulecheck {
1.923     raeburn  1184:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1185:     my %returnhash;
                   1186:     if ($udom ne '') {
                   1187:         if (ref($rules) eq 'ARRAY') {
                   1188:             @{$rules} = map {&escape($_);} (@{$rules});
                   1189:             my $rulestr = join(':',@{$rules});
                   1190:             my $homeserver=&domain($udom,'primary');
                   1191:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1192:                 my $response;
                   1193:                 if ($item eq 'username') {                
                   1194:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1195:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1196:                                               $homeserver));
1.923     raeburn  1197:                 } elsif ($item eq 'id') {
                   1198:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1199:                                               ':'.&escape($id).':'.$rulestr,
                   1200:                                               $homeserver));
1.945     raeburn  1201:                 } elsif ($item eq 'selfcreate') {
                   1202:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1203:                                                &escape($udom).':'.&escape($uname).
                   1204:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1205:                 }
1.912     raeburn  1206:                 if ($response ne 'refused') {
                   1207:                     my @pairs=split(/\&/,$response);
                   1208:                     foreach my $item (@pairs) {
                   1209:                         my ($key,$value)=split(/=/,$item,2);
                   1210:                         $key = &unescape($key);
                   1211:                         next if ($key =~ /^error: 2 /);
                   1212:                         $returnhash{$key}=&thaw_unescape($value);
                   1213:                     }
                   1214:                 }
                   1215:             }
                   1216:         }
                   1217:     }
                   1218:     return %returnhash;
                   1219: }
                   1220: 
                   1221: sub inst_userrules {
1.923     raeburn  1222:     my ($udom,$check) = @_;
1.912     raeburn  1223:     my (%ruleshash,@ruleorder);
                   1224:     if ($udom ne '') {
                   1225:         my $homeserver=&domain($udom,'primary');
                   1226:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1227:             my $response;
                   1228:             if ($check eq 'id') {
                   1229:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1230:                                  $homeserver);
1.943     raeburn  1231:             } elsif ($check eq 'email') {
                   1232:                 $response=&reply('instemailrules:'.&escape($udom),
                   1233:                                  $homeserver);
1.923     raeburn  1234:             } else {
                   1235:                 $response=&reply('instuserrules:'.&escape($udom),
                   1236:                                  $homeserver);
                   1237:             }
1.912     raeburn  1238:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1239:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1240:                 ($response ne 'no_such_host')) {
                   1241:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1242:                 my @pairs=split(/\&/,$hashitems);
                   1243:                 foreach my $item (@pairs) {
                   1244:                     my ($key,$value)=split(/=/,$item,2);
                   1245:                     $key = &unescape($key);
                   1246:                     next if ($key =~ /^error: 2 /);
                   1247:                     $ruleshash{$key}=&thaw_unescape($value);
                   1248:                 }
                   1249:                 my @esc_order = split(/\&/,$orderitems);
                   1250:                 foreach my $item (@esc_order) {
                   1251:                     push(@ruleorder,&unescape($item));
                   1252:                 }
                   1253:             }
                   1254:         }
                   1255:     }
                   1256:     return (\%ruleshash,\@ruleorder);
                   1257: }
                   1258: 
1.976     raeburn  1259: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1260: 
                   1261: sub get_domain_defaults {
                   1262:     my ($domain) = @_;
                   1263:     my $cachetime = 60*60*24;
                   1264:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1265:     if (defined($cached)) {
                   1266:         if (ref($result) eq 'HASH') {
                   1267:             return %{$result};
                   1268:         }
                   1269:     }
                   1270:     my %domdefaults;
                   1271:     my %domconfig =
1.989   ! raeburn  1272:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
        !          1273:                                   'requestcourses','inststatus'],$domain);
1.943     raeburn  1274:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1275:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1276:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1277:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1278:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1279:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1280:     } else {
                   1281:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1282:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1283:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1284:     }
1.976     raeburn  1285:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1286:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1287:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1288:         } else {
                   1289:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1290:         } 
                   1291:         my @usertools = ('aboutme','blog','portfolio');
                   1292:         foreach my $item (@usertools) {
                   1293:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1294:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1295:             }
                   1296:         }
                   1297:     }
1.985     raeburn  1298:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
                   1299:         foreach my $item ('official','unofficial') {
                   1300:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1301:         }
                   1302:     }
1.989   ! raeburn  1303:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
        !          1304:         foreach my $item ('inststatustypes','inststatusorder') {
        !          1305:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
        !          1306:         }
        !          1307:     }
1.943     raeburn  1308:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1309:                                   $cachetime);
                   1310:     return %domdefaults;
                   1311: }
                   1312: 
1.344     www      1313: # --------------------------------------------------- Assign a key to a student
                   1314: 
                   1315: sub assign_access_key {
1.364     www      1316: #
                   1317: # a valid key looks like uname:udom#comments
                   1318: # comments are being appended
                   1319: #
1.498     www      1320:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1321:     $kdom=
1.620     albertel 1322:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1323:     $knum=
1.620     albertel 1324:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1325:     $cdom=
1.620     albertel 1326:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1327:     $cnum=
1.620     albertel 1328:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1329:     $udom=$env{'user.name'} unless (defined($udom));
                   1330:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1331:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1332:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1333:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1334:                                                   # assigned to this person
                   1335:                                                   # - this should not happen,
1.345     www      1336:                                                   # unless something went wrong
                   1337:                                                   # the first time around
                   1338: # ready to assign
1.364     www      1339:         $logentry=$1.'; '.$logentry;
1.496     www      1340:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1341:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1342: # key now belongs to user
1.346     www      1343: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1344:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1345:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1346:                 return 'ok';
                   1347:             } else {
                   1348:                 return 
                   1349:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1350: 	    }
                   1351:         } else {
                   1352:             return 'error: Could not assign key, try again later.';
                   1353:         }
1.364     www      1354:     } elsif (!$existing{$ckey}) {
1.345     www      1355: # the key does not exist
                   1356: 	return 'error: The key does not exist';
                   1357:     } else {
                   1358: # the key is somebody else's
                   1359: 	return 'error: The key is already in use';
                   1360:     }
1.344     www      1361: }
                   1362: 
1.364     www      1363: # ------------------------------------------ put an additional comment on a key
                   1364: 
                   1365: sub comment_access_key {
                   1366: #
                   1367: # a valid key looks like uname:udom#comments
                   1368: # comments are being appended
                   1369: #
                   1370:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1371:     $cdom=
1.620     albertel 1372:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1373:     $cnum=
1.620     albertel 1374:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1375:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1376:     if ($existing{$ckey}) {
                   1377:         $existing{$ckey}.='; '.$logentry;
                   1378: # ready to assign
1.367     www      1379:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1380:                                                  $cdom,$cnum) eq 'ok') {
                   1381: 	    return 'ok';
                   1382:         } else {
                   1383: 	    return 'error: Count not store comment.';
                   1384:         }
                   1385:     } else {
                   1386: # the key does not exist
                   1387: 	return 'error: The key does not exist';
                   1388:     }
                   1389: }
                   1390: 
1.344     www      1391: # ------------------------------------------------------ Generate a set of keys
                   1392: 
                   1393: sub generate_access_keys {
1.364     www      1394:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1395:     $cdom=
1.620     albertel 1396:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1397:     $cnum=
1.620     albertel 1398:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1399:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1400:     unless (($cdom) && ($cnum)) { return 0; }
                   1401:     if ($number>10000) { return 0; }
                   1402:     sleep(2); # make sure don't get same seed twice
                   1403:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1404:     my $total=0;
                   1405:     for (my $i=1;$i<=$number;$i++) {
                   1406:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1407:                   sprintf("%lx",int(100000*rand)).'-'.
                   1408:                   sprintf("%lx",int(100000*rand));
                   1409:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1410:        $newkey=~s/0/h/g; # and also 0 and O
                   1411:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1412:        if ($existing{$newkey}) {
                   1413:            $i--;
                   1414:        } else {
1.364     www      1415: 	  if (&put('accesskeys',
                   1416:               { $newkey => '# generated '.localtime().
1.620     albertel 1417:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1418:                            '; '.$logentry },
                   1419: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1420:               $total++;
                   1421: 	  }
                   1422:        }
                   1423:     }
1.620     albertel 1424:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1425:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1426:     return $total;
                   1427: }
                   1428: 
                   1429: # ------------------------------------------------------- Validate an accesskey
                   1430: 
                   1431: sub validate_access_key {
                   1432:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1433:     $cdom=
1.620     albertel 1434:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1435:     $cnum=
1.620     albertel 1436:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1437:     $udom=$env{'user.domain'} unless (defined($udom));
                   1438:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1439:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1440:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1441: }
                   1442: 
                   1443: # ------------------------------------- Find the section of student in a course
1.652     albertel 1444: sub devalidate_getsection_cache {
                   1445:     my ($udom,$unam,$courseid)=@_;
                   1446:     my $hashid="$udom:$unam:$courseid";
                   1447:     &devalidate_cache_new('getsection',$hashid);
                   1448: }
1.298     matthew  1449: 
1.815     albertel 1450: sub courseid_to_courseurl {
                   1451:     my ($courseid) = @_;
                   1452:     #already url style courseid
                   1453:     return $courseid if ($courseid =~ m{^/});
                   1454: 
                   1455:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1456: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1457: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1458: 	return "/$cdom/$cnum";
                   1459:     }
                   1460: 
                   1461:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1462:     if (exists($courseinfo{'num'})) {
                   1463: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1464:     }
                   1465: 
                   1466:     return undef;
                   1467: }
                   1468: 
1.298     matthew  1469: sub getsection {
                   1470:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1471:     my $cachetime=1800;
1.551     albertel 1472: 
                   1473:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1474:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1475:     if (defined($cached)) { return $result; }
                   1476: 
1.298     matthew  1477:     my %Pending; 
                   1478:     my %Expired;
                   1479:     #
                   1480:     # Each role can either have not started yet (pending), be active, 
                   1481:     #    or have expired.
                   1482:     #
                   1483:     # If there is an active role, we are done.
                   1484:     #
                   1485:     # If there is more than one role which has not started yet, 
                   1486:     #     choose the one which will start sooner
                   1487:     # If there is one role which has not started yet, return it.
                   1488:     #
                   1489:     # If there is more than one expired role, choose the one which ended last.
                   1490:     # If there is a role which has expired, return it.
                   1491:     #
1.815     albertel 1492:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1493:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1494:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1495:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1496:         my $section=$1;
                   1497:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1498:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1499:         my $now=time;
1.548     albertel 1500:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1501:             $Expired{$end}=$section;
                   1502:             next;
                   1503:         }
1.548     albertel 1504:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1505:             $Pending{$start}=$section;
                   1506:             next;
                   1507:         }
1.599     albertel 1508:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1509:     }
                   1510:     #
                   1511:     # Presumedly there will be few matching roles from the above
                   1512:     # loop and the sorting time will be negligible.
                   1513:     if (scalar(keys(%Pending))) {
                   1514:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1515:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1516:     } 
                   1517:     if (scalar(keys(%Expired))) {
                   1518:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1519:         my $time = pop(@sorted);
1.599     albertel 1520:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1521:     }
1.599     albertel 1522:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1523: }
1.70      www      1524: 
1.599     albertel 1525: sub save_cache {
                   1526:     &purge_remembered();
1.722     albertel 1527:     #&Apache::loncommon::validate_page();
1.620     albertel 1528:     undef(%env);
1.780     albertel 1529:     undef($env_loaded);
1.599     albertel 1530: }
1.452     albertel 1531: 
1.599     albertel 1532: my $to_remember=-1;
                   1533: my %remembered;
                   1534: my %accessed;
                   1535: my $kicks=0;
                   1536: my $hits=0;
1.849     albertel 1537: sub make_key {
                   1538:     my ($name,$id) = @_;
1.872     albertel 1539:     if (length($id) > 65 
                   1540: 	&& length(&escape($id)) > 200) {
                   1541: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1542:     }
1.849     albertel 1543:     return &escape($name.':'.$id);
                   1544: }
                   1545: 
1.599     albertel 1546: sub devalidate_cache_new {
                   1547:     my ($name,$id,$debug) = @_;
                   1548:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1549:     $id=&make_key($name,$id);
1.599     albertel 1550:     $memcache->delete($id);
                   1551:     delete($remembered{$id});
                   1552:     delete($accessed{$id});
                   1553: }
                   1554: 
                   1555: sub is_cached_new {
                   1556:     my ($name,$id,$debug) = @_;
1.849     albertel 1557:     $id=&make_key($name,$id);
1.599     albertel 1558:     if (exists($remembered{$id})) {
                   1559: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1560: 	$accessed{$id}=[&gettimeofday()];
                   1561: 	$hits++;
                   1562: 	return ($remembered{$id},1);
                   1563:     }
                   1564:     my $value = $memcache->get($id);
                   1565:     if (!(defined($value))) {
                   1566: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1567: 	return (undef,undef);
1.416     albertel 1568:     }
1.599     albertel 1569:     if ($value eq '__undef__') {
                   1570: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1571: 	$value=undef;
                   1572:     }
                   1573:     &make_room($id,$value,$debug);
                   1574:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1575:     return ($value,1);
                   1576: }
                   1577: 
                   1578: sub do_cache_new {
                   1579:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1580:     $id=&make_key($name,$id);
1.599     albertel 1581:     my $setvalue=$value;
                   1582:     if (!defined($setvalue)) {
                   1583: 	$setvalue='__undef__';
                   1584:     }
1.623     albertel 1585:     if (!defined($time) ) {
                   1586: 	$time=600;
                   1587:     }
1.599     albertel 1588:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1589:     my $result = $memcache->set($id,$setvalue,$time);
                   1590:     if (! $result) {
1.872     albertel 1591: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1592: 	$memcache->disconnect_all();
1.872     albertel 1593:     }
1.600     albertel 1594:     # need to make a copy of $value
1.919     albertel 1595:     &make_room($id,$value,$debug);
1.599     albertel 1596:     return $value;
                   1597: }
                   1598: 
                   1599: sub make_room {
                   1600:     my ($id,$value,$debug)=@_;
1.919     albertel 1601: 
                   1602:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1603:                                     : $value;
1.599     albertel 1604:     if ($to_remember<0) { return; }
                   1605:     $accessed{$id}=[&gettimeofday()];
                   1606:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1607:     my $to_kick;
                   1608:     my $max_time=0;
                   1609:     foreach my $other (keys(%accessed)) {
                   1610: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1611: 	    $to_kick=$other;
                   1612: 	    $max_time=&tv_interval($accessed{$other});
                   1613: 	}
                   1614:     }
                   1615:     delete($remembered{$to_kick});
                   1616:     delete($accessed{$to_kick});
                   1617:     $kicks++;
                   1618:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1619:     return;
                   1620: }
                   1621: 
1.599     albertel 1622: sub purge_remembered {
1.604     albertel 1623:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1624:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1625:     undef(%remembered);
                   1626:     undef(%accessed);
1.428     albertel 1627: }
1.70      www      1628: # ------------------------------------- Read an entry from a user's environment
                   1629: 
                   1630: sub userenvironment {
                   1631:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1632:     my $items;
                   1633:     foreach my $item (@what) {
                   1634:         $items.=&escape($item).'&';
                   1635:     }
                   1636:     $items=~s/\&$//;
1.70      www      1637:     my %returnhash=();
                   1638:     my @answer=split(/\&/,
1.976     raeburn  1639:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1640:                       &homeserver($unam,$udom)));
                   1641:     my $i;
                   1642:     for ($i=0;$i<=$#what;$i++) {
                   1643: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1644:     }
                   1645:     return %returnhash;
1.1       albertel 1646: }
                   1647: 
1.617     albertel 1648: # ---------------------------------------------------------- Get a studentphoto
                   1649: sub studentphoto {
                   1650:     my ($udom,$unam,$ext) = @_;
                   1651:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1652:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1653:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1654:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1655:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1656:             } else {
                   1657:                 my ($result,$perm_reqd)=
1.707     albertel 1658: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1659:                 if ($result eq 'ok') {
                   1660:                     if (!($perm_reqd eq 'yes')) {
                   1661:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1662:                     }
                   1663:                 }
                   1664:             }
                   1665:         }
                   1666:     } else {
                   1667:         my ($result,$perm_reqd) = 
1.707     albertel 1668: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1669:         if ($result eq 'ok') {
                   1670:             if (!($perm_reqd eq 'yes')) {
                   1671:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1672:             }
                   1673:         }
                   1674:     }
                   1675:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1676: }
                   1677: 
                   1678: sub retrievestudentphoto {
                   1679:     my ($udom,$unam,$ext,$type) = @_;
                   1680:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1681:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1682:     if ($ret eq 'ok') {
                   1683:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1684:         if ($type eq 'thumbnail') {
                   1685:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1686:         }
                   1687:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1688:         return $tokenurl;
                   1689:     } else {
                   1690:         if ($type eq 'thumbnail') {
                   1691:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1692:         } else { 
                   1693:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1694:         }
1.617     albertel 1695:     }
                   1696: }
                   1697: 
1.263     www      1698: # -------------------------------------------------------------------- New chat
                   1699: 
                   1700: sub chatsend {
1.724     raeburn  1701:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1702:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1703:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1704:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1705:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1706: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1707: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1708: }
                   1709: 
                   1710: # ------------------------------------------ Find current version of a resource
                   1711: 
                   1712: sub getversion {
                   1713:     my $fname=&clutter(shift);
                   1714:     unless ($fname=~/^\/res\//) { return -1; }
                   1715:     return &currentversion(&filelocation('',$fname));
                   1716: }
                   1717: 
                   1718: sub currentversion {
                   1719:     my $fname=shift;
1.599     albertel 1720:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1721:     if (defined($cached)) { return $result; }
1.292     www      1722:     my $author=$fname;
                   1723:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1724:     my ($udom,$uname)=split(/\//,$author);
                   1725:     my $home=homeserver($uname,$udom);
                   1726:     if ($home eq 'no_host') { 
                   1727:         return -1; 
                   1728:     }
                   1729:     my $answer=reply("currentversion:$fname",$home);
                   1730:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1731: 	return -1;
                   1732:     }
1.599     albertel 1733:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1734: }
                   1735: 
1.1       albertel 1736: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1737: 
1.1       albertel 1738: sub subscribe {
                   1739:     my $fname=shift;
1.761     raeburn  1740:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1741:     $fname=~s/[\n\r]//g;
1.1       albertel 1742:     my $author=$fname;
                   1743:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1744:     my ($udom,$uname)=split(/\//,$author);
                   1745:     my $home=homeserver($uname,$udom);
1.335     albertel 1746:     if ($home eq 'no_host') {
                   1747:         return 'not_found';
1.1       albertel 1748:     }
                   1749:     my $answer=reply("sub:$fname",$home);
1.64      www      1750:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1751: 	$answer.=' by '.$home;
                   1752:     }
1.1       albertel 1753:     return $answer;
                   1754: }
                   1755:     
1.8       www      1756: # -------------------------------------------------------------- Replicate file
                   1757: 
                   1758: sub repcopy {
                   1759:     my $filename=shift;
1.23      www      1760:     $filename=~s/\/+/\//g;
1.607     raeburn  1761:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1762:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1763:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1764: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1765: 	return &repcopy_userfile($filename);
                   1766:     }
1.532     albertel 1767:     $filename=~s/[\n\r]//g;
1.8       www      1768:     my $transname="$filename.in.transfer";
1.828     www      1769: # FIXME: this should flock
1.607     raeburn  1770:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1771:     my $remoteurl=subscribe($filename);
1.64      www      1772:     if ($remoteurl =~ /^con_lost by/) {
                   1773: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1774:            return 'unavailable';
1.8       www      1775:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1776: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1777: 	   return 'not_found';
1.64      www      1778:     } elsif ($remoteurl =~ /^rejected by/) {
                   1779: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1780:            return 'forbidden';
1.20      www      1781:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1782:            return 'ok';
1.8       www      1783:     } else {
1.290     www      1784:         my $author=$filename;
                   1785:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1786:         my ($udom,$uname)=split(/\//,$author);
                   1787:         my $home=homeserver($uname,$udom);
                   1788:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1789:            my @parts=split(/\//,$filename);
                   1790:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1791:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1792:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1793: 	       return 'bad_request';
1.8       www      1794:            }
                   1795:            my $count;
                   1796:            for ($count=5;$count<$#parts;$count++) {
                   1797:                $path.="/$parts[$count]";
                   1798:                if ((-e $path)!=1) {
                   1799: 		   mkdir($path,0777);
                   1800:                }
                   1801:            }
                   1802:            my $ua=new LWP::UserAgent;
                   1803:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1804:            my $response=$ua->request($request,$transname);
                   1805:            if ($response->is_error()) {
                   1806: 	       unlink($transname);
                   1807:                my $message=$response->status_line;
1.672     albertel 1808:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1809:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1810:                return 'unavailable';
1.8       www      1811:            } else {
1.16      www      1812: 	       if ($remoteurl!~/\.meta$/) {
                   1813:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1814:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1815:                   if ($mresponse->is_error()) {
                   1816: 		      unlink($filename.'.meta');
                   1817:                       &logthis(
1.672     albertel 1818:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1819:                   }
                   1820: 	       }
1.8       www      1821:                rename($transname,$filename);
1.607     raeburn  1822:                return 'ok';
1.8       www      1823:            }
1.290     www      1824:        }
1.8       www      1825:     }
1.330     www      1826: }
                   1827: 
                   1828: # ------------------------------------------------ Get server side include body
                   1829: sub ssi_body {
1.381     albertel 1830:     my ($filelink,%form)=@_;
1.606     matthew  1831:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1832:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1833:     }
1.953     www      1834:     my $output='';
                   1835:     my $response;
1.980     raeburn  1836:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1837:        ($output,$response)=&externalssi($filelink);
1.953     www      1838:     } else {
                   1839:        ($output,$response)=&ssi($filelink,%form);
                   1840:     }
1.778     albertel 1841:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1842:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1843:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1844:     if (wantarray) {
                   1845:         return ($output, $response);
                   1846:     } else {
                   1847:         return $output;
                   1848:     }
1.8       www      1849: }
                   1850: 
1.15      www      1851: # --------------------------------------------------------- Server Side Include
                   1852: 
1.782     albertel 1853: sub absolute_url {
                   1854:     my ($host_name) = @_;
                   1855:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1856:     if ($host_name eq '') {
                   1857: 	$host_name = $ENV{'SERVER_NAME'};
                   1858:     }
                   1859:     return $protocol.$host_name;
                   1860: }
                   1861: 
1.942     foxr     1862: #
                   1863: #   Server side include.
                   1864: # Parameters:
                   1865: #  fn     Possibly encrypted resource name/id.
                   1866: #  form   Hash that describes how the rendering should be done
                   1867: #         and other things.
1.944     foxr     1868: # Returns:
1.950     raeburn  1869: #   Scalar context: The content of the response.
                   1870: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1871: #     
1.15      www      1872: sub ssi {
                   1873: 
1.944     foxr     1874:     my ($fn,%form)=@_;
1.15      www      1875:     my $ua=new LWP::UserAgent;
1.23      www      1876:     my $request;
1.711     albertel 1877: 
                   1878:     $form{'no_update_last_known'}=1;
1.895     albertel 1879:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1880:     if (%form) {
1.782     albertel 1881:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1882:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1883:     } else {
1.782     albertel 1884:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1885:     }
                   1886: 
1.15      www      1887:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1888:     my $response=$ua->request($request);
                   1889: 
1.944     foxr     1890:     if (wantarray) {
                   1891: 	return ($response->content, $response);
                   1892:     } else {
                   1893: 	return $response->content;
1.942     foxr     1894:     }
1.324     www      1895: }
                   1896: 
                   1897: sub externalssi {
                   1898:     my ($url)=@_;
                   1899:     my $ua=new LWP::UserAgent;
                   1900:     my $request=new HTTP::Request('GET',$url);
                   1901:     my $response=$ua->request($request);
1.954     raeburn  1902:     if (wantarray) {
                   1903:         return ($response->content, $response);
                   1904:     } else {
                   1905:         return $response->content;
                   1906:     }
1.15      www      1907: }
1.254     www      1908: 
1.492     albertel 1909: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1910: 
                   1911: sub allowuploaded {
                   1912:     my ($srcurl,$url)=@_;
                   1913:     $url=&clutter(&declutter($url));
                   1914:     my $dir=$url;
                   1915:     $dir=~s/\/[^\/]+$//;
                   1916:     my %httpref=();
                   1917:     my $httpurl=&hreflocation('',$url);
                   1918:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1919:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1920: }
1.477     raeburn  1921: 
1.478     albertel 1922: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1923: # input: action, courseID, current domain, intended
1.637     raeburn  1924: #        path to file, source of file, instruction to parse file for objects,
                   1925: #        ref to hash for embedded objects,
                   1926: #        ref to hash for codebase of java objects.
                   1927: #
1.485     raeburn  1928: # output: url to file (if action was uploaddoc), 
                   1929: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1930: #
1.478     albertel 1931: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1932: # course.
1.477     raeburn  1933: #
1.478     albertel 1934: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1935: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1936: #          course's home server.
1.477     raeburn  1937: #
1.478     albertel 1938: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1939: #          be copied from $source (current location) to 
                   1940: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1941: #         and will then be copied to
                   1942: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1943: #         course's home server.
1.485     raeburn  1944: #
1.481     raeburn  1945: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1946: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1947: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1948: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1949: #         in course's home server.
1.637     raeburn  1950: #
1.477     raeburn  1951: 
                   1952: sub process_coursefile {
1.638     albertel 1953:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1954:     my $fetchresult;
1.638     albertel 1955:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1956:     if ($action eq 'propagate') {
1.638     albertel 1957:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1958: 			     $home);
1.481     raeburn  1959:     } else {
1.477     raeburn  1960:         my $fpath = '';
                   1961:         my $fname = $file;
1.478     albertel 1962:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1963:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1964:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1965:         if ($action eq 'copy') {
                   1966:             if ($source eq '') {
                   1967:                 $fetchresult = 'no source file';
                   1968:                 return $fetchresult;
                   1969:             } else {
                   1970:                 my $destination = $filepath.'/'.$fname;
                   1971:                 rename($source,$destination);
                   1972:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1973:                                  $home);
1.481     raeburn  1974:             }
                   1975:         } elsif ($action eq 'uploaddoc') {
                   1976:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1977:             print $fh $env{'form.'.$source};
1.481     raeburn  1978:             close($fh);
1.637     raeburn  1979:             if ($parser eq 'parse') {
1.961     raeburn  1980:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1981:                 unless ($parse_result eq 'ok') {
                   1982:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1983:                 }
                   1984:             }
1.477     raeburn  1985:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1986:                                  $home);
1.481     raeburn  1987:             if ($fetchresult eq 'ok') {
                   1988:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1989:             } else {
                   1990:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1991:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1992:                 return '/adm/notfound.html';
                   1993:             }
1.477     raeburn  1994:         }
                   1995:     }
1.485     raeburn  1996:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1997:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1998:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1999:     }
                   2000:     return $fetchresult;
                   2001: }
                   2002: 
1.637     raeburn  2003: sub build_filepath {
                   2004:     my ($fpath) = @_;
                   2005:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2006:     unless ($fpath eq '') {
                   2007:         my @parts=split('/',$fpath);
                   2008:         foreach my $part (@parts) {
                   2009:             $filepath.= '/'.$part;
                   2010:             if ((-e $filepath)!=1) {
                   2011:                 mkdir($filepath,0777);
                   2012:             }
                   2013:         }
                   2014:     }
                   2015:     return $filepath;
                   2016: }
                   2017: 
                   2018: sub store_edited_file {
1.638     albertel 2019:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2020:     my $file = $primary_url;
                   2021:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2022:     my $fpath = '';
                   2023:     my $fname = $file;
                   2024:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2025:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2026:     my $filepath = &build_filepath($fpath);
                   2027:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2028:     print $fh $content;
                   2029:     close($fh);
1.638     albertel 2030:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2031:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2032: 			  $home);
1.637     raeburn  2033:     if ($$fetchresult eq 'ok') {
                   2034:         return '/uploaded/'.$fpath.'/'.$fname;
                   2035:     } else {
1.638     albertel 2036:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2037: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2038:         return '/adm/notfound.html';
                   2039:     }
                   2040: }
                   2041: 
1.531     albertel 2042: sub clean_filename {
1.831     albertel 2043:     my ($fname,$args)=@_;
1.315     www      2044: # Replace Windows backslashes by forward slashes
1.257     www      2045:     $fname=~s/\\/\//g;
1.831     albertel 2046:     if (!$args->{'keep_path'}) {
                   2047:         # Get rid of everything but the actual filename
                   2048: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2049:     }
1.315     www      2050: # Replace spaces by underscores
                   2051:     $fname=~s/\s+/\_/g;
                   2052: # Replace all other weird characters by nothing
1.831     albertel 2053:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2054: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2055: # numbers
                   2056:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2057:     return $fname;
                   2058: }
1.984     neumanie 2059: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2060: sub resizeImage {
                   2061: 	my($img_url) = @_;	
                   2062: 	my $ima = Image::Magick->new;                       
                   2063:         $ima->Read($img_url);
                   2064: 	if($ima->Get('width') > 400)
                   2065: 	{
                   2066: 		my $factor = $ima->Get('width')/400;
                   2067:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2068: 	}
                   2069: 	if($ima->Get('height') > 500)
                   2070:         {
                   2071:         	my $factor = $ima->Get('height')/500;
                   2072:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2073:         } 
                   2074: 		
                   2075: 	$ima->Write($img_url);
                   2076: }
1.531     albertel 2077: 
1.977     amueller 2078: #Wrapper function for userphotoupload
                   2079: sub userphotoupload
                   2080: {
                   2081: 	my($formname,$subdir) = @_;
                   2082: 	$upload_photo_form = 1;
                   2083: 	return &userfileupload($formname,undef,$subdir);
                   2084: }
                   2085: 
1.608     albertel 2086: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2087: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2088: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2089: #        $coursedoc - if true up to the current course
                   2090: #                     if false
                   2091: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2092: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2093: #        $allfiles - reference to hash for embedded objects
                   2094: #        $codebase - reference to hash for codebase of java objects
                   2095: #        $desuname - username for permanent storage of uploaded file
                   2096: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2097: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2098: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2099: # 
1.686     albertel 2100: # output: url of file in userspace, or error: <message> 
                   2101: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2102: 
                   2103: 
1.531     albertel 2104: sub userfileupload {
1.860     raeburn  2105:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2106:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2107:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2108:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2109:     $fname=&clean_filename($fname);
1.315     www      2110: # See if there is anything left
1.257     www      2111:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2112:     chop($env{'form.'.$formname});
1.523     raeburn  2113:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2114:         my $now = time;
                   2115:         my $filepath = 'tmp/helprequests/'.$now;
                   2116:         my @parts=split(/\//,$filepath);
                   2117:         my $fullpath = $perlvar{'lonDaemons'};
                   2118:         for (my $i=0;$i<@parts;$i++) {
                   2119:             $fullpath .= '/'.$parts[$i];
                   2120:             if ((-e $fullpath)!=1) {
                   2121:                 mkdir($fullpath,0777);
                   2122:             }
                   2123:         }
                   2124:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2125:         print $fh $env{'form.'.$formname};
1.523     raeburn  2126:         close($fh);
1.741     raeburn  2127:         return $fullpath.'/'.$fname;
                   2128:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2129:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2130:                        '_'.$env{'user.domain'}.'/pending';
                   2131:         my @parts=split(/\//,$filepath);
                   2132:         my $fullpath = $perlvar{'lonDaemons'};
                   2133:         for (my $i=0;$i<@parts;$i++) {
                   2134:             $fullpath .= '/'.$parts[$i];
                   2135:             if ((-e $fullpath)!=1) {
                   2136:                 mkdir($fullpath,0777);
                   2137:             }
                   2138:         }
                   2139:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2140:         print $fh $env{'form.'.$formname};
                   2141:         close($fh);
                   2142:         return $fullpath.'/'.$fname;
1.523     raeburn  2143:     }
1.719     banghart 2144:     
1.258     www      2145: # Create the directory if not present
1.493     albertel 2146:     $fname="$subdir/$fname";
1.259     www      2147:     if ($coursedoc) {
1.638     albertel 2148: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2149: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2150:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2151:             return &finishuserfileupload($docuname,$docudom,
                   2152: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2153: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2154:         } else {
1.620     albertel 2155:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2156:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2157: 				       $fname,$formname,$parser,
                   2158: 				       $allfiles,$codebase);
1.481     raeburn  2159:         }
1.719     banghart 2160:     } elsif (defined($destuname)) {
                   2161:         my $docuname=$destuname;
                   2162:         my $docudom=$destudom;
1.860     raeburn  2163: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2164: 				     $parser,$allfiles,$codebase,
                   2165:                                      $thumbwidth,$thumbheight);
1.719     banghart 2166:         
1.259     www      2167:     } else {
1.638     albertel 2168:         my $docuname=$env{'user.name'};
                   2169:         my $docudom=$env{'user.domain'};
1.714     raeburn  2170:         if (exists($env{'form.group'})) {
                   2171:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2172:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2173:         }
1.860     raeburn  2174: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2175: 				     $parser,$allfiles,$codebase,
                   2176:                                      $thumbwidth,$thumbheight);
1.259     www      2177:     }
1.271     www      2178: }
                   2179: 
                   2180: sub finishuserfileupload {
1.860     raeburn  2181:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2182:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2183:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2184:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2185:   
1.860     raeburn  2186:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2187:     $file=$fname;
                   2188:     if ($fname=~m|/|) {
                   2189:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2190: 	$path.=$fnamepath.'/';
                   2191:     }
1.259     www      2192:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2193:     my $count;
                   2194:     for ($count=4;$count<=$#parts;$count++) {
                   2195:         $filepath.="/$parts[$count]";
                   2196:         if ((-e $filepath)!=1) {
                   2197: 	    mkdir($filepath,0777);
                   2198:         }
                   2199:     }
1.984     neumanie 2200: 
1.258     www      2201: # Save the file
                   2202:     {
1.701     albertel 2203: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2204: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2205: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2206: 	    return '/adm/notfound.html';
                   2207: 	}
                   2208: 	if (!print FH ($env{'form.'.$formname})) {
                   2209: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2210: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2211: 	    return '/adm/notfound.html';
                   2212: 	}
1.570     albertel 2213: 	close(FH);
1.977     amueller 2214: 	if($upload_photo_form==1)
                   2215: 	{
1.984     neumanie 2216: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2217: 		$upload_photo_form = 0;
                   2218: 	}
1.258     www      2219:     }
1.637     raeburn  2220:     if ($parser eq 'parse') {
1.961     raeburn  2221:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2222: 						   $codebase);
1.637     raeburn  2223:         unless ($parse_result eq 'ok') {
1.638     albertel 2224:             &logthis('Failed to parse '.$filepath.$file.
                   2225: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2226:         }
                   2227:     }
1.860     raeburn  2228:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2229:         my $input = $filepath.'/'.$file;
                   2230:         my $output = $filepath.'/'.'tn-'.$file;
                   2231:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2232:         system("convert -sample $thumbsize $input $output");
                   2233:         if (-e $filepath.'/'.'tn-'.$file) {
                   2234:             $fetchthumb  = 1; 
                   2235:         }
                   2236:     }
1.858     raeburn  2237:  
1.259     www      2238: # Notify homeserver to grep it
                   2239: #
1.984     neumanie 2240:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2241:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2242:     if ($fetchresult eq 'ok') {
1.860     raeburn  2243:         if ($fetchthumb) {
                   2244:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2245:             if ($thumbresult ne 'ok') {
                   2246:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2247:                          $docuhome.': '.$thumbresult);
                   2248:             }
                   2249:         }
1.259     www      2250: #
1.258     www      2251: # Return the URL to it
1.494     albertel 2252:         return '/uploaded/'.$path.$file;
1.263     www      2253:     } else {
1.494     albertel 2254:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2255: 		 ': '.$fetchresult);
1.263     www      2256:         return '/adm/notfound.html';
1.858     raeburn  2257:     }
1.493     albertel 2258: }
                   2259: 
1.637     raeburn  2260: sub extract_embedded_items {
1.961     raeburn  2261:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2262:     my @state = ();
                   2263:     my %javafiles = (
                   2264:                       codebase => '',
                   2265:                       code => '',
                   2266:                       archive => ''
                   2267:                     );
                   2268:     my %mediafiles = (
                   2269:                       src => '',
                   2270:                       movie => '',
                   2271:                      );
1.648     raeburn  2272:     my $p;
                   2273:     if ($content) {
                   2274:         $p = HTML::LCParser->new($content);
                   2275:     } else {
1.961     raeburn  2276:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2277:     }
1.641     albertel 2278:     while (my $t=$p->get_token()) {
1.640     albertel 2279: 	if ($t->[0] eq 'S') {
                   2280: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2281: 	    push(@state, $tagname);
1.648     raeburn  2282:             if (lc($tagname) eq 'allow') {
                   2283:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2284:             }
1.640     albertel 2285: 	    if (lc($tagname) eq 'img') {
                   2286: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2287: 	    }
1.886     albertel 2288: 	    if (lc($tagname) eq 'a') {
                   2289: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2290: 	    }
1.645     raeburn  2291:             if (lc($tagname) eq 'script') {
                   2292:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2293:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2294:                 } else {
                   2295:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2296:                 }
                   2297:             }
                   2298:             if (lc($tagname) eq 'link') {
                   2299:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2300:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2301:                 }
                   2302:             }
1.640     albertel 2303: 	    if (lc($tagname) eq 'object' ||
                   2304: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2305: 		foreach my $item (keys(%javafiles)) {
                   2306: 		    $javafiles{$item} = '';
                   2307: 		}
                   2308: 	    }
                   2309: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2310: 		my $name = lc($attr->{'name'});
                   2311: 		foreach my $item (keys(%javafiles)) {
                   2312: 		    if ($name eq $item) {
                   2313: 			$javafiles{$item} = $attr->{'value'};
                   2314: 			last;
                   2315: 		    }
                   2316: 		}
                   2317: 		foreach my $item (keys(%mediafiles)) {
                   2318: 		    if ($name eq $item) {
                   2319: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2320: 			last;
                   2321: 		    }
                   2322: 		}
                   2323: 	    }
                   2324: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2325: 		foreach my $item (keys(%javafiles)) {
                   2326: 		    if ($attr->{$item}) {
                   2327: 			$javafiles{$item} = $attr->{$item};
                   2328: 			last;
                   2329: 		    }
                   2330: 		}
                   2331: 		foreach my $item (keys(%mediafiles)) {
                   2332: 		    if ($attr->{$item}) {
                   2333: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2334: 			last;
                   2335: 		    }
                   2336: 		}
                   2337: 	    }
                   2338: 	} elsif ($t->[0] eq 'E') {
                   2339: 	    my ($tagname) = ($t->[1]);
                   2340: 	    if ($javafiles{'codebase'} ne '') {
                   2341: 		$javafiles{'codebase'} .= '/';
                   2342: 	    }  
                   2343: 	    if (lc($tagname) eq 'applet' ||
                   2344: 		lc($tagname) eq 'object' ||
                   2345: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2346: 		) {
                   2347: 		foreach my $item (keys(%javafiles)) {
                   2348: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2349: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2350: 			&add_filetype($allfiles,$file,$item);
                   2351: 		    }
                   2352: 		}
                   2353: 	    } 
                   2354: 	    pop @state;
                   2355: 	}
                   2356:     }
1.637     raeburn  2357:     return 'ok';
                   2358: }
                   2359: 
1.639     albertel 2360: sub add_filetype {
                   2361:     my ($allfiles,$file,$type)=@_;
                   2362:     if (exists($allfiles->{$file})) {
                   2363: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2364: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2365: 	}
                   2366:     } else {
                   2367: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2368:     }
                   2369: }
                   2370: 
1.493     albertel 2371: sub removeuploadedurl {
1.984     neumanie 2372:     my ($url)=@_;	
                   2373:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2374:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2375: }
                   2376: 
                   2377: sub removeuserfile {
                   2378:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2379:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2380:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2381:     if ($result eq 'ok') {	
1.798     raeburn  2382:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2383:             my $metafile = $fname.'.meta';
                   2384:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2385: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2386:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2387:             my $sqlresult = 
1.823     albertel 2388:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2389:                                         'portfolio_metadata',$group,
                   2390:                                         'delete');
1.798     raeburn  2391:         }
                   2392:     }
                   2393:     return $result;
1.257     www      2394: }
1.15      www      2395: 
1.530     albertel 2396: sub mkdiruserfile {
                   2397:     my ($docuname,$docudom,$dir)=@_;
                   2398:     my $home=&homeserver($docuname,$docudom);
                   2399:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2400: }
                   2401: 
1.531     albertel 2402: sub renameuserfile {
                   2403:     my ($docuname,$docudom,$old,$new)=@_;
                   2404:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2405:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2406:                         &escape("$old").':'.&escape("$new"),$home);
                   2407:     if ($result eq 'ok') {
                   2408:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2409:             my $oldmeta = $old.'.meta';
                   2410:             my $newmeta = $new.'.meta';
                   2411:             my $metaresult = 
                   2412:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2413: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2414:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2415:             my $sqlresult = 
1.823     albertel 2416:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2417:                                         'portfolio_metadata',$group,
                   2418:                                         'delete');
1.798     raeburn  2419:         }
                   2420:     }
                   2421:     return $result;
1.531     albertel 2422: }
                   2423: 
1.14      www      2424: # ------------------------------------------------------------------------- Log
                   2425: 
                   2426: sub log {
                   2427:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2428:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2429: }
                   2430: 
                   2431: # ------------------------------------------------------------------ Course Log
1.352     www      2432: #
                   2433: # This routine flushes several buffers of non-mission-critical nature
                   2434: #
1.157     www      2435: 
                   2436: sub flushcourselogs {
1.352     www      2437:     &logthis('Flushing log buffers');
                   2438: #
                   2439: # course logs
                   2440: # This is a log of all transactions in a course, which can be used
                   2441: # for data mining purposes
                   2442: #
                   2443: # It also collects the courseid database, which lists last transaction
                   2444: # times and course titles for all courseids
                   2445: #
                   2446:     my %courseidbuffer=();
1.921     raeburn  2447:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2448:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2449: 		          &escape($courselogs{$crsid}),
                   2450: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2451: 	    delete $courselogs{$crsid};
                   2452:         } else {
                   2453:             &logthis('Failed to flush log buffer for '.$crsid);
                   2454:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2455:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2456:                         " exceeded maximum size, deleting.</font>");
                   2457:                delete $courselogs{$crsid};
                   2458:             }
1.352     www      2459:         }
1.920     raeburn  2460:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2461:             'description' => $coursedescrbuf{$crsid},
                   2462:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2463:             'type'        => $coursetypebuf{$crsid},
                   2464:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2465:         };
1.191     harris41 2466:     }
1.352     www      2467: #
                   2468: # Write course id database (reverse lookup) to homeserver of courses 
                   2469: # Is used in pickcourse
                   2470: #
1.840     albertel 2471:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2472:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2473:                                     $courseidbuffer{$crs_home},
                   2474:                                     $crs_home,'timeonly');
1.352     www      2475:     }
                   2476: #
                   2477: # File accesses
                   2478: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2479: #
1.449     matthew  2480:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2481:         if ($entry =~ /___count$/) {
                   2482:             my ($dom,$name);
1.807     albertel 2483:             ($dom,$name,undef)=
1.811     albertel 2484: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2485:             if (! defined($dom) || $dom eq '' || 
                   2486:                 ! defined($name) || $name eq '') {
1.620     albertel 2487:                 my $cid = $env{'request.course.id'};
                   2488:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2489:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2490:             }
1.450     matthew  2491:             my $value = $accesshash{$entry};
                   2492:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2493:             my %temphash=($url => $value);
1.449     matthew  2494:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2495:             if ($result eq 'ok') {
                   2496:                 delete $accesshash{$entry};
                   2497:             } elsif ($result eq 'unknown_cmd') {
                   2498:                 # Target server has old code running on it.
1.450     matthew  2499:                 my %temphash=($entry => $value);
1.449     matthew  2500:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2501:                     delete $accesshash{$entry};
                   2502:                 }
                   2503:             }
                   2504:         } else {
1.811     albertel 2505:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2506:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2507:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2508:                 delete $accesshash{$entry};
                   2509:             }
1.185     www      2510:         }
1.191     harris41 2511:     }
1.352     www      2512: #
                   2513: # Roles
                   2514: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2515: #
1.800     albertel 2516:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2517:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2518: 	    split(/\:/,$entry);
                   2519:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2520:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2521:                 $rudom,$runame) eq 'ok') {
                   2522: 	    delete $userrolehash{$entry};
                   2523:         }
                   2524:     }
1.662     raeburn  2525: #
                   2526: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2527: #
                   2528:     my %domrolebuffer = ();
                   2529:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2530:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2531:         if ($domrolebuffer{$rudom}) {
                   2532:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2533:                       '='.&escape($domainrolehash{$entry});
                   2534:         } else {
                   2535:             $domrolebuffer{$rudom}.=&escape($entry).
                   2536:                       '='.&escape($domainrolehash{$entry});
                   2537:         }
                   2538:         delete $domainrolehash{$entry};
                   2539:     }
                   2540:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2541: 	my %servers = &get_servers($dom,'library');
                   2542: 	foreach my $tryserver (keys(%servers)) {
                   2543: 	    unless (&reply('domroleput:'.$dom.':'.
                   2544: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2545: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2546: 	    }
1.662     raeburn  2547:         }
                   2548:     }
1.186     www      2549:     $dumpcount++;
1.157     www      2550: }
                   2551: 
                   2552: sub courselog {
                   2553:     my $what=shift;
1.158     www      2554:     $what=time.':'.$what;
1.620     albertel 2555:     unless ($env{'request.course.id'}) { return ''; }
                   2556:     $coursedombuf{$env{'request.course.id'}}=
                   2557:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2558:     $coursenumbuf{$env{'request.course.id'}}=
                   2559:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2560:     $coursehombuf{$env{'request.course.id'}}=
                   2561:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2562:     $coursedescrbuf{$env{'request.course.id'}}=
                   2563:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2564:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2565:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2566:     $courseownerbuf{$env{'request.course.id'}}=
                   2567:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2568:     $coursetypebuf{$env{'request.course.id'}}=
                   2569:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2570:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2571: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2572:     } else {
1.620     albertel 2573: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2574:     }
1.620     albertel 2575:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2576: 	&flushcourselogs();
                   2577:     }
1.158     www      2578: }
                   2579: 
                   2580: sub courseacclog {
                   2581:     my $fnsymb=shift;
1.620     albertel 2582:     unless ($env{'request.course.id'}) { return ''; }
                   2583:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2584:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2585:         $what.=':POST';
1.583     matthew  2586:         # FIXME: Probably ought to escape things....
1.800     albertel 2587: 	foreach my $key (keys(%env)) {
                   2588:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2589:                 my $formitem = $1;
                   2590:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2591:                     $what.=':'.$formitem.'='.$env{$key};
                   2592:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2593:                     $what.=':'.$formitem.'='.$env{$key};
                   2594:                 }
1.158     www      2595:             }
1.191     harris41 2596:         }
1.583     matthew  2597:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2598:         # FIXME: We should not be depending on a form parameter that someone
                   2599:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2600:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2601:             $what.= ':POST';
                   2602:             # FIXME: Probably ought to escape things....
                   2603:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2604:                                  'crsdiscuss') {
1.620     albertel 2605:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2606:             }
                   2607:         }
1.158     www      2608:     }
                   2609:     &courselog($what);
1.149     www      2610: }
                   2611: 
1.185     www      2612: sub countacc {
                   2613:     my $url=&declutter(shift);
1.458     matthew  2614:     return if (! defined($url) || $url eq '');
1.620     albertel 2615:     unless ($env{'request.course.id'}) { return ''; }
                   2616:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2617:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2618:     $accesshash{$key}++;
1.185     www      2619: }
1.349     www      2620: 
1.361     www      2621: sub linklog {
                   2622:     my ($from,$to)=@_;
                   2623:     $from=&declutter($from);
                   2624:     $to=&declutter($to);
                   2625:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2626:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2627: }
                   2628:   
1.349     www      2629: sub userrolelog {
                   2630:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2631:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2632:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2633:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2634:         ($trole=~/^ta/)) {
1.350     www      2635:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2636:        $userrolehash
                   2637:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2638:                     =$tend.':'.$tstart;
1.662     raeburn  2639:     }
1.898     albertel 2640:     if (($env{'request.role'} =~ /dc\./) &&
                   2641: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2642: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2643: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2644:        $userrolehash
                   2645:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2646:                     =$tend.':'.$tstart;
                   2647:     }
1.662     raeburn  2648:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2649:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2650:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2651:         ($trole=~/^sc/)) {
                   2652:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2653:        $domainrolehash
                   2654:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2655:                     = $tend.':'.$tstart;
                   2656:     }
1.351     www      2657: }
                   2658: 
1.957     raeburn  2659: sub courserolelog {
                   2660:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2661:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2662:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2663:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2664:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2665:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2666:             my $cdom = $1;
                   2667:             my $cnum = $2;
                   2668:             my $sec = $3;
                   2669:             my $namespace = 'rolelog';
                   2670:             my %storehash = (
                   2671:                                role    => $trole,
                   2672:                                start   => $tstart,
                   2673:                                end     => $tend,
                   2674:                                selfenroll => $selfenroll,
                   2675:                                context    => $context,
                   2676:                             );
                   2677:             if ($trole eq 'gr') {
                   2678:                 $namespace = 'groupslog';
                   2679:                 $storehash{'group'} = $sec;
                   2680:             } else {
                   2681:                 $storehash{'section'} = $sec;
                   2682:             }
                   2683:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2684:         }
                   2685:     }
                   2686:     return;
                   2687: }
                   2688: 
1.351     www      2689: sub get_course_adv_roles {
1.948     raeburn  2690:     my ($cid,$codes) = @_;
1.620     albertel 2691:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2692:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2693:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2694:     my %nothide=();
1.800     albertel 2695:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2696:         if ($user !~ /:/) {
                   2697: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2698:         } else {
                   2699:             $nothide{$user}=1;
                   2700:         }
1.470     www      2701:     }
1.351     www      2702:     my %returnhash=();
                   2703:     my %dumphash=
                   2704:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2705:     my $now=time;
1.800     albertel 2706:     foreach my $entry (keys %dumphash) {
                   2707: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2708:         if (($tstart) && ($tstart<0)) { next; }
                   2709:         if (($tend) && ($tend<$now)) { next; }
                   2710:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2711:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2712: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2713: 	if ((&privileged($username,$domain)) && 
                   2714: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2715: 	if ($role eq 'cr') { next; }
1.948     raeburn  2716:         if ($codes) {
                   2717:             if ($section) { $role .= ':'.$section; }
                   2718:             if ($returnhash{$role}) {
                   2719:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2720:             } else {
                   2721:                 $returnhash{$role}=$username.':'.$domain;
                   2722:             }
1.351     www      2723:         } else {
1.988     raeburn  2724:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2725:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2726:             if ($returnhash{$key}) {
                   2727: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2728:             } else {
                   2729:                 $returnhash{$key}=$username.':'.$domain;
                   2730:             }
1.351     www      2731:         }
1.948     raeburn  2732:     }
1.400     www      2733:     return %returnhash;
                   2734: }
                   2735: 
                   2736: sub get_my_roles {
1.937     raeburn  2737:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2738:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2739:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2740:     my (%dumphash,%nothide);
1.858     raeburn  2741:     if ($context eq 'userroles') { 
                   2742:         %dumphash = &dump('roles',$udom,$uname);
                   2743:     } else {
                   2744:         %dumphash=
1.400     www      2745:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2746:         if ($hidepriv) {
                   2747:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2748:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2749:                 if ($user !~ /:/) {
                   2750:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2751:                 } else {
                   2752:                     $nothide{$user} = 1;
                   2753:                 }
                   2754:             }
                   2755:         }
1.858     raeburn  2756:     }
1.400     www      2757:     my %returnhash=();
                   2758:     my $now=time;
1.800     albertel 2759:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2760:         my ($role,$tend,$tstart);
                   2761:         if ($context eq 'userroles') {
                   2762: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2763:         } else {
                   2764:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2765:         }
1.400     www      2766:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2767:         my $status = 'active';
1.939     raeburn  2768:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2769:             $status = 'previous';
                   2770:         } 
                   2771:         if (($tstart) && ($now<$tstart)) {
                   2772:             $status = 'future';
                   2773:         }
                   2774:         if (ref($types) eq 'ARRAY') {
                   2775:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2776:                 next;
                   2777:             } 
                   2778:         } else {
                   2779:             if ($status ne 'active') {
                   2780:                 next;
                   2781:             }
                   2782:         }
1.867     raeburn  2783:         my ($rolecode,$username,$domain,$section,$area);
                   2784:         if ($context eq 'userroles') {
                   2785:             ($area,$rolecode) = split(/_/,$entry);
                   2786:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2787:         } else {
                   2788:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2789:         }
1.832     raeburn  2790:         if (ref($roledoms) eq 'ARRAY') {
                   2791:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2792:                 next;
                   2793:             }
                   2794:         }
                   2795:         if (ref($roles) eq 'ARRAY') {
                   2796:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2797:                 if ($role =~ /^cr\//) {
                   2798:                     if (!grep(/^cr$/,@{$roles})) {
                   2799:                         next;
                   2800:                     }
                   2801:                 } else {
                   2802:                     next;
                   2803:                 }
1.832     raeburn  2804:             }
1.867     raeburn  2805:         }
1.937     raeburn  2806:         if ($hidepriv) {
                   2807:             if ((&privileged($username,$domain)) &&
                   2808:                 (!$nothide{$username.':'.$domain})) { 
                   2809:                 next;
                   2810:             }
                   2811:         }
1.933     raeburn  2812:         if ($withsec) {
                   2813:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2814:                 $tstart.':'.$tend;
                   2815:         } else {
                   2816:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2817:         }
1.832     raeburn  2818:     }
1.373     www      2819:     return %returnhash;
1.399     www      2820: }
                   2821: 
                   2822: # ----------------------------------------------------- Frontpage Announcements
                   2823: #
                   2824: #
                   2825: 
                   2826: sub postannounce {
                   2827:     my ($server,$text)=@_;
1.844     albertel 2828:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2829:     unless ($text=~/\w/) { $text=''; }
                   2830:     return &reply('setannounce:'.&escape($text),$server);
                   2831: }
                   2832: 
                   2833: sub getannounce {
1.448     albertel 2834: 
                   2835:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2836: 	my $announcement='';
1.800     albertel 2837: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2838: 	close($fh);
1.399     www      2839: 	if ($announcement=~/\w/) { 
                   2840: 	    return 
                   2841:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2842:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2843: 	} else {
                   2844: 	    return '';
                   2845: 	}
                   2846:     } else {
                   2847: 	return '';
                   2848:     }
1.351     www      2849: }
1.353     www      2850: 
                   2851: # ---------------------------------------------------------- Course ID routines
                   2852: # Deal with domain's nohist_courseid.db files
                   2853: #
                   2854: 
                   2855: sub courseidput {
1.921     raeburn  2856:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2857:     my $outcome;
                   2858:     if ($caller eq 'timeonly') {
                   2859:         my $cids = '';
                   2860:         foreach my $item (keys(%$storehash)) {
                   2861:             $cids.=&escape($item).'&';
                   2862:         }
                   2863:         $cids=~s/\&$//;
                   2864:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2865:                           $coursehome);       
                   2866:     } else {
                   2867:         my $items = '';
                   2868:         foreach my $item (keys(%$storehash)) {
                   2869:             $items.= &escape($item).'='.
                   2870:                      &freeze_escape($$storehash{$item}).'&';
                   2871:         }
                   2872:         $items=~s/\&$//;
                   2873:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2874:                           $coursehome);
1.918     raeburn  2875:     }
                   2876:     if ($outcome eq 'unknown_cmd') {
                   2877:         my $what;
                   2878:         foreach my $cid (keys(%$storehash)) {
                   2879:             $what .= &escape($cid).'=';
1.921     raeburn  2880:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2881:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2882:             }
                   2883:             $what =~ s/\:$/&/;
                   2884:         }
                   2885:         $what =~ s/\&$//;  
                   2886:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2887:     } else {
                   2888:         return $outcome;
                   2889:     }
1.353     www      2890: }
                   2891: 
                   2892: sub courseiddump {
1.921     raeburn  2893:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2894:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2895:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2896:     my $as_hash = 1;
                   2897:     my %returnhash;
                   2898:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2899:     my %libserv = &all_library();
                   2900:     foreach my $tryserver (keys(%libserv)) {
                   2901:         if ( (  $hostidflag == 1 
                   2902: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2903: 	     || (!defined($hostidflag)) ) {
                   2904: 
1.918     raeburn  2905: 	    if (($domfilter eq '') ||
                   2906: 		(&host_domain($tryserver) eq $domfilter)) {
                   2907:                 my $rep = 
                   2908:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2909:                          $sincefilter.':'.&escape($descfilter).':'.
                   2910:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2911:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2912:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2913:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2914:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2915:                 my @pairs=split(/\&/,$rep);
                   2916:                 foreach my $item (@pairs) {
                   2917:                     my ($key,$value)=split(/\=/,$item,2);
                   2918:                     $key = &unescape($key);
                   2919:                     next if ($key =~ /^error: 2 /);
                   2920:                     my $result = &thaw_unescape($value);
                   2921:                     if (ref($result) eq 'HASH') {
                   2922:                         $returnhash{$key}=$result;
                   2923:                     } else {
1.921     raeburn  2924:                         my @responses = split(/:/,$value);
                   2925:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2926:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2927:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2928:                         }
                   2929:                     } 
1.353     www      2930:                 }
                   2931:             }
                   2932:         }
                   2933:     }
                   2934:     return %returnhash;
                   2935: }
                   2936: 
1.658     raeburn  2937: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2938: 
                   2939: sub dcmailput {
1.685     raeburn  2940:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2941:     my $status = &Apache::lonnet::critical(
1.740     www      2942:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2943:        &escape($message),$server);
1.662     raeburn  2944:     return $status;
                   2945: }
                   2946: 
1.658     raeburn  2947: sub dcmaildump {
                   2948:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2949:     my %returnhash=();
1.846     albertel 2950: 
                   2951:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2952:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2953:                                                          &escape($enddate).':';
                   2954: 	my @esc_senders=map { &escape($_)} @$senders;
                   2955: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2956: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2957:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2958:             if (($key) && ($value)) {
                   2959:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2960:             }
                   2961:         }
                   2962:     }
                   2963:     return %returnhash;
                   2964: }
1.662     raeburn  2965: # ---------------------------------------------------------- Domain roles
                   2966: 
                   2967: sub get_domain_roles {
                   2968:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2969:     if (undef($startdate) || $startdate eq '') {
                   2970:         $startdate = '.';
                   2971:     }
                   2972:     if (undef($enddate) || $enddate eq '') {
                   2973:         $enddate = '.';
                   2974:     }
1.922     raeburn  2975:     my $rolelist;
                   2976:     if (ref($roles) eq 'ARRAY') {
                   2977:         $rolelist = join(':',@{$roles});
                   2978:     }
1.662     raeburn  2979:     my %personnel = ();
1.841     albertel 2980: 
                   2981:     my %servers = &get_servers($dom,'library');
                   2982:     foreach my $tryserver (keys(%servers)) {
                   2983: 	%{$personnel{$tryserver}}=();
                   2984: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2985: 					    &escape($startdate).':'.
                   2986: 					    &escape($enddate).':'.
                   2987: 					    &escape($rolelist), $tryserver))) {
                   2988: 	    my ($key,$value) = split(/\=/,$line,2);
                   2989: 	    if (($key) && ($value)) {
                   2990: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2991: 	    }
                   2992: 	}
1.662     raeburn  2993:     }
                   2994:     return %personnel;
                   2995: }
1.658     raeburn  2996: 
1.149     www      2997: # ----------------------------------------------------------- Check out an item
                   2998: 
1.504     albertel 2999: sub get_first_access {
                   3000:     my ($type,$argsymb)=@_;
1.790     albertel 3001:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3002:     if ($argsymb) { $symb=$argsymb; }
                   3003:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3004:     if ($type eq 'course') {
                   3005: 	$res='course';
                   3006:     } elsif ($type eq 'map') {
1.588     albertel 3007: 	$res=&symbread($map);
                   3008:     } else {
                   3009: 	$res=$symb;
                   3010:     }
                   3011:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3012:     return $times{"$courseid\0$res"};
1.504     albertel 3013: }
                   3014: 
                   3015: sub set_first_access {
                   3016:     my ($type)=@_;
1.790     albertel 3017:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3018:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3019:     if ($type eq 'course') {
                   3020: 	$res='course';
                   3021:     } elsif ($type eq 'map') {
1.588     albertel 3022: 	$res=&symbread($map);
                   3023:     } else {
                   3024: 	$res=$symb;
                   3025:     }
                   3026:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3027:     if (!$firstaccess) {
1.588     albertel 3028: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3029:     }
                   3030:     return 'already_set';
1.504     albertel 3031: }
                   3032: 
1.149     www      3033: sub checkout {
                   3034:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3035:     my $now=time;
                   3036:     my $lonhost=$perlvar{'lonHostID'};
                   3037:     my $infostr=&escape(
1.234     www      3038:                  'CHECKOUTTOKEN&'.
1.149     www      3039:                  $tuname.'&'.
                   3040:                  $tudom.'&'.
                   3041:                  $tcrsid.'&'.
                   3042:                  $symb.'&'.
                   3043: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3044:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3045:     if ($token=~/^error\:/) { 
1.672     albertel 3046:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3047:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3048:                  "</font>");
                   3049:         return ''; 
                   3050:     }
                   3051: 
1.149     www      3052:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3053:     $token=~tr/a-z/A-Z/;
                   3054: 
1.153     www      3055:     my %infohash=('resource.0.outtoken' => $token,
                   3056:                   'resource.0.checkouttime' => $now,
                   3057:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3058: 
                   3059:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3060:        return '';
1.151     www      3061:     } else {
1.672     albertel 3062:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3063:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3064:                  "</font>");
1.149     www      3065:     }    
                   3066: 
                   3067:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3068:                          &escape('Checkout '.$infostr.' - '.
                   3069:                                                  $token)) ne 'ok') {
                   3070: 	return '';
1.151     www      3071:     } else {
1.672     albertel 3072:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3073:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3074:                  "</font>");
1.149     www      3075:     }
1.151     www      3076:     return $token;
1.149     www      3077: }
                   3078: 
                   3079: # ------------------------------------------------------------ Check in an item
                   3080: 
                   3081: sub checkin {
                   3082:     my $token=shift;
1.150     www      3083:     my $now=time;
                   3084:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3085:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3086:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3087:     $dtoken=~s/\W/\_/g;
1.234     www      3088:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3089:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3090: 
1.154     www      3091:     unless (($tuname) && ($tudom)) {
                   3092:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3093:         return '';
                   3094:     }
                   3095:     
                   3096:     unless (&allowed('mgr',$tcrsid)) {
                   3097:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3098:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3099:         return '';
                   3100:     }
                   3101: 
1.153     www      3102:     my %infohash=('resource.0.intoken' => $token,
                   3103:                   'resource.0.checkintime' => $now,
                   3104:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3105: 
                   3106:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3107:        return '';
                   3108:     }    
                   3109: 
                   3110:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3111:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3112: 	return '';
                   3113:     }
                   3114: 
                   3115:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3116: }
                   3117: 
                   3118: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3119: 
                   3120: sub expirespread {
                   3121:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3122:     my $cid=$env{'request.course.id'}; 
1.110     www      3123:     if ($cid) {
                   3124:        my $now=time;
                   3125:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3126:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3127:                             $env{'course.'.$cid.'.num'}.
1.110     www      3128: 	        	    ':nohist_expirationdates:'.
                   3129:                             &escape($key).'='.$now,
1.620     albertel 3130:                             $env{'course.'.$cid.'.home'})
1.110     www      3131:     }
                   3132:     return 'ok';
1.14      www      3133: }
                   3134: 
1.109     www      3135: # ----------------------------------------------------- Devalidate Spreadsheets
                   3136: 
                   3137: sub devalidate {
1.325     www      3138:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3139:     my $cid=$env{'request.course.id'}; 
1.109     www      3140:     if ($cid) {
1.391     matthew  3141:         # delete the stored spreadsheets for
                   3142:         # - the student level sheet of this user in course's homespace
                   3143:         # - the assessment level sheet for this resource 
                   3144:         #   for this user in user's homespace
1.553     albertel 3145: 	# - current conditional state info
1.325     www      3146: 	my $key=$uname.':'.$udom.':';
1.109     www      3147:         my $status=
1.299     matthew  3148: 	    &del('nohist_calculatedsheets',
1.391     matthew  3149: 		 [$key.'studentcalc:'],
1.620     albertel 3150: 		 $env{'course.'.$cid.'.domain'},
                   3151: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3152: 		.' '.
                   3153: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3154: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3155:         unless ($status eq 'ok ok') {
                   3156:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3157:                     $uname.' at '.$udom.' for '.
1.109     www      3158: 		    $symb.': '.$status);
1.133     albertel 3159:         }
1.553     albertel 3160: 	&delenv('user.state.'.$cid);
1.109     www      3161:     }
                   3162: }
                   3163: 
1.265     albertel 3164: sub get_scalar {
                   3165:     my ($string,$end) = @_;
                   3166:     my $value;
                   3167:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3168: 	$value = $1;
                   3169:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3170: 	$value = $1;
                   3171:     }
                   3172:     return &unescape($value);
                   3173: }
                   3174: 
                   3175: sub array2str {
                   3176:   my (@array) = @_;
                   3177:   my $result=&arrayref2str(\@array);
                   3178:   $result=~s/^__ARRAY_REF__//;
                   3179:   $result=~s/__END_ARRAY_REF__$//;
                   3180:   return $result;
                   3181: }
                   3182: 
1.204     albertel 3183: sub arrayref2str {
                   3184:   my ($arrayref) = @_;
1.265     albertel 3185:   my $result='__ARRAY_REF__';
1.204     albertel 3186:   foreach my $elem (@$arrayref) {
1.265     albertel 3187:     if(ref($elem) eq 'ARRAY') {
                   3188:       $result.=&arrayref2str($elem).'&';
                   3189:     } elsif(ref($elem) eq 'HASH') {
                   3190:       $result.=&hashref2str($elem).'&';
                   3191:     } elsif(ref($elem)) {
                   3192:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3193:     } else {
                   3194:       $result.=&escape($elem).'&';
                   3195:     }
                   3196:   }
                   3197:   $result=~s/\&$//;
1.265     albertel 3198:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3199:   return $result;
                   3200: }
                   3201: 
1.168     albertel 3202: sub hash2str {
1.204     albertel 3203:   my (%hash) = @_;
                   3204:   my $result=&hashref2str(\%hash);
1.265     albertel 3205:   $result=~s/^__HASH_REF__//;
                   3206:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3207:   return $result;
                   3208: }
                   3209: 
                   3210: sub hashref2str {
                   3211:   my ($hashref)=@_;
1.265     albertel 3212:   my $result='__HASH_REF__';
1.800     albertel 3213:   foreach my $key (sort(keys(%$hashref))) {
                   3214:     if (ref($key) eq 'ARRAY') {
                   3215:       $result.=&arrayref2str($key).'=';
                   3216:     } elsif (ref($key) eq 'HASH') {
                   3217:       $result.=&hashref2str($key).'=';
                   3218:     } elsif (ref($key)) {
1.265     albertel 3219:       $result.='=';
1.800     albertel 3220:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3221:     } else {
1.800     albertel 3222: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3223:     }
                   3224: 
1.800     albertel 3225:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3226:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3227:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3228:       $result.=&hashref2str($hashref->{$key}).'&';
                   3229:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3230:        $result.='&';
1.800     albertel 3231:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3232:     } else {
1.800     albertel 3233:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3234:     }
                   3235:   }
1.168     albertel 3236:   $result=~s/\&$//;
1.265     albertel 3237:   $result .= '__END_HASH_REF__';
1.168     albertel 3238:   return $result;
                   3239: }
                   3240: 
                   3241: sub str2hash {
1.265     albertel 3242:     my ($string)=@_;
                   3243:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3244:     return %$hash;
                   3245: }
                   3246: 
                   3247: sub str2hashref {
1.168     albertel 3248:   my ($string) = @_;
1.265     albertel 3249: 
                   3250:   my %hash;
                   3251: 
                   3252:   if($string !~ /^__HASH_REF__/) {
                   3253:       if (! ($string eq '' || !defined($string))) {
                   3254: 	  $hash{'error'}='Not hash reference';
                   3255:       }
                   3256:       return (\%hash, $string);
                   3257:   }
                   3258: 
                   3259:   $string =~ s/^__HASH_REF__//;
                   3260: 
                   3261:   while($string !~ /^__END_HASH_REF__/) {
                   3262:       #key
                   3263:       my $key='';
                   3264:       if($string =~ /^__HASH_REF__/) {
                   3265:           ($key, $string)=&str2hashref($string);
                   3266:           if(defined($key->{'error'})) {
                   3267:               $hash{'error'}='Bad data';
                   3268:               return (\%hash, $string);
                   3269:           }
                   3270:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3271:           ($key, $string)=&str2arrayref($string);
                   3272:           if($key->[0] eq 'Array reference error') {
                   3273:               $hash{'error'}='Bad data';
                   3274:               return (\%hash, $string);
                   3275:           }
                   3276:       } else {
                   3277:           $string =~ s/^(.*?)=//;
1.267     albertel 3278: 	  $key=&unescape($1);
1.265     albertel 3279:       }
                   3280:       $string =~ s/^=//;
                   3281: 
                   3282:       #value
                   3283:       my $value='';
                   3284:       if($string =~ /^__HASH_REF__/) {
                   3285:           ($value, $string)=&str2hashref($string);
                   3286:           if(defined($value->{'error'})) {
                   3287:               $hash{'error'}='Bad data';
                   3288:               return (\%hash, $string);
                   3289:           }
                   3290:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3291:           ($value, $string)=&str2arrayref($string);
                   3292:           if($value->[0] eq 'Array reference error') {
                   3293:               $hash{'error'}='Bad data';
                   3294:               return (\%hash, $string);
                   3295:           }
                   3296:       } else {
                   3297: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3298:       }
                   3299:       $string =~ s/^&//;
                   3300: 
                   3301:       $hash{$key}=$value;
1.204     albertel 3302:   }
1.265     albertel 3303: 
                   3304:   $string =~ s/^__END_HASH_REF__//;
                   3305: 
                   3306:   return (\%hash, $string);
1.204     albertel 3307: }
                   3308: 
                   3309: sub str2array {
1.265     albertel 3310:     my ($string)=@_;
                   3311:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3312:     return @$array;
                   3313: }
                   3314: 
                   3315: sub str2arrayref {
1.204     albertel 3316:   my ($string) = @_;
1.265     albertel 3317:   my @array;
                   3318: 
                   3319:   if($string !~ /^__ARRAY_REF__/) {
                   3320:       if (! ($string eq '' || !defined($string))) {
                   3321: 	  $array[0]='Array reference error';
                   3322:       }
                   3323:       return (\@array, $string);
                   3324:   }
                   3325: 
                   3326:   $string =~ s/^__ARRAY_REF__//;
                   3327: 
                   3328:   while($string !~ /^__END_ARRAY_REF__/) {
                   3329:       my $value='';
                   3330:       if($string =~ /^__HASH_REF__/) {
                   3331:           ($value, $string)=&str2hashref($string);
                   3332:           if(defined($value->{'error'})) {
                   3333:               $array[0] ='Array reference error';
                   3334:               return (\@array, $string);
                   3335:           }
                   3336:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3337:           ($value, $string)=&str2arrayref($string);
                   3338:           if($value->[0] eq 'Array reference error') {
                   3339:               $array[0] ='Array reference error';
                   3340:               return (\@array, $string);
                   3341:           }
                   3342:       } else {
                   3343: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3344:       }
                   3345:       $string =~ s/^&//;
                   3346: 
                   3347:       push(@array, $value);
1.191     harris41 3348:   }
1.265     albertel 3349: 
                   3350:   $string =~ s/^__END_ARRAY_REF__//;
                   3351: 
                   3352:   return (\@array, $string);
1.168     albertel 3353: }
                   3354: 
1.167     albertel 3355: # -------------------------------------------------------------------Temp Store
                   3356: 
1.168     albertel 3357: sub tmpreset {
                   3358:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3359:   if (!$symb) {
                   3360:     $symb=&symbread();
1.620     albertel 3361:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3362:   }
                   3363:   $symb=escape($symb);
                   3364: 
1.620     albertel 3365:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3366:   $namespace=~s/\//\_/g;
                   3367:   $namespace=~s/\W//g;
                   3368: 
1.620     albertel 3369:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3370:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3371:   if ($domain eq 'public' && $stuname eq 'public') {
                   3372:       $stuname=$ENV{'REMOTE_ADDR'};
                   3373:   }
1.168     albertel 3374:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3375:   my %hash;
                   3376:   if (tie(%hash,'GDBM_File',
                   3377: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3378: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3379:     foreach my $key (keys %hash) {
1.180     albertel 3380:       if ($key=~ /:$symb/) {
1.168     albertel 3381: 	delete($hash{$key});
                   3382:       }
                   3383:     }
                   3384:   }
                   3385: }
                   3386: 
1.167     albertel 3387: sub tmpstore {
1.168     albertel 3388:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3389: 
                   3390:   if (!$symb) {
                   3391:     $symb=&symbread();
1.620     albertel 3392:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3393:   }
                   3394:   $symb=escape($symb);
                   3395: 
                   3396:   if (!$namespace) {
                   3397:     # I don't think we would ever want to store this for a course.
                   3398:     # it seems this will only be used if we don't have a course.
1.620     albertel 3399:     #$namespace=$env{'request.course.id'};
1.168     albertel 3400:     #if (!$namespace) {
1.620     albertel 3401:       $namespace=$env{'request.state'};
1.168     albertel 3402:     #}
                   3403:   }
                   3404:   $namespace=~s/\//\_/g;
                   3405:   $namespace=~s/\W//g;
1.620     albertel 3406:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3407:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3408:   if ($domain eq 'public' && $stuname eq 'public') {
                   3409:       $stuname=$ENV{'REMOTE_ADDR'};
                   3410:   }
1.168     albertel 3411:   my $now=time;
                   3412:   my %hash;
                   3413:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3414:   if (tie(%hash,'GDBM_File',
                   3415: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3416: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3417:     $hash{"version:$symb"}++;
                   3418:     my $version=$hash{"version:$symb"};
                   3419:     my $allkeys=''; 
                   3420:     foreach my $key (keys(%$storehash)) {
                   3421:       $allkeys.=$key.':';
1.591     albertel 3422:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3423:     }
                   3424:     $hash{"$version:$symb:timestamp"}=$now;
                   3425:     $allkeys.='timestamp';
                   3426:     $hash{"$version:keys:$symb"}=$allkeys;
                   3427:     if (untie(%hash)) {
                   3428:       return 'ok';
                   3429:     } else {
                   3430:       return "error:$!";
                   3431:     }
                   3432:   } else {
                   3433:     return "error:$!";
                   3434:   }
                   3435: }
1.167     albertel 3436: 
1.168     albertel 3437: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3438: 
1.168     albertel 3439: sub tmprestore {
                   3440:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3441: 
1.168     albertel 3442:   if (!$symb) {
                   3443:     $symb=&symbread();
1.620     albertel 3444:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3445:   }
                   3446:   $symb=escape($symb);
                   3447: 
1.620     albertel 3448:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3449: 
1.620     albertel 3450:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3451:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3452:   if ($domain eq 'public' && $stuname eq 'public') {
                   3453:       $stuname=$ENV{'REMOTE_ADDR'};
                   3454:   }
1.168     albertel 3455:   my %returnhash;
                   3456:   $namespace=~s/\//\_/g;
                   3457:   $namespace=~s/\W//g;
                   3458:   my %hash;
                   3459:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3460:   if (tie(%hash,'GDBM_File',
                   3461: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3462: 	  &GDBM_READER(),0640)) {
1.168     albertel 3463:     my $version=$hash{"version:$symb"};
                   3464:     $returnhash{'version'}=$version;
                   3465:     my $scope;
                   3466:     for ($scope=1;$scope<=$version;$scope++) {
                   3467:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3468:       my @keys=split(/:/,$vkeys);
                   3469:       my $key;
                   3470:       $returnhash{"$scope:keys"}=$vkeys;
                   3471:       foreach $key (@keys) {
1.591     albertel 3472: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3473: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3474:       }
                   3475:     }
1.168     albertel 3476:     if (!(untie(%hash))) {
                   3477:       return "error:$!";
                   3478:     }
                   3479:   } else {
                   3480:     return "error:$!";
                   3481:   }
                   3482:   return %returnhash;
1.167     albertel 3483: }
                   3484: 
1.9       www      3485: # ----------------------------------------------------------------------- Store
                   3486: 
                   3487: sub store {
1.124     www      3488:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3489:     my $home='';
                   3490: 
1.168     albertel 3491:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3492: 
1.213     www      3493:     $symb=&symbclean($symb);
1.122     albertel 3494:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3495: 
1.620     albertel 3496:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3497:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3498: 
                   3499:     &devalidate($symb,$stuname,$domain);
1.109     www      3500: 
                   3501:     $symb=escape($symb);
1.187     www      3502:     if (!$namespace) { 
1.620     albertel 3503:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3504:           return ''; 
                   3505:        } 
                   3506:     }
1.620     albertel 3507:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3508: 
                   3509:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3510:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3511: 
1.12      www      3512:     my $namevalue='';
1.800     albertel 3513:     foreach my $key (keys(%$storehash)) {
                   3514:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3515:     }
1.12      www      3516:     $namevalue=~s/\&$//;
1.187     www      3517:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3518:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3519: }
                   3520: 
1.47      www      3521: # -------------------------------------------------------------- Critical Store
                   3522: 
                   3523: sub cstore {
1.124     www      3524:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3525:     my $home='';
                   3526: 
1.168     albertel 3527:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3528: 
1.213     www      3529:     $symb=&symbclean($symb);
1.122     albertel 3530:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3531: 
1.620     albertel 3532:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3533:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3534: 
                   3535:     &devalidate($symb,$stuname,$domain);
1.109     www      3536: 
                   3537:     $symb=escape($symb);
1.187     www      3538:     if (!$namespace) { 
1.620     albertel 3539:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3540:           return ''; 
                   3541:        } 
                   3542:     }
1.620     albertel 3543:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3544: 
                   3545:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3546:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3547: 
1.47      www      3548:     my $namevalue='';
1.800     albertel 3549:     foreach my $key (keys(%$storehash)) {
                   3550:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3551:     }
1.47      www      3552:     $namevalue=~s/\&$//;
1.187     www      3553:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3554:     return critical
                   3555:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3556: }
                   3557: 
1.9       www      3558: # --------------------------------------------------------------------- Restore
                   3559: 
                   3560: sub restore {
1.124     www      3561:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3562:     my $home='';
                   3563: 
1.168     albertel 3564:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3565: 
1.122     albertel 3566:     if (!$symb) {
                   3567:       unless ($symb=escape(&symbread())) { return ''; }
                   3568:     } else {
1.213     www      3569:       $symb=&escape(&symbclean($symb));
1.122     albertel 3570:     }
1.188     www      3571:     if (!$namespace) { 
1.620     albertel 3572:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3573:           return ''; 
                   3574:        } 
                   3575:     }
1.620     albertel 3576:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3577:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3578:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3579:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3580: 
1.12      www      3581:     my %returnhash=();
1.800     albertel 3582:     foreach my $line (split(/\&/,$answer)) {
                   3583: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3584:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3585:     }
1.75      www      3586:     my $version;
                   3587:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3588:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3589:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3590:        }
1.75      www      3591:     }
1.13      www      3592:     return %returnhash;
1.34      www      3593: }
                   3594: 
                   3595: # ---------------------------------------------------------- Course Description
                   3596: 
                   3597: sub coursedescription {
1.731     albertel 3598:     my ($courseid,$args)=@_;
1.34      www      3599:     $courseid=~s/^\///;
1.49      www      3600:     $courseid=~s/\_/\//g;
1.34      www      3601:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3602:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3603:     my $normalid=$cdomain.'_'.$cnum;
                   3604:     # need to always cache even if we get errors otherwise we keep 
                   3605:     # trying and trying and trying to get the course description.
                   3606:     my %envhash=();
                   3607:     my %returnhash=();
1.731     albertel 3608:     
                   3609:     my $expiretime=600;
                   3610:     if ($env{'request.course.id'} eq $normalid) {
                   3611: 	$expiretime=120;
                   3612:     }
                   3613: 
                   3614:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3615:     if (!$args->{'freshen_cache'}
                   3616: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3617: 	foreach my $key (keys(%env)) {
                   3618: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3619: 	    my ($setting) = $1;
                   3620: 	    $returnhash{$setting} = $env{$key};
                   3621: 	}
                   3622: 	return %returnhash;
                   3623:     }
                   3624: 
                   3625:     # get the data agin
                   3626:     if (!$args->{'one_time'}) {
                   3627: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3628:     }
1.811     albertel 3629: 
1.34      www      3630:     if ($chome ne 'no_host') {
1.302     albertel 3631:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3632:        if (!exists($returnhash{'con_lost'})) {
                   3633:            $returnhash{'home'}= $chome;
                   3634: 	   $returnhash{'domain'} = $cdomain;
                   3635: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3636:            if (!defined($returnhash{'type'})) {
                   3637:                $returnhash{'type'} = 'Course';
                   3638:            }
1.130     albertel 3639:            while (my ($name,$value) = each %returnhash) {
1.53      www      3640:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3641:            }
1.270     www      3642:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3643:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3644: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3645:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3646:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3647:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3648:        }
                   3649:     }
1.731     albertel 3650:     if (!$args->{'one_time'}) {
1.949     raeburn  3651: 	&appenv(\%envhash);
1.731     albertel 3652:     }
1.302     albertel 3653:     return %returnhash;
1.461     www      3654: }
                   3655: 
                   3656: # -------------------------------------------------See if a user is privileged
                   3657: 
                   3658: sub privileged {
                   3659:     my ($username,$domain)=@_;
                   3660:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3661: 			&homeserver($username,$domain));
                   3662:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3663:     my $now=time;
                   3664:     if ($rolesdump ne '') {
1.800     albertel 3665:         foreach my $entry (split(/&/,$rolesdump)) {
                   3666: 	    if ($entry!~/^rolesdef_/) {
                   3667: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3668: 		$area=~s/\_\w\w$//;
                   3669: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3670: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3671: 		    my $active=1;
                   3672: 		    if ($tend) {
                   3673: 			if ($tend<$now) { $active=0; }
                   3674: 		    }
                   3675: 		    if ($tstart) {
                   3676: 			if ($tstart>$now) { $active=0; }
                   3677: 		    }
                   3678: 		    if ($active) { return 1; }
                   3679: 		}
                   3680: 	    }
                   3681: 	}
                   3682:     }
                   3683:     return 0;
1.9       www      3684: }
1.1       albertel 3685: 
1.103     harris41 3686: # -------------------------------------------------------- Get user privileges
1.11      www      3687: 
                   3688: sub rolesinit {
                   3689:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3690:     my %userroles;
1.11      www      3691:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3692:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3693:     my %allroles=();
1.678     raeburn  3694:     my %allgroups=();   
1.11      www      3695:     my $now=time;
1.966     raeburn  3696:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3697:     my $group_privs;
1.11      www      3698: 
                   3699:     if ($rolesdump ne '') {
1.800     albertel 3700:         foreach my $entry (split(/&/,$rolesdump)) {
                   3701: 	  if ($entry!~/^rolesdef_/) {
                   3702:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3703: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3704:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3705: 	    if ($role=~/^cr/) { 
1.807     albertel 3706: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3707: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3708: 		    ($tend,$tstart)=split('_',$trest);
                   3709: 		} else {
                   3710: 		    $trole=$role;
                   3711: 		}
1.678     raeburn  3712:             } elsif ($role =~ m|^gr/|) {
                   3713:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3714:                 ($trole,$group_privs) = split(/\//,$trole);
                   3715:                 $group_privs = &unescape($group_privs);
1.587     albertel 3716: 	    } else {
                   3717: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3718: 	    }
1.743     albertel 3719: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3720: 					 $username);
                   3721: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3722:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3723:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3724:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3725: 		my $spec=$trole.'.'.$area;
                   3726: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3727: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3728:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3729:                 } elsif ($trole eq 'gr') {
                   3730:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3731: 		} else {
1.567     raeburn  3732:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3733: 		}
1.12      www      3734:             }
1.662     raeburn  3735:           }
1.191     harris41 3736:         }
1.743     albertel 3737:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3738:         $userroles{'user.adv'}    = $adv;
                   3739: 	$userroles{'user.author'} = $author;
1.620     albertel 3740:         $env{'user.adv'}=$adv;
1.11      www      3741:     }
1.743     albertel 3742:     return \%userroles;  
1.11      www      3743: }
                   3744: 
1.567     raeburn  3745: sub set_arearole {
                   3746:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3747: # log the associated role with the area
                   3748:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3749:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3750: }
                   3751: 
                   3752: sub custom_roleprivs {
                   3753:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3754:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3755:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3756:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3757:         my ($rdummy,$roledef)=
                   3758:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3759:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3760:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3761:             if (defined($syspriv)) {
                   3762:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3763:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3764:             }
                   3765:             if ($tdomain ne '') {
                   3766:                 if (defined($dompriv)) {
                   3767:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3768:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3769:                 }
                   3770:                 if (($trest ne '') && (defined($coursepriv))) {
                   3771:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3772:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3773:                 }
                   3774:             }
                   3775:         }
                   3776:     }
                   3777: }
                   3778: 
1.678     raeburn  3779: sub group_roleprivs {
                   3780:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3781:     my $access = 1;
                   3782:     my $now = time;
                   3783:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3784:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3785:     if ($access) {
1.811     albertel 3786:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3787:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3788:     }
                   3789: }
1.567     raeburn  3790: 
                   3791: sub standard_roleprivs {
                   3792:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3793:     if (defined($pr{$trole.':s'})) {
                   3794:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3795:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3796:     }
                   3797:     if ($tdomain ne '') {
                   3798:         if (defined($pr{$trole.':d'})) {
                   3799:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3800:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3801:         }
                   3802:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3803:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3804:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3805:         }
                   3806:     }
                   3807: }
                   3808: 
                   3809: sub set_userprivs {
1.678     raeburn  3810:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3811:     my $author=0;
                   3812:     my $adv=0;
1.678     raeburn  3813:     my %grouproles = ();
                   3814:     if (keys(%{$allgroups}) > 0) {
                   3815:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3816:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3817:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3818:                 $trole = $1;
                   3819:                 $area = $2;
1.681     raeburn  3820:                 $sec = $3;
                   3821:                 $extendedarea = $area.$sec;
                   3822:                 if (exists($$allgroups{$area})) {
                   3823:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3824:                         my $spec = $trole.'.'.$extendedarea;
                   3825:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3826:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3827:                     }
                   3828:                 }
                   3829:             }
                   3830:         }
                   3831:     }
1.800     albertel 3832:     foreach my $group (keys(%grouproles)) {
                   3833:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3834:     }
1.800     albertel 3835:     foreach my $role (keys(%{$allroles})) {
                   3836:         my %thesepriv;
1.941     raeburn  3837:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3838:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3839:             if ($item ne '') {
                   3840:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3841:                 if ($restrictions eq '') {
                   3842:                     $thesepriv{$privilege}='F';
                   3843:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3844:                     $thesepriv{$privilege}.=$restrictions;
                   3845:                 }
                   3846:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3847:             }
                   3848:         }
                   3849:         my $thesestr='';
1.800     albertel 3850:         foreach my $priv (keys(%thesepriv)) {
                   3851: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3852: 	}
                   3853:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3854:     }
                   3855:     return ($author,$adv);
                   3856: }
                   3857: 
1.12      www      3858: # --------------------------------------------------------------- get interface
                   3859: 
                   3860: sub get {
1.131     albertel 3861:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3862:    my $items='';
1.800     albertel 3863:    foreach my $item (@$storearr) {
                   3864:        $items.=&escape($item).'&';
1.191     harris41 3865:    }
1.12      www      3866:    $items=~s/\&$//;
1.620     albertel 3867:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3868:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3869:    my $uhome=&homeserver($uname,$udomain);
                   3870: 
1.133     albertel 3871:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3872:    my @pairs=split(/\&/,$rep);
1.273     albertel 3873:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3874:      return @pairs;
                   3875:    }
1.15      www      3876:    my %returnhash=();
1.42      www      3877:    my $i=0;
1.800     albertel 3878:    foreach my $item (@$storearr) {
                   3879:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3880:       $i++;
1.191     harris41 3881:    }
1.15      www      3882:    return %returnhash;
1.27      www      3883: }
                   3884: 
                   3885: # --------------------------------------------------------------- del interface
                   3886: 
                   3887: sub del {
1.133     albertel 3888:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3889:    my $items='';
1.800     albertel 3890:    foreach my $item (@$storearr) {
                   3891:        $items.=&escape($item).'&';
1.191     harris41 3892:    }
1.984     neumanie 3893: 
1.27      www      3894:    $items=~s/\&$//;
1.620     albertel 3895:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3896:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3897:    my $uhome=&homeserver($uname,$udomain);
                   3898:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3899: }
                   3900: 
                   3901: # -------------------------------------------------------------- dump interface
                   3902: 
                   3903: sub dump {
1.755     albertel 3904:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3905:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3906:     if (!$uname) { $uname=$env{'user.name'}; }
                   3907:     my $uhome=&homeserver($uname,$udomain);
                   3908:     if ($regexp) {
                   3909: 	$regexp=&escape($regexp);
                   3910:     } else {
                   3911: 	$regexp='.';
                   3912:     }
                   3913:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3914:     my @pairs=split(/\&/,$rep);
                   3915:     my %returnhash=();
                   3916:     foreach my $item (@pairs) {
                   3917: 	my ($key,$value)=split(/=/,$item,2);
                   3918: 	$key = &unescape($key);
                   3919: 	next if ($key =~ /^error: 2 /);
                   3920: 	$returnhash{$key}=&thaw_unescape($value);
                   3921:     }
                   3922:     return %returnhash;
1.407     www      3923: }
                   3924: 
1.717     albertel 3925: # --------------------------------------------------------- dumpstore interface
                   3926: 
                   3927: sub dumpstore {
                   3928:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3929:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3930:    if (!$uname) { $uname=$env{'user.name'}; }
                   3931:    my $uhome=&homeserver($uname,$udomain);
                   3932:    if ($regexp) {
                   3933:        $regexp=&escape($regexp);
                   3934:    } else {
                   3935:        $regexp='.';
                   3936:    }
                   3937:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3938:    my @pairs=split(/\&/,$rep);
                   3939:    my %returnhash=();
                   3940:    foreach my $item (@pairs) {
                   3941:        my ($key,$value)=split(/=/,$item,2);
                   3942:        next if ($key =~ /^error: 2 /);
                   3943:        $returnhash{$key}=&thaw_unescape($value);
                   3944:    }
                   3945:    return %returnhash;
1.717     albertel 3946: }
                   3947: 
1.407     www      3948: # -------------------------------------------------------------- keys interface
                   3949: 
                   3950: sub getkeys {
                   3951:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3952:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3953:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3954:    my $uhome=&homeserver($uname,$udomain);
                   3955:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3956:    my @keyarray=();
1.800     albertel 3957:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3958:       next if ($key =~ /^error: 2 /);
1.800     albertel 3959:       push(@keyarray,&unescape($key));
1.407     www      3960:    }
                   3961:    return @keyarray;
1.318     matthew  3962: }
                   3963: 
1.319     matthew  3964: # --------------------------------------------------------------- currentdump
                   3965: sub currentdump {
1.328     matthew  3966:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3967:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3968:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3969:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3970:    my $uhome = &homeserver($sname,$sdom);
                   3971:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3972:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3973:    #
1.318     matthew  3974:    my %returnhash=();
1.319     matthew  3975:    #
                   3976:    if ($rep eq "unknown_cmd") { 
                   3977:        # an old lond will not know currentdump
                   3978:        # Do a dump and make it look like a currentdump
1.822     albertel 3979:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3980:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3981:        my %hash = @tmp;
                   3982:        @tmp=();
1.424     matthew  3983:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3984:    } else {
                   3985:        my @pairs=split(/\&/,$rep);
1.800     albertel 3986:        foreach my $pair (@pairs) {
                   3987:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3988:            my ($symb,$param) = split(/:/,$key);
                   3989:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3990:                                                         &thaw_unescape($value);
1.319     matthew  3991:        }
1.191     harris41 3992:    }
1.12      www      3993:    return %returnhash;
1.424     matthew  3994: }
                   3995: 
                   3996: sub convert_dump_to_currentdump{
                   3997:     my %hash = %{shift()};
                   3998:     my %returnhash;
                   3999:     # Code ripped from lond, essentially.  The only difference
                   4000:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4001:     # we might run in to problems with parameter names =~ /^v\./
                   4002:     while (my ($key,$value) = each(%hash)) {
                   4003:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4004: 	$symb  = &unescape($symb);
                   4005: 	$param = &unescape($param);
1.424     matthew  4006:         next if ($v eq 'version' || $symb eq 'keys');
                   4007:         next if (exists($returnhash{$symb}) &&
                   4008:                  exists($returnhash{$symb}->{$param}) &&
                   4009:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4010:         $returnhash{$symb}->{$param}=$value;
                   4011:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4012:     }
                   4013:     #
                   4014:     # Remove all of the keys in the hashes which keep track of
                   4015:     # the version of the parameter.
                   4016:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4017:         # use a foreach because we are going to delete from the hash.
                   4018:         foreach my $key (keys(%$param_hash)) {
                   4019:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4020:         }
                   4021:     }
                   4022:     return \%returnhash;
1.12      www      4023: }
                   4024: 
1.627     albertel 4025: # ------------------------------------------------------ critical inc interface
                   4026: 
                   4027: sub cinc {
                   4028:     return &inc(@_,'critical');
                   4029: }
                   4030: 
1.449     matthew  4031: # --------------------------------------------------------------- inc interface
                   4032: 
                   4033: sub inc {
1.627     albertel 4034:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4035:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4036:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4037:     my $uhome=&homeserver($uname,$udomain);
                   4038:     my $items='';
                   4039:     if (! ref($store)) {
                   4040:         # got a single value, so use that instead
                   4041:         $items = &escape($store).'=&';
                   4042:     } elsif (ref($store) eq 'SCALAR') {
                   4043:         $items = &escape($$store).'=&';        
                   4044:     } elsif (ref($store) eq 'ARRAY') {
                   4045:         $items = join('=&',map {&escape($_);} @{$store});
                   4046:     } elsif (ref($store) eq 'HASH') {
                   4047:         while (my($key,$value) = each(%{$store})) {
                   4048:             $items.= &escape($key).'='.&escape($value).'&';
                   4049:         }
                   4050:     }
                   4051:     $items=~s/\&$//;
1.627     albertel 4052:     if ($critical) {
                   4053: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4054:     } else {
                   4055: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4056:     }
1.449     matthew  4057: }
                   4058: 
1.12      www      4059: # --------------------------------------------------------------- put interface
                   4060: 
                   4061: sub put {
1.134     albertel 4062:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4063:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4064:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4065:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4066:    my $items='';
1.800     albertel 4067:    foreach my $item (keys(%$storehash)) {
                   4068:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4069:    }
1.12      www      4070:    $items=~s/\&$//;
1.134     albertel 4071:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4072: }
                   4073: 
1.631     albertel 4074: # ------------------------------------------------------------ newput interface
                   4075: 
                   4076: sub newput {
                   4077:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4078:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4079:    if (!$uname) { $uname=$env{'user.name'}; }
                   4080:    my $uhome=&homeserver($uname,$udomain);
                   4081:    my $items='';
                   4082:    foreach my $key (keys(%$storehash)) {
                   4083:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4084:    }
                   4085:    $items=~s/\&$//;
                   4086:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4087: }
                   4088: 
                   4089: # ---------------------------------------------------------  putstore interface
                   4090: 
1.524     raeburn  4091: sub putstore {
1.715     albertel 4092:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4093:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4094:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4095:    my $uhome=&homeserver($uname,$udomain);
                   4096:    my $items='';
1.715     albertel 4097:    foreach my $key (keys(%$storehash)) {
                   4098:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4099:    }
1.715     albertel 4100:    $items=~s/\&$//;
1.716     albertel 4101:    my $esc_symb=&escape($symb);
                   4102:    my $esc_v=&escape($version);
1.715     albertel 4103:    my $reply =
1.716     albertel 4104:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4105: 	      $uhome);
                   4106:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4107:        # gfall back to way things use to be done
1.715     albertel 4108:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4109: 			    $uname);
1.524     raeburn  4110:    }
1.715     albertel 4111:    return $reply;
                   4112: }
                   4113: 
                   4114: sub old_putstore {
1.716     albertel 4115:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4116:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4117:     if (!$uname) { $uname=$env{'user.name'}; }
                   4118:     my $uhome=&homeserver($uname,$udomain);
                   4119:     my %newstorehash;
1.800     albertel 4120:     foreach my $item (keys(%$storehash)) {
                   4121: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4122: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4123:     }
                   4124:     my $items='';
                   4125:     my %allitems = ();
1.800     albertel 4126:     foreach my $item (keys(%newstorehash)) {
                   4127: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4128: 	    my $key = $1.':keys:'.$2;
                   4129: 	    $allitems{$key} .= $3.':';
                   4130: 	}
1.800     albertel 4131: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4132:     }
1.800     albertel 4133:     foreach my $item (keys(%allitems)) {
                   4134: 	$allitems{$item} =~ s/\:$//;
                   4135: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4136:     }
                   4137:     $items=~s/\&$//;
                   4138:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4139: }
                   4140: 
1.47      www      4141: # ------------------------------------------------------ critical put interface
                   4142: 
                   4143: sub cput {
1.134     albertel 4144:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4145:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4146:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4147:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4148:    my $items='';
1.800     albertel 4149:    foreach my $item (keys(%$storehash)) {
                   4150:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4151:    }
1.47      www      4152:    $items=~s/\&$//;
1.134     albertel 4153:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4154: }
                   4155: 
                   4156: # -------------------------------------------------------------- eget interface
                   4157: 
                   4158: sub eget {
1.133     albertel 4159:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4160:    my $items='';
1.800     albertel 4161:    foreach my $item (@$storearr) {
                   4162:        $items.=&escape($item).'&';
1.191     harris41 4163:    }
1.12      www      4164:    $items=~s/\&$//;
1.620     albertel 4165:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4166:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4167:    my $uhome=&homeserver($uname,$udomain);
                   4168:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4169:    my @pairs=split(/\&/,$rep);
                   4170:    my %returnhash=();
1.42      www      4171:    my $i=0;
1.800     albertel 4172:    foreach my $item (@$storearr) {
                   4173:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4174:       $i++;
1.191     harris41 4175:    }
1.12      www      4176:    return %returnhash;
                   4177: }
                   4178: 
1.667     albertel 4179: # ------------------------------------------------------------ tmpput interface
                   4180: sub tmpput {
1.802     raeburn  4181:     my ($storehash,$server,$context)=@_;
1.667     albertel 4182:     my $items='';
1.800     albertel 4183:     foreach my $item (keys(%$storehash)) {
                   4184: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4185:     }
                   4186:     $items=~s/\&$//;
1.802     raeburn  4187:     if (defined($context)) {
                   4188:         $items .= ':'.&escape($context);
                   4189:     }
1.667     albertel 4190:     return &reply("tmpput:$items",$server);
                   4191: }
                   4192: 
                   4193: # ------------------------------------------------------------ tmpget interface
                   4194: sub tmpget {
1.688     albertel 4195:     my ($token,$server)=@_;
                   4196:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4197:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4198:     my %returnhash;
                   4199:     foreach my $item (split(/\&/,$rep)) {
                   4200: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4201:         next if ($key =~ /^error: 2 /);
1.667     albertel 4202: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4203:     }
                   4204:     return %returnhash;
                   4205: }
                   4206: 
1.688     albertel 4207: # ------------------------------------------------------------ tmpget interface
                   4208: sub tmpdel {
                   4209:     my ($token,$server)=@_;
                   4210:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4211:     return &reply("tmpdel:$token",$server);
                   4212: }
                   4213: 
1.765     albertel 4214: # -------------------------------------------------- portfolio access checking
                   4215: 
                   4216: sub portfolio_access {
1.766     albertel 4217:     my ($requrl) = @_;
1.765     albertel 4218:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4219:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4220:     if ($result) {
                   4221:         my %setters;
                   4222:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4223:             my ($startblock,$endblock) =
                   4224:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4225:             if ($startblock && $endblock) {
                   4226:                 return 'B';
                   4227:             }
                   4228:         } else {
                   4229:             my ($startblock,$endblock) =
                   4230:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4231:             if ($startblock && $endblock) {
                   4232:                 return 'B';
                   4233:             }
                   4234:         }
                   4235:     }
1.765     albertel 4236:     if ($result eq 'ok') {
1.766     albertel 4237:        return 'F';
1.765     albertel 4238:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4239:        return 'A';
1.765     albertel 4240:     }
1.766     albertel 4241:     return '';
1.765     albertel 4242: }
                   4243: 
                   4244: sub get_portfolio_access {
1.767     albertel 4245:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4246: 
                   4247:     if (!ref($access_hash)) {
                   4248: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4249: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4250: 						   $file_name);
                   4251: 	$access_hash = $access_controls{$file_name};
                   4252:     }
                   4253: 
1.765     albertel 4254:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4255:     my $now = time;
                   4256:     if (ref($access_hash) eq 'HASH') {
                   4257:         foreach my $key (keys(%{$access_hash})) {
                   4258:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4259:             if ($start > $now) {
                   4260:                 next;
                   4261:             }
                   4262:             if ($end && $end<$now) {
                   4263:                 next;
                   4264:             }
                   4265:             if ($scope eq 'public') {
                   4266:                 $public = $key;
                   4267:                 last;
                   4268:             } elsif ($scope eq 'guest') {
                   4269:                 $guest = $key;
                   4270:             } elsif ($scope eq 'domains') {
                   4271:                 push(@domains,$key);
                   4272:             } elsif ($scope eq 'users') {
                   4273:                 push(@users,$key);
                   4274:             } elsif ($scope eq 'course') {
                   4275:                 push(@courses,$key);
                   4276:             } elsif ($scope eq 'group') {
                   4277:                 push(@groups,$key);
                   4278:             }
                   4279:         }
                   4280:         if ($public) {
                   4281:             return 'ok';
                   4282:         }
                   4283:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4284:             if ($guest) {
                   4285:                 return $guest;
                   4286:             }
                   4287:         } else {
                   4288:             if (@domains > 0) {
                   4289:                 foreach my $domkey (@domains) {
                   4290:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4291:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4292:                             return 'ok';
                   4293:                         }
                   4294:                     }
                   4295:                 }
                   4296:             }
                   4297:             if (@users > 0) {
                   4298:                 foreach my $userkey (@users) {
1.865     raeburn  4299:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4300:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4301:                             if (ref($item) eq 'HASH') {
                   4302:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4303:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4304:                                     return 'ok';
                   4305:                                 }
                   4306:                             }
                   4307:                         }
                   4308:                     } 
1.765     albertel 4309:                 }
                   4310:             }
                   4311:             my %roleshash;
                   4312:             my @courses_and_groups = @courses;
                   4313:             push(@courses_and_groups,@groups); 
                   4314:             if (@courses_and_groups > 0) {
                   4315:                 my (%allgroups,%allroles); 
                   4316:                 my ($start,$end,$role,$sec,$group);
                   4317:                 foreach my $envkey (%env) {
1.811     albertel 4318:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4319:                         my $cid = $2.'_'.$3; 
                   4320:                         if ($1 eq 'gr') {
                   4321:                             $group = $4;
                   4322:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4323:                         } else {
                   4324:                             if ($4 eq '') {
                   4325:                                 $sec = 'none';
                   4326:                             } else {
                   4327:                                 $sec = $4;
                   4328:                             }
                   4329:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4330:                         }
1.811     albertel 4331:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4332:                         my $cid = $2.'_'.$3;
                   4333:                         if ($4 eq '') {
                   4334:                             $sec = 'none';
                   4335:                         } else {
                   4336:                             $sec = $4;
                   4337:                         }
                   4338:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4339:                     }
                   4340:                 }
                   4341:                 if (keys(%allroles) == 0) {
                   4342:                     return;
                   4343:                 }
                   4344:                 foreach my $key (@courses_and_groups) {
                   4345:                     my %content = %{$$access_hash{$key}};
                   4346:                     my $cnum = $content{'number'};
                   4347:                     my $cdom = $content{'domain'};
                   4348:                     my $cid = $cdom.'_'.$cnum;
                   4349:                     if (!exists($allroles{$cid})) {
                   4350:                         next;
                   4351:                     }    
                   4352:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4353:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4354:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4355:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4356:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4357:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4358:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4359:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4360:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4361:                                         if (grep/^all$/,@sections) {
                   4362:                                             return 'ok';
                   4363:                                         } else {
                   4364:                                             if (grep/^$sec$/,@sections) {
                   4365:                                                 return 'ok';
                   4366:                                             }
                   4367:                                         }
                   4368:                                     }
                   4369:                                 }
                   4370:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4371:                                     if (grep/^none$/,@groups) {
                   4372:                                         return 'ok';
                   4373:                                     }
                   4374:                                 } else {
                   4375:                                     if (grep/^all$/,@groups) {
                   4376:                                         return 'ok';
                   4377:                                     } 
                   4378:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4379:                                         if (grep/^$group$/,@groups) {
                   4380:                                             return 'ok';
                   4381:                                         }
                   4382:                                     }
                   4383:                                 } 
                   4384:                             }
                   4385:                         }
                   4386:                     }
                   4387:                 }
                   4388:             }
                   4389:             if ($guest) {
                   4390:                 return $guest;
                   4391:             }
                   4392:         }
                   4393:     }
                   4394:     return;
                   4395: }
                   4396: 
                   4397: sub course_group_datechecker {
                   4398:     my ($dates,$now,$status) = @_;
                   4399:     my ($start,$end) = split(/\./,$dates);
                   4400:     if (!$start && !$end) {
                   4401:         return 'ok';
                   4402:     }
                   4403:     if (grep/^active$/,@{$status}) {
                   4404:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4405:             return 'ok';
                   4406:         }
                   4407:     }
                   4408:     if (grep/^previous$/,@{$status}) {
                   4409:         if ($end > $now ) {
                   4410:             return 'ok';
                   4411:         }
                   4412:     }
                   4413:     if (grep/^future$/,@{$status}) {
                   4414:         if ($start > $now) {
                   4415:             return 'ok';
                   4416:         }
                   4417:     }
                   4418:     return; 
                   4419: }
                   4420: 
                   4421: sub parse_portfolio_url {
                   4422:     my ($url) = @_;
                   4423: 
                   4424:     my ($type,$udom,$unum,$group,$file_name);
                   4425:     
1.823     albertel 4426:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4427: 	$type = 1;
                   4428:         $udom = $1;
                   4429:         $unum = $2;
                   4430:         $file_name = $3;
1.823     albertel 4431:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4432: 	$type = 2;
                   4433:         $udom = $1;
                   4434:         $unum = $2;
                   4435:         $group = $3;
                   4436:         $file_name = $3.'/'.$4;
                   4437:     }
                   4438:     if (wantarray) {
                   4439: 	return ($type,$udom,$unum,$file_name,$group);
                   4440:     }
                   4441:     return $type;
                   4442: }
                   4443: 
                   4444: sub is_portfolio_url {
                   4445:     my ($url) = @_;
                   4446:     return scalar(&parse_portfolio_url($url));
                   4447: }
                   4448: 
1.798     raeburn  4449: sub is_portfolio_file {
                   4450:     my ($file) = @_;
1.820     raeburn  4451:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4452:         return 1;
                   4453:     }
                   4454:     return;
                   4455: }
                   4456: 
1.976     raeburn  4457: sub usertools_access {
1.985     raeburn  4458:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4459:     my ($access,%tools);
                   4460:     if ($context eq '') {
                   4461:         $context = 'tools';
                   4462:     }
                   4463:     if ($context eq 'requestcourses') {
                   4464:         %tools = (
                   4465:                       official   => 1,
                   4466:                       unofficial => 1,
                   4467:                  );
                   4468:     } else {
                   4469:         %tools = (
                   4470:                       aboutme   => 1,
                   4471:                       blog      => 1,
                   4472:                       portfolio => 1,
                   4473:                  );
                   4474:     }
1.976     raeburn  4475:     return if (!defined($tools{$tool}));
                   4476: 
                   4477:     if ((!defined($udom)) || (!defined($uname))) {
                   4478:         $udom = $env{'user.domain'};
                   4479:         $uname = $env{'user.name'};
                   4480:     }
                   4481: 
1.978     raeburn  4482:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4483:         if ($action ne 'reload') {
1.985     raeburn  4484:             if ($context eq 'requestcourses') {
                   4485:                 return $env{'environment.canrequest.'.$tool};
                   4486:             } else {
                   4487:                 return $env{'environment.availabletools.'.$tool};
                   4488:             }
                   4489:         }
1.976     raeburn  4490:     }
                   4491: 
                   4492:     my ($toolstatus,$inststatus);
                   4493: 
1.985     raeburn  4494:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4495:          ($action ne 'reload')) {
                   4496:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4497:         $inststatus = $env{'environment.inststatus'};
                   4498:     } else {
1.985     raeburn  4499:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
                   4500:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4501:         $inststatus = $userenv{'inststatus'};
                   4502:     }
                   4503: 
                   4504:     if ($toolstatus ne '') {
                   4505:         if ($toolstatus) {
                   4506:             $access = 1;
                   4507:         } else {
                   4508:             $access = 0;
                   4509:         }
                   4510:         return $access;
                   4511:     }
                   4512: 
                   4513:     my $is_adv = &is_advanced_user($udom,$uname);
                   4514:     my %domdef = &get_domain_defaults($udom);
                   4515:     if (ref($domdef{$tool}) eq 'HASH') {
                   4516:         if ($is_adv) {
                   4517:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4518:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4519:                     $access = 1;
                   4520:                 } else {
                   4521:                     $access = 0;
                   4522:                 }
                   4523:                 return $access;
                   4524:             }
                   4525:         }
                   4526:         if ($inststatus ne '') {
                   4527:             my ($hasaccess,$hasnoaccess);
                   4528:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4529:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4530:                     if ($domdef{$tool}{$affiliation}) {
                   4531:                         $hasaccess = 1;
                   4532:                     } else {
                   4533:                         $hasnoaccess = 1;
                   4534:                     }
                   4535:                 }
                   4536:             }
                   4537:             if ($hasaccess || $hasnoaccess) {
                   4538:                 if ($hasaccess) {
                   4539:                     $access = 1;
                   4540:                 } elsif ($hasnoaccess) {
                   4541:                     $access = 0; 
                   4542:                 }
                   4543:                 return $access;
                   4544:             }
                   4545:         } else {
                   4546:             if ($domdef{$tool}{'default'} ne '') {
                   4547:                 if ($domdef{$tool}{'default'}) {
                   4548:                     $access = 1;
                   4549:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4550:                     $access = 0;
                   4551:                 }
                   4552:                 return $access;
                   4553:             }
                   4554:         }
                   4555:     } else {
1.985     raeburn  4556:         if ($context eq 'tools') {
                   4557:             $access = 1;
                   4558:         } else {
                   4559:             $access = 0;
                   4560:         }
1.976     raeburn  4561:         return $access;
                   4562:     }
                   4563: }
                   4564: 
                   4565: sub is_advanced_user {
                   4566:     my ($udom,$uname) = @_;
                   4567:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4568:     my %allroles;
                   4569:     my $is_adv;
                   4570:     foreach my $role (keys(%roleshash)) {
                   4571:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4572:         my $area = '/'.$tdomain.'/'.$trest;
                   4573:         if ($sec ne '') {
                   4574:             $area .= '/'.$sec;
                   4575:         }
                   4576:         if (($area ne '') && ($trole ne '')) {
                   4577:             my $spec=$trole.'.'.$area;
                   4578:             if ($trole =~ /^cr\//) {
                   4579:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4580:             } elsif ($trole ne 'gr') {
                   4581:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4582:             }
                   4583:         }
                   4584:     }
                   4585:     foreach my $role (keys(%allroles)) {
                   4586:         last if ($is_adv);
                   4587:         foreach my $item (split(/:/,$allroles{$role})) {
                   4588:             if ($item ne '') {
                   4589:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4590:                 if ($privilege eq 'adv') {
                   4591:                     $is_adv = 1;
                   4592:                     last;
                   4593:                 }
                   4594:             }
                   4595:         }
                   4596:     }
                   4597:     return $is_adv;
                   4598: }
1.798     raeburn  4599: 
1.341     www      4600: # ---------------------------------------------- Custom access rule evaluation
                   4601: 
                   4602: sub customaccess {
                   4603:     my ($priv,$uri)=@_;
1.807     albertel 4604:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4605:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4606:     $udom = &LONCAPA::clean_domain($udom);
                   4607:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4608:     my $access=0;
1.800     albertel 4609:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4610: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4611: 	if ($type eq 'user') {
                   4612: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4613: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4614: 		if ($tdom) {
                   4615: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4616: 		}
1.896     albertel 4617: 		if ($tuname) {
                   4618: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4619: 		}
                   4620: 		$access=($effect eq 'allow');
                   4621: 		last;
                   4622: 	    }
                   4623: 	} else {
                   4624: 	    if ($role) {
                   4625: 		if ($role ne $urole) { next; }
                   4626: 	    }
                   4627: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4628: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4629: 		if ($tdom) {
                   4630: 		    if ($tdom ne $udom) { next; }
                   4631: 		}
                   4632: 		if ($tcrs) {
                   4633: 		    if ($tcrs ne $ucrs) { next; }
                   4634: 		}
                   4635: 		if ($tsec) {
                   4636: 		    if ($tsec ne $usec) { next; }
                   4637: 		}
                   4638: 		$access=($effect eq 'allow');
                   4639: 		last;
                   4640: 	    }
                   4641: 	    if ($realm eq '' && $role eq '') {
                   4642: 		$access=($effect eq 'allow');
                   4643: 	    }
1.402     bowersj2 4644: 	}
1.341     www      4645:     }
                   4646:     return $access;
                   4647: }
                   4648: 
1.103     harris41 4649: # ------------------------------------------------- Check for a user privilege
1.12      www      4650: 
                   4651: sub allowed {
1.810     raeburn  4652:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4653:     my $ver_orguri=$uri;
1.439     www      4654:     $uri=&deversion($uri);
1.152     www      4655:     my $orguri=$uri;
1.52      www      4656:     $uri=&declutter($uri);
1.809     raeburn  4657: 
1.810     raeburn  4658:     if ($priv eq 'evb') {
                   4659: # Evade communication block restrictions for specified role in a course
                   4660:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4661:             return $1;
                   4662:         } else {
                   4663:             return;
                   4664:         }
                   4665:     }
                   4666: 
1.620     albertel 4667:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4668: # Free bre access to adm and meta resources
1.775     albertel 4669:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4670: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4671: 	&& ($priv eq 'bre')) {
1.14      www      4672: 	return 'F';
1.159     www      4673:     }
                   4674: 
1.545     banghart 4675: # Free bre access to user's own portfolio contents
1.714     raeburn  4676:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4677:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4678: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4679:         my %setters;
                   4680:         my ($startblock,$endblock) = 
                   4681:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4682:         if ($startblock && $endblock) {
                   4683:             return 'B';
                   4684:         } else {
                   4685:             return 'F';
                   4686:         }
1.545     banghart 4687:     }
                   4688: 
1.762     raeburn  4689: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4690:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4691:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4692:         if (exists($env{'request.course.id'})) {
                   4693:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4694:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4695:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4696:                 my $courseprivid=$env{'request.course.id'};
                   4697:                 $courseprivid=~s/\_/\//;
                   4698:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4699:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4700:                     return $1; 
1.762     raeburn  4701:                 } else {
                   4702:                     if ($env{'request.course.sec'}) {
                   4703:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4704:                     }
                   4705:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4706:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4707:                         return $2;
                   4708:                     }
1.714     raeburn  4709:                 }
                   4710:             }
                   4711:         }
                   4712:     }
                   4713: 
1.159     www      4714: # Free bre to public access
                   4715: 
                   4716:     if ($priv eq 'bre') {
1.238     www      4717:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4718: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4719:            return 'F'; 
                   4720:         }
1.238     www      4721:         if ($copyright eq 'priv') {
                   4722:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4723: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4724: 		return '';
                   4725:             }
                   4726:         }
                   4727:         if ($copyright eq 'domain') {
                   4728:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4729: 	    unless (($env{'user.domain'} eq $1) ||
                   4730:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4731: 		return '';
                   4732:             }
1.262     matthew  4733:         }
1.620     albertel 4734:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4735:             # Library role, so allow browsing of resources in this domain.
                   4736:             return 'F';
1.238     www      4737:         }
1.341     www      4738:         if ($copyright eq 'custom') {
                   4739: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4740:         }
1.14      www      4741:     }
1.264     matthew  4742:     # Domain coordinator is trying to create a course
1.620     albertel 4743:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4744:         # uri is the requested domain in this case.
                   4745:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4746:         # a role of dc for the domain in question.
1.620     albertel 4747:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4748:     }
1.29      www      4749: 
1.52      www      4750:     my $thisallowed='';
                   4751:     my $statecond=0;
                   4752:     my $courseprivid='';
                   4753: 
                   4754: # Course
                   4755: 
1.620     albertel 4756:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4757:        $thisallowed.=$1;
                   4758:     }
1.29      www      4759: 
1.52      www      4760: # Domain
                   4761: 
1.620     albertel 4762:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4763:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4764:        $thisallowed.=$1;
                   4765:     }
1.52      www      4766: 
                   4767: # Course: uri itself is a course
1.66      www      4768:     my $courseuri=$uri;
                   4769:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4770:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4771: 
1.620     albertel 4772:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4773:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4774:        $thisallowed.=$1;
                   4775:     }
1.29      www      4776: 
1.665     albertel 4777: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4778: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4779:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4780: 	$thisallowed='';
1.671     raeburn  4781:         my ($match)=&is_on_map($uri);
                   4782:         if ($match) {
                   4783:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4784:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4785:                 $thisallowed.=$1;
                   4786:             }
                   4787:         } else {
1.705     albertel 4788:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4789:             if ($refuri) {
                   4790:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4791:                     $thisallowed='F';
1.671     raeburn  4792:                 } else {
                   4793:                     $refuri=&declutter($refuri);
                   4794:                     my ($match) = &is_on_map($refuri);
                   4795:                     if ($match) {
                   4796:                         $thisallowed='F';
                   4797:                     }
1.669     raeburn  4798:                 }
1.671     raeburn  4799:             }
                   4800:         }
1.314     www      4801:     }
1.492     albertel 4802: 
1.766     albertel 4803:     if ($priv eq 'bre'
                   4804: 	&& $thisallowed ne 'F' 
                   4805: 	&& $thisallowed ne '2'
                   4806: 	&& &is_portfolio_url($uri)) {
                   4807: 	$thisallowed = &portfolio_access($uri);
                   4808:     }
                   4809:     
1.52      www      4810: # Full access at system, domain or course-wide level? Exit.
1.29      www      4811:     if ($thisallowed=~/F/) {
                   4812: 	return 'F';
                   4813:     }
                   4814: 
1.52      www      4815: # If this is generating or modifying users, exit with special codes
1.29      www      4816: 
1.643     www      4817:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4818: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4819: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4820: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4821: 	    unless ($auname) { return $thisallowed; }
                   4822: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4823: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4824: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4825: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4826: 	}
1.52      www      4827: 	return $thisallowed;
                   4828:     }
                   4829: #
1.103     harris41 4830: # Gathered so far: system, domain and course wide privileges
1.52      www      4831: #
                   4832: # Course: See if uri or referer is an individual resource that is part of 
                   4833: # the course
                   4834: 
1.620     albertel 4835:     if ($env{'request.course.id'}) {
1.232     www      4836: 
1.620     albertel 4837:        $courseprivid=$env{'request.course.id'};
                   4838:        if ($env{'request.course.sec'}) {
                   4839:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4840:        }
                   4841:        $courseprivid=~s/\_/\//;
                   4842:        my $checkreferer=1;
1.232     www      4843:        my ($match,$cond)=&is_on_map($uri);
                   4844:        if ($match) {
                   4845:            $statecond=$cond;
1.620     albertel 4846:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4847:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4848:                $thisallowed.=$1;
                   4849:                $checkreferer=0;
                   4850:            }
1.29      www      4851:        }
1.83      www      4852:        
1.148     www      4853:        if ($checkreferer) {
1.620     albertel 4854: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4855:             unless ($refuri) {
1.800     albertel 4856:                 foreach my $key (keys(%env)) {
                   4857: 		    if ($key=~/^httpref\..*\*/) {
                   4858: 			my $pattern=$key;
1.156     www      4859:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4860:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4861:                         $pattern=~s/\//\\\//g;
1.152     www      4862:                         if ($orguri=~/$pattern/) {
1.800     albertel 4863: 			    $refuri=$env{$key};
1.148     www      4864:                         }
                   4865:                     }
1.191     harris41 4866:                 }
1.148     www      4867:             }
1.232     www      4868: 
1.148     www      4869:          if ($refuri) { 
1.152     www      4870: 	  $refuri=&declutter($refuri);
1.232     www      4871:           my ($match,$cond)=&is_on_map($refuri);
                   4872:             if ($match) {
                   4873:               my $refstatecond=$cond;
1.620     albertel 4874:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4875:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4876:                   $thisallowed.=$1;
1.53      www      4877:                   $uri=$refuri;
                   4878:                   $statecond=$refstatecond;
1.52      www      4879:               }
                   4880:           }
1.148     www      4881:         }
1.29      www      4882:        }
1.52      www      4883:    }
1.29      www      4884: 
1.52      www      4885: #
1.103     harris41 4886: # Gathered now: all privileges that could apply, and condition number
1.52      www      4887: # 
                   4888: #
                   4889: # Full or no access?
                   4890: #
1.29      www      4891: 
1.52      www      4892:     if ($thisallowed=~/F/) {
                   4893: 	return 'F';
                   4894:     }
1.29      www      4895: 
1.52      www      4896:     unless ($thisallowed) {
                   4897:         return '';
                   4898:     }
1.29      www      4899: 
1.52      www      4900: # Restrictions exist, deal with them
                   4901: #
                   4902: #   C:according to course preferences
                   4903: #   R:according to resource settings
                   4904: #   L:unless locked
                   4905: #   X:according to user session state
                   4906: #
                   4907: 
                   4908: # Possibly locked functionality, check all courses
1.54      www      4909: # Locks might take effect only after 10 minutes cache expiration for other
                   4910: # courses, and 2 minutes for current course
1.52      www      4911: 
                   4912:     my $envkey;
                   4913:     if ($thisallowed=~/L/) {
1.620     albertel 4914:         foreach $envkey (keys %env) {
1.54      www      4915:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4916:                my $courseid=$2;
                   4917:                my $roleid=$1.'.'.$2;
1.92      www      4918:                $courseid=~s/^\///;
1.54      www      4919:                my $expiretime=600;
1.620     albertel 4920:                if ($env{'request.role'} eq $roleid) {
1.54      www      4921: 		  $expiretime=120;
                   4922:                }
                   4923: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4924:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4925:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4926: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4927:                }
1.620     albertel 4928:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4929:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4930: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4931:                        &log($env{'user.domain'},$env{'user.name'},
                   4932:                             $env{'user.home'},
1.57      www      4933:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4934:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4935:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4936: 		       return '';
                   4937:                    }
                   4938:                }
1.620     albertel 4939:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4940:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4941: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4942:                        &log($env{'user.domain'},$env{'user.name'},
                   4943:                             $env{'user.home'},
1.57      www      4944:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4945:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4946:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4947: 		       return '';
                   4948:                    }
                   4949:                }
                   4950: 	   }
1.29      www      4951:        }
1.52      www      4952:     }
                   4953:    
                   4954: #
                   4955: # Rest of the restrictions depend on selected course
                   4956: #
                   4957: 
1.620     albertel 4958:     unless ($env{'request.course.id'}) {
1.766     albertel 4959: 	if ($thisallowed eq 'A') {
                   4960: 	    return 'A';
1.814     raeburn  4961:         } elsif ($thisallowed eq 'B') {
                   4962:             return 'B';
1.766     albertel 4963: 	} else {
                   4964: 	    return '1';
                   4965: 	}
1.52      www      4966:     }
1.29      www      4967: 
1.52      www      4968: #
                   4969: # Now user is definitely in a course
                   4970: #
1.53      www      4971: 
                   4972: 
                   4973: # Course preferences
                   4974: 
                   4975:    if ($thisallowed=~/C/) {
1.620     albertel 4976:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4977:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4978:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4979: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4980: 	   if ($priv ne 'pch') { 
                   4981: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4982: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4983: 			$env{'request.course.id'});
                   4984: 	   }
1.237     www      4985:            return '';
                   4986:        }
                   4987: 
1.620     albertel 4988:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4989: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4990: 	   if ($priv ne 'pch') { 
                   4991: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4992: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4993: 			$env{'request.course.id'});
                   4994: 	   }
1.54      www      4995:            return '';
                   4996:        }
1.53      www      4997:    }
                   4998: 
                   4999: # Resource preferences
                   5000: 
                   5001:    if ($thisallowed=~/R/) {
1.620     albertel 5002:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5003:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5004: 	   if ($priv ne 'pch') { 
                   5005: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5006: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5007: 	   }
                   5008: 	   return '';
1.54      www      5009:        }
1.53      www      5010:    }
1.30      www      5011: 
1.246     www      5012: # Restricted by state or randomout?
1.30      www      5013: 
1.52      www      5014:    if ($thisallowed=~/X/) {
1.620     albertel 5015:       if ($env{'acc.randomout'}) {
1.579     albertel 5016: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5017:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5018:             return ''; 
                   5019:          }
1.247     www      5020:       }
                   5021:       if (&condval($statecond)) {
1.52      www      5022: 	 return '2';
                   5023:       } else {
                   5024:          return '';
                   5025:       }
                   5026:    }
1.30      www      5027: 
1.766     albertel 5028:     if ($thisallowed eq 'A') {
                   5029: 	return 'A';
1.814     raeburn  5030:     } elsif ($thisallowed eq 'B') {
                   5031:         return 'B';
1.766     albertel 5032:     }
1.52      www      5033:    return 'F';
1.232     www      5034: }
                   5035: 
1.710     albertel 5036: sub split_uri_for_cond {
                   5037:     my $uri=&deversion(&declutter(shift));
                   5038:     my @uriparts=split(/\//,$uri);
                   5039:     my $filename=pop(@uriparts);
                   5040:     my $pathname=join('/',@uriparts);
                   5041:     return ($pathname,$filename);
                   5042: }
1.232     www      5043: # --------------------------------------------------- Is a resource on the map?
                   5044: 
                   5045: sub is_on_map {
1.710     albertel 5046:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5047:     #Trying to find the conditional for the file
1.620     albertel 5048:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5049: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5050:     if ($match) {
1.289     bowersj2 5051: 	return (1,$1);
                   5052:     } else {
1.434     www      5053: 	return (0,0);
1.289     bowersj2 5054:     }
1.12      www      5055: }
                   5056: 
1.427     www      5057: # --------------------------------------------------------- Get symb from alias
                   5058: 
                   5059: sub get_symb_from_alias {
                   5060:     my $symb=shift;
                   5061:     my ($map,$resid,$url)=&decode_symb($symb);
                   5062: # Already is a symb
                   5063:     if ($url) { return $symb; }
                   5064: # Must be an alias
                   5065:     my $aliassymb='';
                   5066:     my %bighash;
1.620     albertel 5067:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5068:                             &GDBM_READER(),0640)) {
                   5069:         my $rid=$bighash{'mapalias_'.$symb};
                   5070: 	if ($rid) {
                   5071: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5072: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5073: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5074: 	}
                   5075:         untie %bighash;
                   5076:     }
                   5077:     return $aliassymb;
                   5078: }
                   5079: 
1.12      www      5080: # ----------------------------------------------------------------- Define Role
                   5081: 
                   5082: sub definerole {
                   5083:   if (allowed('mcr','/')) {
                   5084:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5085:     foreach my $role (split(':',$sysrole)) {
                   5086: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5087:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5088:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5089: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5090:                return "refused:s:$crole&$cqual"; 
                   5091:             }
                   5092:         }
1.191     harris41 5093:     }
1.800     albertel 5094:     foreach my $role (split(':',$domrole)) {
                   5095: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5096:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5097:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5098: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5099:                return "refused:d:$crole&$cqual"; 
                   5100:             }
                   5101:         }
1.191     harris41 5102:     }
1.800     albertel 5103:     foreach my $role (split(':',$courole)) {
                   5104: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5105:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5106:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5107: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5108:                return "refused:c:$crole&$cqual"; 
                   5109:             }
                   5110:         }
1.191     harris41 5111:     }
1.620     albertel 5112:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5113:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5114: 	        "rolesdef_$rolename=".
                   5115:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5116:     return reply($command,$env{'user.home'});
1.12      www      5117:   } else {
                   5118:     return 'refused';
                   5119:   }
1.105     harris41 5120: }
                   5121: 
                   5122: # ---------------- Make a metadata query against the network of library servers
                   5123: 
                   5124: sub metadata_query {
1.244     matthew  5125:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5126:     my %rhash;
1.845     albertel 5127:     my %libserv = &all_library();
1.244     matthew  5128:     my @server_list = (defined($server_array) ? @$server_array
                   5129:                                               : keys(%libserv) );
                   5130:     for my $server (@server_list) {
1.118     harris41 5131: 	unless ($custom or $customshow) {
                   5132: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5133: 	    $rhash{$server}=$reply;
                   5134: 	}
                   5135: 	else {
                   5136: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5137: 			     &escape($custom).':'.&escape($customshow),
                   5138: 			     $server);
                   5139: 	    $rhash{$server}=$reply;
                   5140: 	}
1.112     harris41 5141:     }
1.118     harris41 5142:     return \%rhash;
1.240     www      5143: }
                   5144: 
                   5145: # ----------------------------------------- Send log queries and wait for reply
                   5146: 
                   5147: sub log_query {
                   5148:     my ($uname,$udom,$query,%filters)=@_;
                   5149:     my $uhome=&homeserver($uname,$udom);
                   5150:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5151:     my $uhost=&hostname($uhome);
1.800     albertel 5152:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5153:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5154:                        $uhome);
1.479     albertel 5155:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5156:     return get_query_reply($queryid);
                   5157: }
                   5158: 
1.818     raeburn  5159: # -------------------------- Update MySQL table for portfolio file
                   5160: 
                   5161: sub update_portfolio_table {
1.821     raeburn  5162:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5163:     if ($group ne '') {
                   5164:         $file_name =~s /^\Q$group\E//;
                   5165:     }
1.818     raeburn  5166:     my $homeserver = &homeserver($uname,$udom);
                   5167:     my $queryid=
1.821     raeburn  5168:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5169:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5170:     my $reply = &get_query_reply($queryid);
                   5171:     return $reply;
                   5172: }
                   5173: 
1.899     raeburn  5174: # -------------------------- Update MySQL allusers table
                   5175: 
                   5176: sub update_allusers_table {
                   5177:     my ($uname,$udom,$names) = @_;
                   5178:     my $homeserver = &homeserver($uname,$udom);
                   5179:     my $queryid=
                   5180:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5181:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5182:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5183:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5184:                'generation='.&escape($names->{'generation'}).'%%'.
                   5185:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5186:                'id='.&escape($names->{'id'}),$homeserver);
                   5187:     my $reply = &get_query_reply($queryid);
                   5188:     return $reply;
                   5189: }
                   5190: 
1.508     raeburn  5191: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5192: 
                   5193: sub fetch_enrollment_query {
1.511     raeburn  5194:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5195:     my $homeserver;
1.547     raeburn  5196:     my $maxtries = 1;
1.508     raeburn  5197:     if ($context eq 'automated') {
                   5198:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5199:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5200:     } else {
                   5201:         $homeserver = &homeserver($cnum,$dom);
                   5202:     }
1.838     albertel 5203:     my $host=&hostname($homeserver);
1.506     raeburn  5204:     my $cmd = '';
1.800     albertel 5205:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5206:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5207:     }
                   5208:     $cmd =~ s/%%$//;
                   5209:     $cmd = &escape($cmd);
                   5210:     my $query = 'fetchenrollment';
1.620     albertel 5211:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5212:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5213:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5214:         return 'error: '.$queryid;
                   5215:     }
1.506     raeburn  5216:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5217:     my $tries = 1;
                   5218:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5219:         $reply = &get_query_reply($queryid);
                   5220:         $tries ++;
                   5221:     }
1.526     raeburn  5222:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5223:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5224:     } else {
1.901     albertel 5225:         my @responses = split(/:/,$reply);
1.515     raeburn  5226:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5227:             foreach my $line (@responses) {
                   5228:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5229:                 $$replyref{$key} = $value;
                   5230:             }
                   5231:         } else {
1.506     raeburn  5232:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5233:             foreach my $line (@responses) {
                   5234:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5235:                 $$replyref{$key} = $value;
                   5236:                 if ($value > 0) {
1.800     albertel 5237:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5238:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5239:                         my $destname = $pathname.'/'.$filename;
                   5240:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5241:                         if ($xml_classlist =~ /^error/) {
                   5242:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5243:                         } else {
1.506     raeburn  5244:                             if ( open(FILE,">$destname") ) {
                   5245:                                 print FILE &unescape($xml_classlist);
                   5246:                                 close(FILE);
1.526     raeburn  5247:                             } else {
                   5248:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5249:                             }
                   5250:                         }
                   5251:                     }
                   5252:                 }
                   5253:             }
                   5254:         }
                   5255:         return 'ok';
                   5256:     }
                   5257:     return 'error';
                   5258: }
                   5259: 
1.242     www      5260: sub get_query_reply {
                   5261:     my $queryid=shift;
1.240     www      5262:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5263:     my $reply='';
                   5264:     for (1..100) {
                   5265: 	sleep 2;
                   5266:         if (-e $replyfile.'.end') {
1.448     albertel 5267: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5268: 		$reply = join('',<$fh>);
                   5269: 		close($fh);
1.240     www      5270: 	   } else { return 'error: reply_file_error'; }
1.242     www      5271:            return &unescape($reply);
                   5272: 	}
1.240     www      5273:     }
1.242     www      5274:     return 'timeout:'.$queryid;
1.240     www      5275: }
                   5276: 
                   5277: sub courselog_query {
1.241     www      5278: #
                   5279: # possible filters:
                   5280: # url: url or symb
                   5281: # username
                   5282: # domain
                   5283: # action: view, submit, grade
                   5284: # start: timestamp
                   5285: # end: timestamp
                   5286: #
1.240     www      5287:     my (%filters)=@_;
1.620     albertel 5288:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5289:     if ($filters{'url'}) {
                   5290: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5291:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5292:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5293:     }
1.620     albertel 5294:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5295:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5296:     return &log_query($cname,$cdom,'courselog',%filters);
                   5297: }
                   5298: 
                   5299: sub userlog_query {
1.858     raeburn  5300: #
                   5301: # possible filters:
                   5302: # action: log check role
                   5303: # start: timestamp
                   5304: # end: timestamp
                   5305: #
1.240     www      5306:     my ($uname,$udom,%filters)=@_;
                   5307:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5308: }
                   5309: 
1.506     raeburn  5310: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5311: 
                   5312: sub auto_run {
1.508     raeburn  5313:     my ($cnum,$cdom) = @_;
1.876     raeburn  5314:     my $response = 0;
                   5315:     my $settings;
                   5316:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5317:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5318:         $settings = $domconfig{'autoenroll'};
                   5319:         if ($settings->{'run'} eq '1') {
                   5320:             $response = 1;
                   5321:         }
                   5322:     } else {
1.934     raeburn  5323:         my $homeserver;
                   5324:         if (&is_course($cdom,$cnum)) {
                   5325:             $homeserver = &homeserver($cnum,$cdom);
                   5326:         } else {
                   5327:             $homeserver = &domain($cdom,'primary');
                   5328:         }
                   5329:         if ($homeserver ne 'no_host') {
                   5330:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5331:         }
1.876     raeburn  5332:     }
1.506     raeburn  5333:     return $response;
                   5334: }
1.776     albertel 5335: 
1.506     raeburn  5336: sub auto_get_sections {
1.508     raeburn  5337:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5338:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5339:     my @secs = ();
1.511     raeburn  5340:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5341:     unless ($response eq 'refused') {
1.901     albertel 5342:         @secs = split(/:/,$response);
1.506     raeburn  5343:     }
                   5344:     return @secs;
                   5345: }
1.776     albertel 5346: 
1.506     raeburn  5347: sub auto_new_course {
1.508     raeburn  5348:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5349:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5350:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5351:     return $response;
                   5352: }
1.776     albertel 5353: 
1.506     raeburn  5354: sub auto_validate_courseID {
1.508     raeburn  5355:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5356:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5357:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5358:     return $response;
                   5359: }
1.776     albertel 5360: 
1.506     raeburn  5361: sub auto_create_password {
1.873     raeburn  5362:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5363:     my ($homeserver,$response);
1.506     raeburn  5364:     my $create_passwd = 0;
                   5365:     my $authchk = '';
1.873     raeburn  5366:     if ($udom =~ /^$match_domain$/) {
                   5367:         $homeserver = &domain($udom,'primary');
                   5368:     }
                   5369:     if ($homeserver eq '') {
                   5370:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5371:             $homeserver = &homeserver($cnum,$cdom);
                   5372:         }
                   5373:     }
                   5374:     if ($homeserver eq '') {
                   5375:         $authchk = 'nodomain';
1.506     raeburn  5376:     } else {
1.873     raeburn  5377:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5378:         if ($response eq 'refused') {
                   5379:             $authchk = 'refused';
                   5380:         } else {
1.901     albertel 5381:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5382:         }
1.506     raeburn  5383:     }
                   5384:     return ($authparam,$create_passwd,$authchk);
                   5385: }
                   5386: 
1.706     raeburn  5387: sub auto_photo_permission {
                   5388:     my ($cnum,$cdom,$students) = @_;
                   5389:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5390:     my ($outcome,$perm_reqd,$conditions) = 
                   5391: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5392:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5393: 	return (undef,undef);
                   5394:     }
1.706     raeburn  5395:     return ($outcome,$perm_reqd,$conditions);
                   5396: }
                   5397: 
                   5398: sub auto_checkphotos {
                   5399:     my ($uname,$udom,$pid) = @_;
                   5400:     my $homeserver = &homeserver($uname,$udom);
                   5401:     my ($result,$resulttype);
                   5402:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5403: 				   &escape($uname).':'.&escape($pid),
                   5404: 				   $homeserver));
1.709     albertel 5405:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5406: 	return (undef,undef);
                   5407:     }
1.706     raeburn  5408:     if ($outcome) {
                   5409:         ($result,$resulttype) = split(/:/,$outcome);
                   5410:     } 
                   5411:     return ($result,$resulttype);
                   5412: }
                   5413: 
                   5414: sub auto_photochoice {
                   5415:     my ($cnum,$cdom) = @_;
                   5416:     my $homeserver = &homeserver($cnum,$cdom);
                   5417:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5418: 						       &escape($cdom),
                   5419: 						       $homeserver)));
1.709     albertel 5420:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5421: 	return (undef,undef);
                   5422:     }
1.706     raeburn  5423:     return ($update,$comment);
                   5424: }
                   5425: 
                   5426: sub auto_photoupdate {
                   5427:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5428:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5429:     my $host=&hostname($homeserver);
1.706     raeburn  5430:     my $cmd = '';
                   5431:     my $maxtries = 1;
1.800     albertel 5432:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5433:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5434:     }
                   5435:     $cmd =~ s/%%$//;
                   5436:     $cmd = &escape($cmd);
                   5437:     my $query = 'institutionalphotos';
                   5438:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5439:     unless ($queryid=~/^\Q$host\E\_/) {
                   5440:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5441:         return 'error: '.$queryid;
                   5442:     }
                   5443:     my $reply = &get_query_reply($queryid);
                   5444:     my $tries = 1;
                   5445:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5446:         $reply = &get_query_reply($queryid);
                   5447:         $tries ++;
                   5448:     }
                   5449:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5450:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5451:     } else {
                   5452:         my @responses = split(/:/,$reply);
                   5453:         my $outcome = shift(@responses); 
                   5454:         foreach my $item (@responses) {
                   5455:             my ($key,$value) = split(/=/,$item);
                   5456:             $$photo{$key} = $value;
                   5457:         }
                   5458:         return $outcome;
                   5459:     }
                   5460:     return 'error';
                   5461: }
                   5462: 
1.521     raeburn  5463: sub auto_instcode_format {
1.793     albertel 5464:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5465: 	$cat_order) = @_;
1.521     raeburn  5466:     my $courses = '';
1.772     raeburn  5467:     my @homeservers;
1.521     raeburn  5468:     if ($caller eq 'global') {
1.841     albertel 5469: 	my %servers = &get_servers($codedom,'library');
                   5470: 	foreach my $tryserver (keys(%servers)) {
                   5471: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5472: 		push(@homeservers,$tryserver);
                   5473: 	    }
1.584     raeburn  5474:         }
1.521     raeburn  5475:     } else {
1.772     raeburn  5476:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5477:     }
1.793     albertel 5478:     foreach my $code (keys(%{$instcodes})) {
                   5479:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5480:     }
                   5481:     chop($courses);
1.772     raeburn  5482:     my $ok_response = 0;
                   5483:     my $response;
                   5484:     while (@homeservers > 0 && $ok_response == 0) {
                   5485:         my $server = shift(@homeservers); 
                   5486:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5487:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5488:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5489: 		split(/:/,$response);
1.772     raeburn  5490:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5491:             push(@{$codetitles},&str2array($codetitles_str));
                   5492:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5493:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5494:             $ok_response = 1;
                   5495:         }
                   5496:     }
                   5497:     if ($ok_response) {
1.521     raeburn  5498:         return 'ok';
1.772     raeburn  5499:     } else {
                   5500:         return $response;
1.521     raeburn  5501:     }
                   5502: }
                   5503: 
1.792     raeburn  5504: sub auto_instcode_defaults {
                   5505:     my ($domain,$returnhash,$code_order) = @_;
                   5506:     my @homeservers;
1.841     albertel 5507: 
                   5508:     my %servers = &get_servers($domain,'library');
                   5509:     foreach my $tryserver (keys(%servers)) {
                   5510: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5511: 	    push(@homeservers,$tryserver);
                   5512: 	}
1.792     raeburn  5513:     }
1.841     albertel 5514: 
1.792     raeburn  5515:     my $response;
1.841     albertel 5516:     foreach my $server (@homeservers) {
1.792     raeburn  5517:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5518:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5519: 	
                   5520: 	foreach my $pair (split(/\&/,$response)) {
                   5521: 	    my ($name,$value)=split(/\=/,$pair);
                   5522: 	    if ($name eq 'code_order') {
                   5523: 		@{$code_order} = split(/\&/,&unescape($value));
                   5524: 	    } else {
                   5525: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5526: 	    }
                   5527: 	}
                   5528: 	return 'ok';
1.792     raeburn  5529:     }
1.841     albertel 5530: 
                   5531:     return $response;
1.792     raeburn  5532: } 
                   5533: 
1.777     albertel 5534: sub auto_validate_class_sec {
1.918     raeburn  5535:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5536:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5537:     my $ownerlist;
                   5538:     if (ref($owners) eq 'ARRAY') {
                   5539:         $ownerlist = join(',',@{$owners});
                   5540:     } else {
                   5541:         $ownerlist = $owners;
                   5542:     }
1.773     raeburn  5543:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5544:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5545:     return $response;
                   5546: }
                   5547: 
1.679     raeburn  5548: # ------------------------------------------------------- Course Group routines
                   5549: 
                   5550: sub get_coursegroups {
1.809     raeburn  5551:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5552:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5553: }
                   5554: 
1.679     raeburn  5555: sub modify_coursegroup {
                   5556:     my ($cdom,$cnum,$groupsettings) = @_;
                   5557:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5558: }
                   5559: 
1.809     raeburn  5560: sub toggle_coursegroup_status {
                   5561:     my ($cdom,$cnum,$group,$action) = @_;
                   5562:     my ($from_namespace,$to_namespace);
                   5563:     if ($action eq 'delete') {
                   5564:         $from_namespace = 'coursegroups';
                   5565:         $to_namespace = 'deleted_groups';
                   5566:     } else {
                   5567:         $from_namespace = 'deleted_groups';
                   5568:         $to_namespace = 'coursegroups';
                   5569:     }
                   5570:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5571:     if (my $tmp = &error(%curr_group)) {
                   5572:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5573:         return ('read error',$tmp);
                   5574:     } else {
                   5575:         my %savedsettings = %curr_group; 
1.809     raeburn  5576:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5577:         my $deloutcome;
                   5578:         if ($result eq 'ok') {
1.809     raeburn  5579:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5580:         } else {
                   5581:             return ('write error',$result);
                   5582:         }
                   5583:         if ($deloutcome eq 'ok') {
                   5584:             return 'ok';
                   5585:         } else {
                   5586:             return ('delete error',$deloutcome);
                   5587:         }
                   5588:     }
                   5589: }
                   5590: 
1.679     raeburn  5591: sub modify_group_roles {
1.957     raeburn  5592:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5593:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5594:     my $role = 'gr/'.&escape($userprivs);
                   5595:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5596:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5597:     if ($result eq 'ok') {
                   5598:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5599:     }
1.679     raeburn  5600:     return $result;
                   5601: }
                   5602: 
                   5603: sub modify_coursegroup_membership {
                   5604:     my ($cdom,$cnum,$membership) = @_;
                   5605:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5606:     return $result;
                   5607: }
                   5608: 
1.682     raeburn  5609: sub get_active_groups {
                   5610:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5611:     my $now = time;
                   5612:     my %groups = ();
                   5613:     foreach my $key (keys(%env)) {
1.811     albertel 5614:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5615:             my ($start,$end) = split(/\./,$env{$key});
                   5616:             if (($end!=0) && ($end<$now)) { next; }
                   5617:             if (($start!=0) && ($start>$now)) { next; }
                   5618:             if ($1 eq $cdom && $2 eq $cnum) {
                   5619:                 $groups{$3} = $env{$key} ;
                   5620:             }
                   5621:         }
                   5622:     }
                   5623:     return %groups;
                   5624: }
                   5625: 
1.683     raeburn  5626: sub get_group_membership {
                   5627:     my ($cdom,$cnum,$group) = @_;
                   5628:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5629: }
                   5630: 
                   5631: sub get_users_groups {
                   5632:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5633:     my @usersgroups;
1.683     raeburn  5634:     my $cachetime=1800;
                   5635: 
                   5636:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5637:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5638:     if (defined($cached)) {
1.734     albertel 5639:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5640:     } else {  
                   5641:         $grouplist = '';
1.816     raeburn  5642:         my $courseurl = &courseid_to_courseurl($courseid);
                   5643:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5644:         my $access_end = $env{'course.'.$courseid.
                   5645:                               '.default_enrollment_end_date'};
                   5646:         my $now = time;
                   5647:         foreach my $key (keys(%roleshash)) {
                   5648:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5649:                 my $group = $1;
                   5650:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5651:                     my $start = $2;
                   5652:                     my $end = $1;
                   5653:                     if ($start == -1) { next; } # deleted from group
                   5654:                     if (($start!=0) && ($start>$now)) { next; }
                   5655:                     if (($end!=0) && ($end<$now)) {
                   5656:                         if ($access_end && $access_end < $now) {
                   5657:                             if ($access_end - $end < 86400) {
                   5658:                                 push(@usersgroups,$group);
1.733     raeburn  5659:                             }
                   5660:                         }
1.817     raeburn  5661:                         next;
1.733     raeburn  5662:                     }
1.817     raeburn  5663:                     push(@usersgroups,$group);
1.683     raeburn  5664:                 }
                   5665:             }
                   5666:         }
1.817     raeburn  5667:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5668:         $grouplist = join(':',@usersgroups);
                   5669:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5670:     }
1.733     raeburn  5671:     return @usersgroups;
1.683     raeburn  5672: }
                   5673: 
                   5674: sub devalidate_getgroups_cache {
                   5675:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5676:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5677: 
1.683     raeburn  5678:     my $hashid="$udom:$uname:$courseid";
                   5679:     &devalidate_cache_new('getgroups',$hashid);
                   5680: }
                   5681: 
1.12      www      5682: # ------------------------------------------------------------------ Plain Text
                   5683: 
                   5684: sub plaintext {
1.988     raeburn  5685:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 5686:     if ($short =~ /^cr/) {
                   5687: 	return (split('/',$short))[-1];
                   5688:     }
1.742     raeburn  5689:     if (!defined($cid)) {
                   5690:         $cid = $env{'request.course.id'};
                   5691:     }
1.988     raeburn  5692:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
                   5693:         unless ($forcedefault) {
                   5694:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   5695:             &Apache::lonlocal::mt_escape(\$roletext);
                   5696:             return &Apache::lonlocal::mt($roletext);
                   5697:         }
1.742     raeburn  5698:     }
                   5699:     my %rolenames = (
                   5700:                       Course => 'std',
                   5701:                       Group => 'alt1',
                   5702:                     );
                   5703:     if (defined($type) && 
                   5704:          defined($rolenames{$type}) && 
                   5705:          defined($prp{$short}{$rolenames{$type}})) {
                   5706:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5707:     } else {
                   5708:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5709:     }
1.12      www      5710: }
                   5711: 
                   5712: # ----------------------------------------------------------------- Assign Role
                   5713: 
                   5714: sub assignrole {
1.957     raeburn  5715:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5716:         $context)=@_;
1.21      www      5717:     my $mrole;
                   5718:     if ($role =~ /^cr\//) {
1.393     www      5719:         my $cwosec=$url;
1.811     albertel 5720:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5721: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5722:            &logthis('Refused custom assignrole: '.
                   5723:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5724: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5725:            return 'refused'; 
                   5726:         }
1.21      www      5727:         $mrole='cr';
1.678     raeburn  5728:     } elsif ($role =~ /^gr\//) {
                   5729:         my $cwogrp=$url;
1.811     albertel 5730:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5731:         unless (&allowed('mdg',$cwogrp)) {
                   5732:             &logthis('Refused group assignrole: '.
                   5733:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5734:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5735:             return 'refused';
                   5736:         }
                   5737:         $mrole='gr';
1.21      www      5738:     } else {
1.82      www      5739:         my $cwosec=$url;
1.811     albertel 5740:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5741:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5742:             my $refused;
                   5743:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5744:                 if (!(&allowed('c'.$role,$url))) {
                   5745:                     $refused = 1;
                   5746:                 }
                   5747:             } else {
                   5748:                 $refused = 1;
                   5749:             }
1.947     raeburn  5750:             if ($refused) {
                   5751:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5752:                     $refused = '';
                   5753:                 } else {
                   5754:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5755:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5756: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5757:                     return 'refused';
                   5758:                 }
1.932     raeburn  5759:             }
1.104     www      5760:         }
1.21      www      5761:         $mrole=$role;
                   5762:     }
1.620     albertel 5763:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5764:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5765:     if ($end) { $command.='_'.$end; }
1.21      www      5766:     if ($start) {
                   5767: 	if ($end) { 
1.81      www      5768:            $command.='_'.$start; 
1.21      www      5769:         } else {
1.81      www      5770:            $command.='_0_'.$start;
1.21      www      5771:         }
                   5772:     }
1.739     raeburn  5773:     my $origstart = $start;
                   5774:     my $origend = $end;
1.957     raeburn  5775:     my $delflag;
1.357     www      5776: # actually delete
                   5777:     if ($deleteflag) {
1.373     www      5778: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5779: # modify command to delete the role
1.620     albertel 5780:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5781:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5782: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5783: # set start and finish to negative values for userrolelog
                   5784:            $start=-1;
                   5785:            $end=-1;
1.957     raeburn  5786:            $delflag = 1;
1.357     www      5787:         }
                   5788:     }
                   5789: # send command
1.349     www      5790:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5791: # log new user role if status is ok
1.349     www      5792:     if ($answer eq 'ok') {
1.663     raeburn  5793: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5794: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5795:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5796:         unless ($role =~ /^gr/) {
                   5797:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5798:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5799:         }
1.349     www      5800:     }
                   5801:     return $answer;
1.169     harris41 5802: }
                   5803: 
                   5804: # -------------------------------------------------- Modify user authentication
1.197     www      5805: # Overrides without validation
                   5806: 
1.169     harris41 5807: sub modifyuserauth {
                   5808:     my ($udom,$uname,$umode,$upass)=@_;
                   5809:     my $uhome=&homeserver($uname,$udom);
1.197     www      5810:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5811:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5812:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5813:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5814:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5815: 		     &escape($upass),$uhome);
1.620     albertel 5816:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5817:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5818:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5819:     &log($udom,,$uname,$uhome,
1.620     albertel 5820:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5821:                                      $env{'user.name'}.', '.$umode.
1.197     www      5822:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5823:     unless ($reply eq 'ok') {
1.197     www      5824:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5825: 	return 'error: '.$reply;
                   5826:     }   
1.170     harris41 5827:     return 'ok';
1.80      www      5828: }
                   5829: 
1.81      www      5830: # --------------------------------------------------------------- Modify a user
1.80      www      5831: 
1.81      www      5832: sub modifyuser {
1.206     matthew  5833:     my ($udom,    $uname, $uid,
                   5834:         $umode,   $upass, $first,
                   5835:         $middle,  $last,  $gene,
1.963     raeburn  5836:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5837:     $udom= &LONCAPA::clean_domain($udom);
                   5838:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5839:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5840:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5841: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5842:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5843:                                      ' desiredhome not specified'). 
1.620     albertel 5844:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5845:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5846:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5847: # ----------------------------------------------------------------- Create User
1.406     albertel 5848:     if (($uhome eq 'no_host') && 
                   5849: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5850:         my $unhome='';
1.844     albertel 5851:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5852:             $unhome = $desiredhome;
1.620     albertel 5853: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5854: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5855:         } else { # load balancing routine for determining $unhome
1.81      www      5856:             my $loadm=10000000;
1.841     albertel 5857: 	    my %servers = &get_servers($udom,'library');
                   5858: 	    foreach my $tryserver (keys(%servers)) {
                   5859: 		my $answer=reply('load',$tryserver);
                   5860: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5861: 		    $loadm=$answer;
                   5862: 		    $unhome=$tryserver;
                   5863: 		}
1.80      www      5864: 	    }
                   5865:         }
                   5866:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5867: 	    return 'error: unable to find a home server for '.$uname.
                   5868:                    ' in domain '.$udom;
1.80      www      5869:         }
                   5870:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5871:                          &escape($upass),$unhome);
                   5872: 	unless ($reply eq 'ok') {
                   5873:             return 'error: '.$reply;
                   5874:         }   
1.230     stredwic 5875:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5876:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5877: 	    return 'error: unable verify users home machine.';
1.80      www      5878:         }
1.209     matthew  5879:     }   # End of creation of new user
1.80      www      5880: # ---------------------------------------------------------------------- Add ID
                   5881:     if ($uid) {
                   5882:        $uid=~tr/A-Z/a-z/;
                   5883:        my %uidhash=&idrget($udom,$uname);
1.196     www      5884:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5885:          && (!$forceid)) {
1.80      www      5886: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5887: 	      return 'error: user id "'.$uid.'" does not match '.
                   5888:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5889:           }
                   5890:        } else {
                   5891: 	  &idput($udom,($uname => $uid));
                   5892:        }
                   5893:     }
                   5894: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5895:     my @tmp=&get('environment',
1.899     raeburn  5896: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5897:                     'permanentemail','inststatus'],
1.134     albertel 5898: 		   $udom,$uname);
1.313     matthew  5899:     my %names;
                   5900:     if ($tmp[0] =~ m/^error:.*/) { 
                   5901:         %names=(); 
                   5902:     } else {
                   5903:         %names = @tmp;
                   5904:     }
1.388     www      5905: #
                   5906: # Make sure to not trash student environment if instructor does not bother
                   5907: # to supply name and email information
                   5908: #
                   5909:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5910:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5911:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5912:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5913:     if ($email) {
                   5914:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5915:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5916:     }
1.899     raeburn  5917:     if ($uid) { $names{'id'}  = $uid; }
1.989   ! raeburn  5918:     if (defined($inststatus)) {
        !          5919:         $names{'inststatus'} = '';
        !          5920:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
        !          5921:         if (ref($usertypes) eq 'HASH') {
        !          5922:             my @okstatuses; 
        !          5923:             foreach my $item (split(/:/,$inststatus)) {
        !          5924:                 if (defined($usertypes->{$item})) {
        !          5925:                     push(@okstatuses,$item);  
        !          5926:                 }
        !          5927:             }
        !          5928:             if (@okstatuses) {
        !          5929:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
        !          5930:             }
        !          5931:         }
        !          5932:     }
1.134     albertel 5933:     my $reply = &put('environment', \%names, $udom,$uname);
                   5934:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5935:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5936:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5937:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5938:                  $umode.', '.$first.', '.$middle.', '.
                   5939: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5940:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5941:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5942:     } else {
                   5943:         $logmsg .= ' during self creation';
                   5944:     }
                   5945:     &logthis($logmsg);
1.134     albertel 5946:     return 'ok';
1.80      www      5947: }
                   5948: 
1.81      www      5949: # -------------------------------------------------------------- Modify student
1.80      www      5950: 
1.81      www      5951: sub modifystudent {
                   5952:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5953:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5954:         $selfenroll,$context)=@_;
1.455     albertel 5955:     if (!$cid) {
1.620     albertel 5956: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5957: 	    return 'not_in_class';
                   5958: 	}
1.80      www      5959:     }
                   5960: # --------------------------------------------------------------- Make the user
1.81      www      5961:     my $reply=&modifyuser
1.209     matthew  5962: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5963:          $desiredhome,$email);
1.80      www      5964:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5965:     # This will cause &modify_student_enrollment to get the uid from the
                   5966:     # students environment
                   5967:     $uid = undef if (!$forceid);
1.455     albertel 5968:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5969: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5970:     return $reply;
                   5971: }
                   5972: 
                   5973: sub modify_student_enrollment {
1.957     raeburn  5974:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5975:     my ($cdom,$cnum,$chome);
                   5976:     if (!$cid) {
1.620     albertel 5977: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5978: 	    return 'not_in_class';
                   5979: 	}
1.620     albertel 5980: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5981: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5982:     } else {
                   5983: 	($cdom,$cnum)=split(/_/,$cid);
                   5984:     }
1.620     albertel 5985:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5986:     if (!$chome) {
1.457     raeburn  5987: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5988:     }
1.455     albertel 5989:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5990:     # Make sure the user exists
1.81      www      5991:     my $uhome=&homeserver($uname,$udom);
                   5992:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5993: 	return 'error: no such user';
                   5994:     }
1.297     matthew  5995:     # Get student data if we were not given enough information
                   5996:     if (!defined($first)  || $first  eq '' || 
                   5997:         !defined($last)   || $last   eq '' || 
                   5998:         !defined($uid)    || $uid    eq '' || 
                   5999:         !defined($middle) || $middle eq '' || 
                   6000:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6001:         # They did not supply us with enough data to enroll the student, so
                   6002:         # we need to pick up more information.
1.297     matthew  6003:         my %tmp = &get('environment',
1.294     matthew  6004:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6005:                        ,$udom,$uname);
                   6006: 
1.800     albertel 6007:         #foreach my $key (keys(%tmp)) {
                   6008:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6009:         #}
1.294     matthew  6010:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6011:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6012:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6013:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6014:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6015:     }
1.556     albertel 6016:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6017:     my $reply=cput('classlist',
                   6018: 		   {"$uname:$udom" => 
1.515     raeburn  6019: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6020: 		   $cdom,$cnum);
1.81      www      6021:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6022: 	return 'error: '.$reply;
1.652     albertel 6023:     } else {
                   6024: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6025:     }
1.297     matthew  6026:     # Add student role to user
1.83      www      6027:     my $uurl='/'.$cid;
1.81      www      6028:     $uurl=~s/\_/\//g;
                   6029:     if ($usec) {
                   6030: 	$uurl.='/'.$usec;
                   6031:     }
1.957     raeburn  6032:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6033: }
                   6034: 
1.556     albertel 6035: sub format_name {
                   6036:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6037:     my $name;
                   6038:     if ($first ne 'lastname') {
                   6039: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6040:     } else {
                   6041: 	if ($lastname=~/\S/) {
                   6042: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6043: 	    $name=~s/\s+,/,/;
                   6044: 	} else {
                   6045: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6046: 	}
                   6047:     }
                   6048:     $name=~s/^\s+//;
                   6049:     $name=~s/\s+$//;
                   6050:     $name=~s/\s+/ /g;
                   6051:     return $name;
                   6052: }
                   6053: 
1.84      www      6054: # ------------------------------------------------- Write to course preferences
                   6055: 
                   6056: sub writecoursepref {
                   6057:     my ($courseid,%prefs)=@_;
                   6058:     $courseid=~s/^\///;
                   6059:     $courseid=~s/\_/\//g;
                   6060:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6061:     my $chome=homeserver($cnum,$cdomain);
                   6062:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6063: 	return 'error: no such course';
                   6064:     }
                   6065:     my $cstring='';
1.800     albertel 6066:     foreach my $pref (keys(%prefs)) {
                   6067: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6068:     }
1.84      www      6069:     $cstring=~s/\&$//;
                   6070:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6071: }
                   6072: 
                   6073: # ---------------------------------------------------------- Make/modify course
                   6074: 
                   6075: sub createcourse {
1.741     raeburn  6076:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6077:         $course_owner,$crstype)=@_;
1.84      www      6078:     $url=&declutter($url);
                   6079:     my $cid='';
1.264     matthew  6080:     unless (&allowed('ccc',$udom)) {
1.84      www      6081:         return 'refused';
                   6082:     }
                   6083: # ------------------------------------------------------------------- Create ID
1.674     www      6084:    my $uname=int(1+rand(9)).
                   6085:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6086:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6087:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6088: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6089:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6090:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6091:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6092:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6093:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6094:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6095:            return 'error: unable to generate unique course-ID';
                   6096:        } 
                   6097:    }
1.264     matthew  6098: # ------------------------------------------------ Check supplied server name
1.620     albertel 6099:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6100:     if (! &is_library($course_server)) {
1.264     matthew  6101:         return 'error:bad server name '.$course_server;
                   6102:     }
1.84      www      6103: # ------------------------------------------------------------- Make the course
                   6104:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6105:                       $course_server);
1.84      www      6106:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6107:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6108:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6109: 	return 'error: no such course';
                   6110:     }
1.271     www      6111: # ----------------------------------------------------------------- Course made
1.516     raeburn  6112: # log existence
1.918     raeburn  6113:     my $newcourse = {
                   6114:                     $udom.'_'.$uname => {
1.921     raeburn  6115:                                      description => $description,
                   6116:                                      inst_code   => $inst_code,
                   6117:                                      owner       => $course_owner,
                   6118:                                      type        => $crstype,
1.918     raeburn  6119:                                                 },
                   6120:                     };
1.921     raeburn  6121:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6122: # set toplevel url
1.271     www      6123:     my $topurl=$url;
                   6124:     unless ($nonstandard) {
                   6125: # ------------------------------------------ For standard courses, make top url
                   6126:         my $mapurl=&clutter($url);
1.278     www      6127:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6128:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6129: <map>
                   6130: <resource id="1" type="start"></resource>
                   6131: <resource id="2" src="$mapurl"></resource>
                   6132: <resource id="3" type="finish"></resource>
                   6133: <link index="1" from="1" to="2"></link>
                   6134: <link index="2" from="2" to="3"></link>
                   6135: </map>
                   6136: ENDINITMAP
                   6137:         $topurl=&declutter(
1.638     albertel 6138:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6139:                           );
                   6140:     }
                   6141: # ----------------------------------------------------------- Write preferences
1.84      www      6142:     &writecoursepref($udom.'_'.$uname,
                   6143:                      ('description' => $description,
1.271     www      6144:                       'url'         => $topurl));
1.84      www      6145:     return '/'.$udom.'/'.$uname;
                   6146: }
                   6147: 
1.813     albertel 6148: sub is_course {
                   6149:     my ($cdom,$cnum) = @_;
                   6150:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6151: 				undef,'.');
1.813     albertel 6152:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6153:         return 1;
                   6154:     }
                   6155:     return 0;
                   6156: }
                   6157: 
1.21      www      6158: # ---------------------------------------------------------- Assign Custom Role
                   6159: 
                   6160: sub assigncustomrole {
1.957     raeburn  6161:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6162:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6163:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6164: }
                   6165: 
                   6166: # ----------------------------------------------------------------- Revoke Role
                   6167: 
                   6168: sub revokerole {
1.957     raeburn  6169:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6170:     my $now=time;
1.965     raeburn  6171:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6172: }
                   6173: 
                   6174: # ---------------------------------------------------------- Revoke Custom Role
                   6175: 
                   6176: sub revokecustomrole {
1.957     raeburn  6177:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6178:     my $now=time;
1.357     www      6179:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6180:            $deleteflag,$selfenroll,$context);
1.17      www      6181: }
                   6182: 
1.533     banghart 6183: # ------------------------------------------------------------ Disk usage
1.535     albertel 6184: sub diskusage {
1.955     raeburn  6185:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6186:     $directorypath =~ s/\/$//;
                   6187:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6188:                        .&escape($getpropath).':'.&escape($uname).':'
                   6189:                        .&escape($udom),homeserver($uname,$udom));
                   6190:     if ($listing eq 'unknown_cmd') {
                   6191:         if ($getpropath) {
                   6192:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6193:         }
                   6194:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6195:     }
1.514     albertel 6196:     return $listing;
1.512     banghart 6197: }
                   6198: 
1.566     banghart 6199: sub is_locked {
                   6200:     my ($file_name, $domain, $user) = @_;
                   6201:     my @check;
                   6202:     my $is_locked;
                   6203:     push @check, $file_name;
1.613     albertel 6204:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6205: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6206:     my ($tmp)=keys(%locked);
                   6207:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6208:     
1.566     banghart 6209:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6210:         $is_locked = 'false';
                   6211:         foreach my $entry (@{$locked{$file_name}}) {
                   6212:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6213:                $is_locked = 'true';
                   6214:                last;
1.745     raeburn  6215:            }
                   6216:        }
1.566     banghart 6217:     } else {
                   6218:         $is_locked = 'false';
                   6219:     }
                   6220: }
                   6221: 
1.759     albertel 6222: sub declutter_portfile {
                   6223:     my ($file) = @_;
1.833     albertel 6224:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6225:     return $file;
                   6226: }
                   6227: 
1.559     banghart 6228: # ------------------------------------------------------------- Mark as Read Only
                   6229: 
                   6230: sub mark_as_readonly {
                   6231:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6232:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6233:     my ($tmp)=keys(%current_permissions);
                   6234:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6235:     foreach my $file (@{$files}) {
1.759     albertel 6236: 	$file = &declutter_portfile($file);
1.561     banghart 6237:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6238:     }
1.613     albertel 6239:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6240:     return;
                   6241: }
                   6242: 
1.572     banghart 6243: # ------------------------------------------------------------Save Selected Files
                   6244: 
                   6245: sub save_selected_files {
                   6246:     my ($user, $path, @files) = @_;
                   6247:     my $filename = $user."savedfiles";
1.573     banghart 6248:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6249:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6250:     foreach my $file (@files) {
1.620     albertel 6251:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6252:     }
                   6253:     foreach my $file (@other_files) {
1.574     banghart 6254:         print (OUT $file."\n");
1.572     banghart 6255:     }
1.574     banghart 6256:     close (OUT);
1.572     banghart 6257:     return 'ok';
                   6258: }
                   6259: 
1.574     banghart 6260: sub clear_selected_files {
                   6261:     my ($user) = @_;
                   6262:     my $filename = $user."savedfiles";
                   6263:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6264:     print (OUT undef);
                   6265:     close (OUT);
                   6266:     return ("ok");    
                   6267: }
                   6268: 
1.572     banghart 6269: sub files_in_path {
                   6270:     my ($user, $path) = @_;
                   6271:     my $filename = $user."savedfiles";
                   6272:     my %return_files;
1.574     banghart 6273:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6274:     while (my $line_in = <IN>) {
1.574     banghart 6275:         chomp ($line_in);
                   6276:         my @paths_and_file = split (m!/!, $line_in);
                   6277:         my $file_part = pop (@paths_and_file);
                   6278:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6279:         $path_part.='/';
                   6280:         my $path_and_file = $path_part.$file_part;
                   6281:         if ($path_part eq $path) {
                   6282:             $return_files{$file_part}= 'selected';
                   6283:         }
                   6284:     }
1.574     banghart 6285:     close (IN);
                   6286:     return (\%return_files);
1.572     banghart 6287: }
                   6288: 
                   6289: # called in portfolio select mode, to show files selected NOT in current directory
                   6290: sub files_not_in_path {
                   6291:     my ($user, $path) = @_;
                   6292:     my $filename = $user."savedfiles";
                   6293:     my @return_files;
                   6294:     my $path_part;
1.800     albertel 6295:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6296:     while (my $line = <IN>) {
1.572     banghart 6297:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6298:         my @paths_and_file = split(m|/|, $line);
                   6299:         my $file_part = pop(@paths_and_file);
                   6300:         chomp($file_part);
                   6301:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6302:         $path_part .= '/';
                   6303:         my $path_and_file = $path_part.$file_part;
                   6304:         if ($path_part ne $path) {
1.800     albertel 6305:             push(@return_files, ($path_and_file));
1.572     banghart 6306:         }
                   6307:     }
1.800     albertel 6308:     close(OUT);
1.574     banghart 6309:     return (@return_files);
1.572     banghart 6310: }
                   6311: 
1.745     raeburn  6312: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6313: 
1.745     raeburn  6314: sub get_portfile_permissions {
                   6315:     my ($domain,$user) = @_;
1.613     albertel 6316:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6317:     my ($tmp)=keys(%current_permissions);
                   6318:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6319:     return \%current_permissions;
                   6320: }
                   6321: 
                   6322: #---------------------------------------------Get portfolio file access controls
                   6323: 
1.749     raeburn  6324: sub get_access_controls {
1.745     raeburn  6325:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6326:     my %access;
                   6327:     my $real_file = $file;
                   6328:     $file =~ s/\.meta$//;
1.745     raeburn  6329:     if (defined($file)) {
1.749     raeburn  6330:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6331:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6332:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6333:             }
                   6334:         }
1.745     raeburn  6335:     } else {
1.749     raeburn  6336:         foreach my $key (keys(%{$current_permissions})) {
                   6337:             if ($key =~ /\0accesscontrol$/) {
                   6338:                 if (defined($group)) {
                   6339:                     if ($key !~ m-^\Q$group\E/-) {
                   6340:                         next;
                   6341:                     }
                   6342:                 }
                   6343:                 my ($fullpath) = split(/\0/,$key);
                   6344:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6345:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6346:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6347:                     }
                   6348:                 }
                   6349:             }
                   6350:         }
                   6351:     }
                   6352:     return %access;
                   6353: }
                   6354: 
                   6355: sub modify_access_controls {
                   6356:     my ($file_name,$changes,$domain,$user)=@_;
                   6357:     my ($outcome,$deloutcome);
                   6358:     my %store_permissions;
                   6359:     my %new_values;
                   6360:     my %new_control;
                   6361:     my %translation;
                   6362:     my @deletions = ();
                   6363:     my $now = time;
                   6364:     if (exists($$changes{'activate'})) {
                   6365:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6366:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6367:             my $numnew = scalar(@newitems);
                   6368:             for (my $i=0; $i<$numnew; $i++) {
                   6369:                 my $newkey = $newitems[$i];
                   6370:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6371:                 if ($newkey =~ /^\d+:/) { 
                   6372:                     $newkey =~ s/^(\d+)/$newid/;
                   6373:                     $translation{$1} = $newid;
                   6374:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6375:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6376:                     $translation{$1} = $newid;
                   6377:                 }
1.749     raeburn  6378:                 $new_values{$file_name."\0".$newkey} = 
                   6379:                                           $$changes{'activate'}{$newitems[$i]};
                   6380:                 $new_control{$newkey} = $now;
                   6381:             }
                   6382:         }
                   6383:     }
                   6384:     my %todelete;
                   6385:     my %changed_items;
                   6386:     foreach my $action ('delete','update') {
                   6387:         if (exists($$changes{$action})) {
                   6388:             if (ref($$changes{$action}) eq 'HASH') {
                   6389:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6390:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6391:                     if ($action eq 'delete') { 
                   6392:                         $todelete{$itemnum} = 1;
                   6393:                     } else {
                   6394:                         $changed_items{$itemnum} = $key;
                   6395:                     }
                   6396:                 }
1.745     raeburn  6397:             }
                   6398:         }
1.749     raeburn  6399:     }
                   6400:     # get lock on access controls for file.
                   6401:     my $lockhash = {
                   6402:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6403:                                                        ':'.$env{'user.domain'},
                   6404:                    }; 
                   6405:     my $tries = 0;
                   6406:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6407:    
                   6408:     while (($gotlock ne 'ok') && $tries <3) {
                   6409:         $tries ++;
                   6410:         sleep 1;
                   6411:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6412:     }
                   6413:     if ($gotlock eq 'ok') {
                   6414:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6415:         my ($tmp)=keys(%curr_permissions);
                   6416:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6417:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6418:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6419:             if (ref($curr_controls) eq 'HASH') {
                   6420:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6421:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6422:                     if (defined($todelete{$itemnum})) {
                   6423:                         push(@deletions,$file_name."\0".$control_item);
                   6424:                     } else {
                   6425:                         if (defined($changed_items{$itemnum})) {
                   6426:                             $new_control{$changed_items{$itemnum}} = $now;
                   6427:                             push(@deletions,$file_name."\0".$control_item);
                   6428:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6429:                         } else {
                   6430:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6431:                         }
                   6432:                     }
1.745     raeburn  6433:                 }
                   6434:             }
                   6435:         }
1.970     raeburn  6436:         my ($group);
                   6437:         if (&is_course($domain,$user)) {
                   6438:             ($group,my $file) = split(/\//,$file_name,2);
                   6439:         }
1.749     raeburn  6440:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6441:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6442:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6443:         #  remove lock
                   6444:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6445:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6446:         my $sqlresult =
1.970     raeburn  6447:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6448:                                     $group);
1.749     raeburn  6449:     } else {
                   6450:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6451:     }
1.749     raeburn  6452:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6453: }
                   6454: 
1.827     raeburn  6455: sub make_public_indefinitely {
                   6456:     my ($requrl) = @_;
                   6457:     my $now = time;
                   6458:     my $action = 'activate';
                   6459:     my $aclnum = 0;
                   6460:     if (&is_portfolio_url($requrl)) {
                   6461:         my (undef,$udom,$unum,$file_name,$group) =
                   6462:             &parse_portfolio_url($requrl);
                   6463:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6464:         my %access_controls = &get_access_controls($current_perms,
                   6465:                                                    $group,$file_name);
                   6466:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6467:             my ($num,$scope,$end,$start) = 
                   6468:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6469:             if ($scope eq 'public') {
                   6470:                 if ($start <= $now && $end == 0) {
                   6471:                     $action = 'none';
                   6472:                 } else {
                   6473:                     $action = 'update';
                   6474:                     $aclnum = $num;
                   6475:                 }
                   6476:                 last;
                   6477:             }
                   6478:         }
                   6479:         if ($action eq 'none') {
                   6480:              return 'ok';
                   6481:         } else {
                   6482:             my %changes;
                   6483:             my $newend = 0;
                   6484:             my $newstart = $now;
                   6485:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6486:             $changes{$action}{$newkey} = {
                   6487:                 type => 'public',
                   6488:                 time => {
                   6489:                     start => $newstart,
                   6490:                     end   => $newend,
                   6491:                 },
                   6492:             };
                   6493:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6494:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6495:             return $outcome;
                   6496:         }
                   6497:     } else {
                   6498:         return 'invalid';
                   6499:     }
                   6500: }
                   6501: 
1.745     raeburn  6502: #------------------------------------------------------Get Marked as Read Only
                   6503: 
                   6504: sub get_marked_as_readonly {
                   6505:     my ($domain,$user,$what,$group) = @_;
                   6506:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6507:     my @readonly_files;
1.629     banghart 6508:     my $cmp1=$what;
                   6509:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6510:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6511:         if (defined($group)) {
                   6512:             if ($file_name !~ m-^\Q$group\E/-) {
                   6513:                 next;
                   6514:             }
                   6515:         }
1.561     banghart 6516:         if (ref($value) eq "ARRAY"){
                   6517:             foreach my $stored_what (@{$value}) {
1.629     banghart 6518:                 my $cmp2=$stored_what;
1.759     albertel 6519:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6520:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6521:                 }
1.629     banghart 6522:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6523:                     push(@readonly_files, $file_name);
1.745     raeburn  6524:                     last;
1.563     banghart 6525:                 } elsif (!defined($what)) {
                   6526:                     push(@readonly_files, $file_name);
1.745     raeburn  6527:                     last;
1.561     banghart 6528:                 }
                   6529:             }
1.745     raeburn  6530:         }
1.561     banghart 6531:     }
                   6532:     return @readonly_files;
                   6533: }
1.577     banghart 6534: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6535: 
1.577     banghart 6536: sub get_marked_as_readonly_hash {
1.745     raeburn  6537:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6538:     my %readonly_files;
1.745     raeburn  6539:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6540:         if (defined($group)) {
                   6541:             if ($file_name !~ m-^\Q$group\E/-) {
                   6542:                 next;
                   6543:             }
                   6544:         }
1.577     banghart 6545:         if (ref($value) eq "ARRAY"){
                   6546:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6547:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6548:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6549:                         if ($lock_descriptor eq 'graded') {
                   6550:                             $readonly_files{$file_name} = 'graded';
                   6551:                         } elsif ($lock_descriptor eq 'handback') {
                   6552:                             $readonly_files{$file_name} = 'handback';
                   6553:                         } else {
                   6554:                             if (!exists($readonly_files{$file_name})) {
                   6555:                                 $readonly_files{$file_name} = 'locked';
                   6556:                             }
                   6557:                         }
1.745     raeburn  6558:                     }
1.750     banghart 6559:                 } 
1.577     banghart 6560:             }
                   6561:         } 
                   6562:     }
                   6563:     return %readonly_files;
                   6564: }
1.559     banghart 6565: # ------------------------------------------------------------ Unmark as Read Only
                   6566: 
                   6567: sub unmark_as_readonly {
1.629     banghart 6568:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6569:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6570:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6571:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6572:     my $symb_crs = $what;
                   6573:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6574:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6575:     my ($tmp)=keys(%current_permissions);
                   6576:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6577:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6578:     foreach my $file (@readonly_files) {
1.759     albertel 6579: 	my $clean_file = &declutter_portfile($file);
                   6580: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6581: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6582:         my @new_locks;
                   6583:         my @del_keys;
                   6584:         if (ref($current_locks) eq "ARRAY"){
                   6585:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6586:                 my $compare=$locker;
1.749     raeburn  6587:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6588:                     $compare=join('',@{$locker});
1.746     raeburn  6589:                     if ($compare ne $symb_crs) {
                   6590:                         push(@new_locks, $locker);
                   6591:                     }
1.563     banghart 6592:                 }
                   6593:             }
1.650     albertel 6594:             if (scalar(@new_locks) > 0) {
1.563     banghart 6595:                 $current_permissions{$file} = \@new_locks;
                   6596:             } else {
                   6597:                 push(@del_keys, $file);
1.613     albertel 6598:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6599:                 delete($current_permissions{$file});
1.563     banghart 6600:             }
                   6601:         }
1.561     banghart 6602:     }
1.613     albertel 6603:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6604:     return;
                   6605: }
1.512     banghart 6606: 
1.17      www      6607: # ------------------------------------------------------------ Directory lister
                   6608: 
                   6609: sub dirlist {
1.955     raeburn  6610:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6611:     $uri=~s/^\///;
                   6612:     $uri=~s/\/$//;
1.253     stredwic 6613:     my ($udom, $uname);
1.955     raeburn  6614:     if ($getuserdir) {
1.253     stredwic 6615:         $udom = $userdomain;
                   6616:         $uname = $username;
1.955     raeburn  6617:     } else {
                   6618:         (undef,$udom,$uname)=split(/\//,$uri);
                   6619:         if(defined($userdomain)) {
                   6620:             $udom = $userdomain;
                   6621:         }
                   6622:         if(defined($username)) {
                   6623:             $uname = $username;
                   6624:         }
1.253     stredwic 6625:     }
1.955     raeburn  6626:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6627: 
1.955     raeburn  6628:     $dirRoot = $perlvar{'lonDocRoot'};
                   6629:     if (defined($getpropath)) {
                   6630:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6631:         $dirRoot =~ s/\/$//;
1.955     raeburn  6632:     } elsif (defined($getuserdir)) {
                   6633:         my $subdir=$uname.'__';
                   6634:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6635:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6636:                    ."/$udom/$subdir/$uname";
                   6637:     } elsif (defined($alternateRoot)) {
                   6638:         $dirRoot = $alternateRoot;
1.751     banghart 6639:     }
1.253     stredwic 6640: 
                   6641:     if($udom) {
                   6642:         if($uname) {
1.955     raeburn  6643:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6644:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6645:                               .':'.&escape($uname).':'.&escape($udom),
                   6646:                               &homeserver($uname,$udom));
                   6647:             if ($listing eq 'unknown_cmd') {
                   6648:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6649:                                   &homeserver($uname,$udom));
                   6650:             } else {
                   6651:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6652:             }
1.605     matthew  6653:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6654:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6655: 				  &homeserver($uname,$udom));
1.605     matthew  6656:                 @listing_results = split(/:/,$listing);
                   6657:             } else {
                   6658:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6659:             }
                   6660:             return @listing_results;
1.955     raeburn  6661:         } elsif(!$alternateRoot) {
1.800     albertel 6662:             my %allusers;
1.841     albertel 6663: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6664:  	    foreach my $tryserver (keys(%servers)) {
                   6665:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6666:                                   &escape($udom),$tryserver);
                   6667:                 if ($listing eq 'unknown_cmd') {
                   6668: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6669: 				      $udom, $tryserver);
                   6670:                 } else {
                   6671:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6672:                 }
1.841     albertel 6673: 		if ($listing eq 'unknown_cmd') {
                   6674: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6675: 				      $udom, $tryserver);
                   6676: 		    @listing_results = split(/:/,$listing);
                   6677: 		} else {
                   6678: 		    @listing_results =
                   6679: 			map { &unescape($_); } split(/:/,$listing);
                   6680: 		}
                   6681: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6682: 		    $listing_results[0] ne 'empty'       &&
                   6683: 		    $listing_results[0] ne 'con_lost') {
                   6684: 		    foreach my $line (@listing_results) {
                   6685: 			my ($entry) = split(/&/,$line,2);
                   6686: 			$allusers{$entry} = 1;
                   6687: 		    }
                   6688: 		}
1.253     stredwic 6689:             }
                   6690:             my $alluserstr='';
1.800     albertel 6691:             foreach my $user (sort(keys(%allusers))) {
                   6692:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6693:             }
                   6694:             $alluserstr=~s/:$//;
                   6695:             return split(/:/,$alluserstr);
                   6696:         } else {
1.800     albertel 6697:             return ('missing user name');
1.253     stredwic 6698:         }
1.955     raeburn  6699:     } elsif(!defined($getpropath)) {
1.841     albertel 6700:         my @all_domains = sort(&all_domains());
1.955     raeburn  6701:         foreach my $domain (@all_domains) {
                   6702:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6703:         }
                   6704:         return @all_domains;
                   6705:     } else {
1.800     albertel 6706:         return ('missing domain');
1.275     stredwic 6707:     }
                   6708: }
                   6709: 
                   6710: # --------------------------------------------- GetFileTimestamp
                   6711: # This function utilizes dirlist and returns the date stamp for
                   6712: # when it was last modified.  It will also return an error of -1
                   6713: # if an error occurs
                   6714: 
                   6715: sub GetFileTimestamp {
1.955     raeburn  6716:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6717:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6718:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6719:     my ($fileStat) = 
                   6720:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6721:                                  undef,$getuserdir);
1.275     stredwic 6722:     my @stats = split('&', $fileStat);
                   6723:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6724:         # @stats contains first the filename, then the stat output
                   6725:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6726:     } else {
                   6727:         return -1;
1.253     stredwic 6728:     }
1.26      www      6729: }
                   6730: 
1.712     albertel 6731: sub stat_file {
                   6732:     my ($uri) = @_;
1.787     albertel 6733:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6734: 
1.955     raeburn  6735:     my ($udom,$uname,$file);
1.712     albertel 6736:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6737: 	($udom,$uname,$file) =
1.811     albertel 6738: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6739: 	$file = 'userfiles/'.$file;
                   6740:     }
                   6741:     if ($uri =~ m-^/res/-) {
                   6742: 	($udom,$uname) = 
1.807     albertel 6743: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6744: 	$file = $uri;
                   6745:     }
                   6746: 
                   6747:     if (!$udom || !$uname || !$file) {
                   6748: 	# unable to handle the uri
                   6749: 	return ();
                   6750:     }
1.956     raeburn  6751:     my $getpropath;
                   6752:     if ($file =~ /^userfiles\//) {
                   6753:         $getpropath = 1;
                   6754:     }
1.955     raeburn  6755:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6756:     my @stats = split('&', $result);
1.721     banghart 6757:     
1.712     albertel 6758:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6759: 	shift(@stats); #filename is first
                   6760: 	return @stats;
                   6761:     }
                   6762:     return ();
                   6763: }
                   6764: 
1.26      www      6765: # -------------------------------------------------------- Value of a Condition
                   6766: 
1.713     albertel 6767: # gets the value of a specific preevaluated condition
                   6768: #    stored in the string  $env{user.state.<cid>}
                   6769: # or looks up a condition reference in the bighash and if if hasn't
                   6770: # already been evaluated recurses into docondval to get the value of
                   6771: # the condition, then memoizing it to 
                   6772: #   $env{user.state.<cid>.<condition>}
1.40      www      6773: sub directcondval {
                   6774:     my $number=shift;
1.620     albertel 6775:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6776: 	&Apache::lonuserstate::evalstate();
                   6777:     }
1.713     albertel 6778:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6779: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6780:     } elsif ($number =~ /^_/) {
                   6781: 	my $sub_condition;
                   6782: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6783: 		&GDBM_READER(),0640)) {
                   6784: 	    $sub_condition=$bighash{'conditions'.$number};
                   6785: 	    untie(%bighash);
                   6786: 	}
                   6787: 	my $value = &docondval($sub_condition);
1.949     raeburn  6788: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6789: 	return $value;
                   6790:     }
1.620     albertel 6791:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6792:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6793:     } else {
                   6794:        return 2;
                   6795:     }
                   6796: }
                   6797: 
1.713     albertel 6798: # get the collection of conditions for this resource
1.26      www      6799: sub condval {
                   6800:     my $condidx=shift;
1.54      www      6801:     my $allpathcond='';
1.713     albertel 6802:     foreach my $cond (split(/\|/,$condidx)) {
                   6803: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6804: 	    $allpathcond.=
                   6805: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6806: 	}
1.191     harris41 6807:     }
1.54      www      6808:     $allpathcond=~s/\|$//;
1.713     albertel 6809:     return &docondval($allpathcond);
                   6810: }
                   6811: 
                   6812: #evaluates an expression of conditions
                   6813: sub docondval {
                   6814:     my ($allpathcond) = @_;
                   6815:     my $result=0;
                   6816:     if ($env{'request.course.id'}
                   6817: 	&& defined($allpathcond)) {
                   6818: 	my $operand='|';
                   6819: 	my @stack;
                   6820: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6821: 	    if ($chunk eq '(') {
                   6822: 		push @stack,($operand,$result);
                   6823: 	    } elsif ($chunk eq ')') {
                   6824: 		my $before=pop @stack;
                   6825: 		if (pop @stack eq '&') {
                   6826: 		    $result=$result>$before?$before:$result;
                   6827: 		} else {
                   6828: 		    $result=$result>$before?$result:$before;
                   6829: 		}
                   6830: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6831: 		$operand=$chunk;
                   6832: 	    } else {
                   6833: 		my $new=directcondval($chunk);
                   6834: 		if ($operand eq '&') {
                   6835: 		    $result=$result>$new?$new:$result;
                   6836: 		} else {
                   6837: 		    $result=$result>$new?$result:$new;
                   6838: 		}
                   6839: 	    }
                   6840: 	}
1.26      www      6841:     }
                   6842:     return $result;
1.421     albertel 6843: }
                   6844: 
                   6845: # ---------------------------------------------------- Devalidate courseresdata
                   6846: 
                   6847: sub devalidatecourseresdata {
                   6848:     my ($coursenum,$coursedomain)=@_;
                   6849:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6850:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6851: }
                   6852: 
1.763     www      6853: 
1.200     www      6854: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6855: #
                   6856: #  Parameters:
                   6857: #      $coursenum    - Number of the course.
                   6858: #      $coursedomain - Domain at which the course was created.
                   6859: #  Returns:
                   6860: #     A hash of the course parameters along (I think) with timestamps
                   6861: #     and version info.
1.877     foxr     6862: 
1.624     albertel 6863: sub get_courseresdata {
                   6864:     my ($coursenum,$coursedomain)=@_;
1.200     www      6865:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6866:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6867:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6868:     my %dumpreply;
1.417     albertel 6869:     unless (defined($cached)) {
1.624     albertel 6870: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6871: 	$result=\%dumpreply;
1.251     albertel 6872: 	my ($tmp) = keys(%dumpreply);
                   6873: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6874: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6875: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6876: 	    return $tmp;
1.416     albertel 6877: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6878: 	    $result=undef;
1.599     albertel 6879: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6880: 	}
                   6881:     }
1.624     albertel 6882:     return $result;
                   6883: }
                   6884: 
1.633     albertel 6885: sub devalidateuserresdata {
                   6886:     my ($uname,$udom)=@_;
                   6887:     my $hashid="$udom:$uname";
                   6888:     &devalidate_cache_new('userres',$hashid);
                   6889: }
                   6890: 
1.624     albertel 6891: sub get_userresdata {
                   6892:     my ($uname,$udom)=@_;
                   6893:     #most student don\'t have any data set, check if there is some data
                   6894:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6895: 
                   6896:     my $hashid="$udom:$uname";
                   6897:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6898:     if (!defined($cached)) {
                   6899: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6900: 	$result=\%resourcedata;
                   6901: 	&do_cache_new('userres',$hashid,$result,600);
                   6902:     }
                   6903:     my ($tmp)=keys(%$result);
                   6904:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6905: 	return $result;
                   6906:     }
                   6907:     #error 2 occurs when the .db doesn't exist
                   6908:     if ($tmp!~/error: 2 /) {
1.672     albertel 6909: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6910: 		 " Trying to get resource data for ".
                   6911: 		 $uname." at ".$udom.": ".
                   6912: 		 $tmp."</font>");
                   6913:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6914: 	#&EXT_cache_set($udom,$uname);
                   6915: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6916: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6917:     }
                   6918:     return $tmp;
                   6919: }
1.879     foxr     6920: #----------------------------------------------- resdata - return resource data
                   6921: #  Purpose:
                   6922: #    Return resource data for either users or for a course.
                   6923: #  Parameters:
                   6924: #     $name      - Course/user name.
                   6925: #     $domain    - Name of the domain the user/course is registered on.
                   6926: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6927: #     @which     - Array of names of resources desired.
                   6928: #  Returns:
                   6929: #     The value of the first reasource in @which that is found in the
                   6930: #     resource hash.
                   6931: #  Exceptional Conditions:
                   6932: #     If the $type passed in is not valid (not the string 'course' or 
                   6933: #     'user', an undefined  reference is returned.
                   6934: #     If none of the resources are found, an undef is returned
1.624     albertel 6935: sub resdata {
                   6936:     my ($name,$domain,$type,@which)=@_;
                   6937:     my $result;
                   6938:     if ($type eq 'course') {
                   6939: 	$result=&get_courseresdata($name,$domain);
                   6940:     } elsif ($type eq 'user') {
                   6941: 	$result=&get_userresdata($name,$domain);
                   6942:     }
                   6943:     if (!ref($result)) { return $result; }    
1.251     albertel 6944:     foreach my $item (@which) {
1.927     albertel 6945: 	if (defined($result->{$item->[0]})) {
                   6946: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6947: 	}
1.250     albertel 6948:     }
1.291     albertel 6949:     return undef;
1.200     www      6950: }
                   6951: 
1.379     matthew  6952: #
                   6953: # EXT resource caching routines
                   6954: #
                   6955: 
                   6956: sub clear_EXT_cache_status {
1.383     albertel 6957:     &delenv('cache.EXT.');
1.379     matthew  6958: }
                   6959: 
                   6960: sub EXT_cache_status {
                   6961:     my ($target_domain,$target_user) = @_;
1.383     albertel 6962:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6963:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6964:         # We know already the user has no data
                   6965:         return 1;
                   6966:     } else {
                   6967:         return 0;
                   6968:     }
                   6969: }
                   6970: 
                   6971: sub EXT_cache_set {
                   6972:     my ($target_domain,$target_user) = @_;
1.383     albertel 6973:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6974:     #&appenv({$cachename => time});
1.379     matthew  6975: }
                   6976: 
1.28      www      6977: # --------------------------------------------------------- Value of a Variable
1.58      www      6978: sub EXT {
1.715     albertel 6979: 
1.395     albertel 6980:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6981:     unless ($varname) { return ''; }
1.218     albertel 6982:     #get real user name/domain, courseid and symb
                   6983:     my $courseid;
1.359     albertel 6984:     my $publicuser;
1.427     www      6985:     if ($symbparm) {
                   6986: 	$symbparm=&get_symb_from_alias($symbparm);
                   6987:     }
1.218     albertel 6988:     if (!($uname && $udom)) {
1.790     albertel 6989:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6990:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6991:     } else {
1.620     albertel 6992: 	$courseid=$env{'request.course.id'};
1.218     albertel 6993:     }
1.48      www      6994:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6995:     my $rest;
1.320     albertel 6996:     if (defined($therest[0])) {
1.48      www      6997:        $rest=join('.',@therest);
                   6998:     } else {
                   6999:        $rest='';
                   7000:     }
1.320     albertel 7001: 
1.57      www      7002:     my $qualifierrest=$qualifier;
                   7003:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7004:     my $spacequalifierrest=$space;
                   7005:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7006:     if ($realm eq 'user') {
1.48      www      7007: # --------------------------------------------------------------- user.resource
                   7008: 	if ($space eq 'resource') {
1.651     albertel 7009: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7010: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7011: 		 &&
1.744     albertel 7012: 		 ($symbparm eq &symbread()) ) {	
                   7013: 		# if we are in the middle of processing the resource the
                   7014: 		# get the value we are planning on committing
                   7015:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7016:                     return $Apache::lonhomework::results{$qualifierrest};
                   7017:                 } else {
                   7018:                     return $Apache::lonhomework::history{$qualifierrest};
                   7019:                 }
1.335     albertel 7020: 	    } else {
1.359     albertel 7021: 		my %restored;
1.620     albertel 7022: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7023: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7024: 		} else {
                   7025: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7026: 		}
1.335     albertel 7027: 		return $restored{$qualifierrest};
                   7028: 	    }
1.48      www      7029: # ----------------------------------------------------------------- user.access
                   7030:         } elsif ($space eq 'access') {
1.218     albertel 7031: 	    # FIXME - not supporting calls for a specific user
1.48      www      7032:             return &allowed($qualifier,$rest);
                   7033: # ------------------------------------------ user.preferences, user.environment
                   7034:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7035: 	    if (($uname eq $env{'user.name'}) &&
                   7036: 		($udom eq $env{'user.domain'})) {
                   7037: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7038: 	    } else {
1.359     albertel 7039: 		my %returnhash;
                   7040: 		if (!$publicuser) {
                   7041: 		    %returnhash=&userenvironment($udom,$uname,
                   7042: 						 $qualifierrest);
                   7043: 		}
1.218     albertel 7044: 		return $returnhash{$qualifierrest};
                   7045: 	    }
1.48      www      7046: # ----------------------------------------------------------------- user.course
                   7047:         } elsif ($space eq 'course') {
1.218     albertel 7048: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7049:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7050: # ------------------------------------------------------------------- user.role
                   7051:         } elsif ($space eq 'role') {
1.218     albertel 7052: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7053:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7054:             if ($qualifier eq 'value') {
                   7055: 		return $role;
                   7056:             } elsif ($qualifier eq 'extent') {
                   7057:                 return $where;
                   7058:             }
                   7059: # ----------------------------------------------------------------- user.domain
                   7060:         } elsif ($space eq 'domain') {
1.218     albertel 7061:             return $udom;
1.48      www      7062: # ------------------------------------------------------------------- user.name
                   7063:         } elsif ($space eq 'name') {
1.218     albertel 7064:             return $uname;
1.48      www      7065: # ---------------------------------------------------- Any other user namespace
1.29      www      7066:         } else {
1.359     albertel 7067: 	    my %reply;
                   7068: 	    if (!$publicuser) {
                   7069: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7070: 	    }
                   7071: 	    return $reply{$qualifierrest};
1.48      www      7072:         }
1.236     www      7073:     } elsif ($realm eq 'query') {
                   7074: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7075:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7076: 						[$spacequalifierrest]);
1.620     albertel 7077: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7078:    } elsif ($realm eq 'request') {
1.48      www      7079: # ------------------------------------------------------------- request.browser
                   7080:         if ($space eq 'browser') {
1.430     www      7081: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7082: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7083: 		    return 1;
                   7084: 		} else {
                   7085: 		    return 0;
                   7086: 		}
                   7087: 	    } else {
1.620     albertel 7088: 		return $env{'browser.'.$qualifier};
1.430     www      7089: 	    }
1.57      www      7090: # ------------------------------------------------------------ request.filename
                   7091:         } else {
1.620     albertel 7092:             return $env{'request.'.$spacequalifierrest};
1.29      www      7093:         }
1.28      www      7094:     } elsif ($realm eq 'course') {
1.48      www      7095: # ---------------------------------------------------------- course.description
1.620     albertel 7096:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7097:     } elsif ($realm eq 'resource') {
1.165     www      7098: 
1.620     albertel 7099: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7100: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7101: 	}
1.693     albertel 7102: 
                   7103: 	if ($space eq 'title') {
                   7104: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7105: 	    return &gettitle($symbparm);
                   7106: 	}
                   7107: 	
                   7108: 	if ($space eq 'map') {
                   7109: 	    my ($map) = &decode_symb($symbparm);
                   7110: 	    return &symbread($map);
                   7111: 	}
1.905     albertel 7112: 	if ($space eq 'filename') {
                   7113: 	    if ($symbparm) {
                   7114: 		return &clutter((&decode_symb($symbparm))[2]);
                   7115: 	    }
                   7116: 	    return &hreflocation('',$env{'request.filename'});
                   7117: 	}
1.693     albertel 7118: 
                   7119: 	my ($section, $group, @groups);
1.593     albertel 7120: 	my ($courselevelm,$courselevel);
1.539     albertel 7121: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7122: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7123: 
1.218     albertel 7124: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7125: 
1.60      www      7126: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7127: 	    my $symbp=$symbparm;
1.735     albertel 7128: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7129: 
                   7130: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7131: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7132: 
1.620     albertel 7133: 	    if (($env{'user.name'} eq $uname) &&
                   7134: 		($env{'user.domain'} eq $udom)) {
                   7135: 		$section=$env{'request.course.sec'};
1.733     raeburn  7136:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7137:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7138: 	    } else {
1.539     albertel 7139: 		if (! defined($usection)) {
1.551     albertel 7140: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7141: 		} else {
                   7142: 		    $section = $usection;
                   7143: 		}
1.733     raeburn  7144:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7145: 	    }
                   7146: 
                   7147: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7148: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7149: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7150: 
1.593     albertel 7151: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7152: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7153: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7154: 
1.60      www      7155: # ----------------------------------------------------------- first, check user
1.624     albertel 7156: 
                   7157: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7158: 				       ([$courselevelr,'resource'],
                   7159: 					[$courselevelm,'map'     ],
                   7160: 					[$courselevel, 'course'  ]));
1.931     albertel 7161: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7162: 
1.594     albertel 7163: # ------------------------------------------------ second, check some of course
1.684     raeburn  7164:             my $coursereply;
1.691     raeburn  7165:             if (@groups > 0) {
                   7166:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7167:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7168:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7169:             }
1.96      www      7170: 
1.684     raeburn  7171: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7172: 				  $env{'course.'.$courseid.'.domain'},
                   7173: 				  'course',
                   7174: 				  ([$seclevelr,   'resource'],
                   7175: 				   [$seclevelm,   'map'     ],
                   7176: 				   [$seclevel,    'course'  ],
                   7177: 				   [$courselevelr,'resource']));
                   7178: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7179: 
1.60      www      7180: # ------------------------------------------------------ third, check map parms
1.218     albertel 7181: 	    my %parmhash=();
                   7182: 	    my $thisparm='';
                   7183: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7184: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7185: 		    &GDBM_READER(),0640)) {
1.218     albertel 7186: 		$thisparm=$parmhash{$symbparm};
                   7187: 		untie(%parmhash);
                   7188: 	    }
1.927     albertel 7189: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7190: 	}
1.594     albertel 7191: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7192: 
1.218     albertel 7193: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7194: 	my $filename;
                   7195: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7196: 	if ($symbparm) {
1.409     www      7197: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7198: 	} else {
1.620     albertel 7199: 	    $filename=$env{'request.filename'};
1.282     albertel 7200: 	}
                   7201: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7202: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7203: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7204: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7205: 
1.927     albertel 7206: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7207: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7208: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7209: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7210: 				     $env{'course.'.$courseid.'.domain'},
                   7211: 				     'course',
1.927     albertel 7212: 				     ([$courselevelm,'map'   ],
                   7213: 				      [$courselevel, 'course']));
                   7214: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7215: 	}
1.145     www      7216: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7217: 	unless ($space eq '0') {
1.336     albertel 7218: 	    my @parts=split(/_/,$space);
                   7219: 	    my $id=pop(@parts);
                   7220: 	    my $part=join('_',@parts);
                   7221: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7222: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7223: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7224: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7225: 	}
1.395     albertel 7226: 	if ($recurse) { return undef; }
                   7227: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7228: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7229: # ---------------------------------------------------- Any other user namespace
                   7230:     } elsif ($realm eq 'environment') {
                   7231: # ----------------------------------------------------------------- environment
1.620     albertel 7232: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7233: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7234: 	} else {
1.770     albertel 7235: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7236: 		return '';
                   7237: 	    }
1.219     albertel 7238: 	    my %returnhash=&userenvironment($udom,$uname,
                   7239: 					    $spacequalifierrest);
                   7240: 	    return $returnhash{$spacequalifierrest};
                   7241: 	}
1.28      www      7242:     } elsif ($realm eq 'system') {
1.48      www      7243: # ----------------------------------------------------------------- system.time
                   7244: 	if ($space eq 'time') {
                   7245: 	    return time;
                   7246:         }
1.696     albertel 7247:     } elsif ($realm eq 'server') {
                   7248: # ----------------------------------------------------------------- system.time
                   7249: 	if ($space eq 'name') {
                   7250: 	    return $ENV{'SERVER_NAME'};
                   7251:         }
1.28      www      7252:     }
1.48      www      7253:     return '';
1.61      www      7254: }
                   7255: 
1.927     albertel 7256: sub get_reply {
                   7257:     my ($reply_value) = @_;
1.940     raeburn  7258:     if (ref($reply_value) eq 'ARRAY') {
                   7259:         if (wantarray) {
                   7260: 	    return @$reply_value;
                   7261:         }
                   7262:         return $reply_value->[0];
                   7263:     } else {
                   7264:         return $reply_value;
1.927     albertel 7265:     }
                   7266: }
                   7267: 
1.691     raeburn  7268: sub check_group_parms {
                   7269:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7270:     my @groupitems = ();
                   7271:     my $resultitem;
1.927     albertel 7272:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7273:     foreach my $group (@{$groups}) {
                   7274:         foreach my $level (@levels) {
1.927     albertel 7275:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7276:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7277:         }
                   7278:     }
                   7279:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7280:                             $env{'course.'.$courseid.'.domain'},
                   7281:                                      'course',@groupitems);
                   7282:     return $coursereply;
                   7283: }
                   7284: 
                   7285: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7286:     my ($courseid,@groups) = @_;
                   7287:     @groups = sort(@groups);
1.691     raeburn  7288:     return @groups;
                   7289: }
                   7290: 
1.395     albertel 7291: sub packages_tab_default {
                   7292:     my ($uri,$varname)=@_;
                   7293:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7294: 
                   7295:     my (@extension,@specifics,$do_default);
                   7296:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7297: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7298: 	if ($pack_type eq 'default') {
                   7299: 	    $do_default=1;
                   7300: 	} elsif ($pack_type eq 'extension') {
                   7301: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7302: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7303: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7304: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7305: 	}
                   7306:     }
                   7307:     # first look for a package that matches the requested part id
                   7308:     foreach my $package (@specifics) {
                   7309: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7310: 	next if ($pack_part ne $part);
                   7311: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7312: 	    return $packagetab{"$pack_type&$name&default"};
                   7313: 	}
                   7314:     }
                   7315:     # look for any possible matching non extension_ package
                   7316:     foreach my $package (@specifics) {
                   7317: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7318: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7319: 	    return $packagetab{"$pack_type&$name&default"};
                   7320: 	}
1.585     albertel 7321: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7322: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7323: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7324: 	}
                   7325:     }
1.738     albertel 7326:     # look for any posible extension_ match
                   7327:     foreach my $package (@extension) {
                   7328: 	my ($package,$pack_type)=@{$package};
                   7329: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7330: 	    return $packagetab{"$pack_type&$name&default"};
                   7331: 	}
                   7332: 	if (defined($packagetab{$package."&$name&default"})) {
                   7333: 	    return $packagetab{$package."&$name&default"};
                   7334: 	}
                   7335:     }
                   7336:     # look for a global default setting
                   7337:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7338: 	return $packagetab{"default&$name&default"};
                   7339:     }
1.395     albertel 7340:     return undef;
                   7341: }
                   7342: 
1.334     albertel 7343: sub add_prefix_and_part {
                   7344:     my ($prefix,$part)=@_;
                   7345:     my $keyroot;
                   7346:     if (defined($prefix) && $prefix !~ /^__/) {
                   7347: 	# prefix that has a part already
                   7348: 	$keyroot=$prefix;
                   7349:     } elsif (defined($prefix)) {
                   7350: 	# prefix that is missing a part
                   7351: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7352:     } else {
                   7353: 	# no prefix at all
                   7354: 	if (defined($part)) { $keyroot='_'.$part; }
                   7355:     }
                   7356:     return $keyroot;
                   7357: }
                   7358: 
1.71      www      7359: # ---------------------------------------------------------------- Get metadata
                   7360: 
1.599     albertel 7361: my %metaentry;
1.71      www      7362: sub metadata {
1.176     www      7363:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7364:     $uri=&declutter($uri);
1.288     albertel 7365:     # if it is a non metadata possible uri return quickly
1.529     albertel 7366:     if (($uri eq '') || 
                   7367: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7368: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7369:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7370: 	return undef;
                   7371:     }
                   7372:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7373: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7374: 	return undef;
1.288     albertel 7375:     }
1.73      www      7376:     my $filename=$uri;
                   7377:     $uri=~s/\.meta$//;
1.172     www      7378: #
                   7379: # Is the metadata already cached?
1.177     www      7380: # Look at timestamp of caching
1.172     www      7381: # Everything is cached by the main uri, libraries are never directly cached
                   7382: #
1.428     albertel 7383:     if (!defined($liburi)) {
1.599     albertel 7384: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7385: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7386:     }
                   7387:     {
1.172     www      7388: #
                   7389: # Is this a recursive call for a library?
                   7390: #
1.599     albertel 7391: #	if (! exists($metacache{$uri})) {
                   7392: #	    $metacache{$uri}={};
                   7393: #	}
1.924     albertel 7394: 	my $cachetime = 60*60;
1.171     www      7395:         if ($liburi) {
                   7396: 	    $liburi=&declutter($liburi);
                   7397:             $filename=$liburi;
1.401     bowersj2 7398:         } else {
1.599     albertel 7399: 	    &devalidate_cache_new('meta',$uri);
                   7400: 	    undef(%metaentry);
1.401     bowersj2 7401: 	}
1.140     www      7402:         my %metathesekeys=();
1.73      www      7403:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7404: 	my $metastring;
1.924     albertel 7405: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7406: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7407: 	    $metastring = 
1.929     albertel 7408: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7409: 					  ('grade_target' => 'meta'));
                   7410: 	    $cachetime = 1; # only want this cached in the child not long term
                   7411: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7412: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7413: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7414: 	    $metastring=&getfile($file);
1.489     albertel 7415: 	}
1.208     albertel 7416:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7417:         my $token;
1.140     www      7418:         undef %metathesekeys;
1.71      www      7419:         while ($token=$parser->get_token) {
1.339     albertel 7420: 	    if ($token->[0] eq 'S') {
                   7421: 		if (defined($token->[2]->{'package'})) {
1.172     www      7422: #
                   7423: # This is a package - get package info
                   7424: #
1.339     albertel 7425: 		    my $package=$token->[2]->{'package'};
                   7426: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7427: 		    if (defined($token->[2]->{'id'})) { 
                   7428: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7429: 		    }
1.599     albertel 7430: 		    if ($metaentry{':packages'}) {
                   7431: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7432: 		    } else {
1.599     albertel 7433: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7434: 		    }
1.736     albertel 7435: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7436: 			my $part=$keyroot;
                   7437: 			$part=~s/^\_//;
1.736     albertel 7438: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7439: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7440: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7441: 			    # ignore package.tab specified default values
                   7442:                             # here &package_tab_default() will fetch those
                   7443: 			    if ($subp eq 'default') { next; }
1.736     albertel 7444: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7445: 			    my $unikey;
                   7446: 			    if ($pack =~ /_0$/) {
                   7447: 				$unikey='parameter_0_'.$name;
                   7448: 				$part=0;
                   7449: 			    } else {
                   7450: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7451: 			    }
1.339     albertel 7452: 			    if ($subp eq 'display') {
                   7453: 				$value.=' [Part: '.$part.']';
                   7454: 			    }
1.599     albertel 7455: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7456: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7457: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7458: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7459: 			    }
1.599     albertel 7460: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7461: 				$metaentry{':'.$unikey}=
                   7462: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7463: 			    }
1.339     albertel 7464: 			}
                   7465: 		    }
                   7466: 		} else {
1.172     www      7467: #
                   7468: # This is not a package - some other kind of start tag
1.339     albertel 7469: #
                   7470: 		    my $entry=$token->[1];
                   7471: 		    my $unikey;
                   7472: 		    if ($entry eq 'import') {
                   7473: 			$unikey='';
                   7474: 		    } else {
                   7475: 			$unikey=$entry;
                   7476: 		    }
                   7477: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7478: 
                   7479: 		    if (defined($token->[2]->{'id'})) { 
                   7480: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7481: 		    }
1.175     www      7482: 
1.339     albertel 7483: 		    if ($entry eq 'import') {
1.175     www      7484: #
                   7485: # Importing a library here
1.339     albertel 7486: #
                   7487: 			if ($depthcount<20) {
                   7488: 			    my $location=$parser->get_text('/import');
                   7489: 			    my $dir=$filename;
                   7490: 			    $dir=~s|[^/]*$||;
                   7491: 			    $location=&filelocation($dir,$location);
1.736     albertel 7492: 			    my $metadata = 
                   7493: 				&metadata($uri,'keys', $location,$unikey,
                   7494: 					  $depthcount+1);
                   7495: 			    foreach my $meta (split(',',$metadata)) {
                   7496: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7497: 				$metathesekeys{$meta}=1;
1.339     albertel 7498: 			    }
                   7499: 			}
                   7500: 		    } else { 
                   7501: 			
                   7502: 			if (defined($token->[2]->{'name'})) { 
                   7503: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7504: 			}
                   7505: 			$metathesekeys{$unikey}=1;
1.736     albertel 7506: 			foreach my $param (@{$token->[3]}) {
                   7507: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7508: 				$token->[2]->{$param};
1.339     albertel 7509: 			}
                   7510: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7511: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7512: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7513: 		 # only ws inside the tag, and not in default, so use default
                   7514: 		 # as value
1.599     albertel 7515: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7516: 			} elsif ( $internaltext =~ /\S/ ) {
                   7517: 		  # something interesting inside the tag
                   7518: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7519: 			} else {
1.908     albertel 7520: 		  # no interesting values, don't set a default
1.339     albertel 7521: 			}
1.172     www      7522: # end of not-a-package not-a-library import
1.339     albertel 7523: 		    }
1.172     www      7524: # end of not-a-package start tag
1.339     albertel 7525: 		}
1.172     www      7526: # the next is the end of "start tag"
1.339     albertel 7527: 	    }
                   7528: 	}
1.483     albertel 7529: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7530: 	$extension = lc($extension);
                   7531: 	if ($extension eq 'htm') { $extension='html'; }
                   7532: 
1.737     albertel 7533: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7534: 	    #no specific packages #how's our extension
                   7535: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7536: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7537: 					 \%metathesekeys);
                   7538: 	}
1.883     albertel 7539: 
                   7540: 	if (!exists($metaentry{':packages'})
                   7541: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7542: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7543: 		#no specific packages well let's get default then
                   7544: 		if ($key!~/^default&/) { next; }
1.488     albertel 7545: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7546: 					     \%metathesekeys);
                   7547: 	    }
                   7548: 	}
1.338     www      7549: # are there custom rights to evaluate
1.599     albertel 7550: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7551: 
1.338     www      7552:     #
                   7553:     # Importing a rights file here
1.339     albertel 7554:     #
                   7555: 	    unless ($depthcount) {
1.599     albertel 7556: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7557: 		my $dir=$filename;
                   7558: 		$dir=~s|[^/]*$||;
                   7559: 		$location=&filelocation($dir,$location);
1.736     albertel 7560: 		my $rights_metadata =
                   7561: 		    &metadata($uri,'keys',$location,'_rights',
                   7562: 			      $depthcount+1);
                   7563: 		foreach my $rights (split(',',$rights_metadata)) {
                   7564: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7565: 		    $metathesekeys{$rights}=1;
1.339     albertel 7566: 		}
                   7567: 	    }
                   7568: 	}
1.737     albertel 7569: 	# uniqifiy package listing
                   7570: 	my %seen;
                   7571: 	my @uniq_packages =
                   7572: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7573: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7574: 
                   7575: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7576: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7577: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7578: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7579: # this is the end of "was not already recently cached
1.71      www      7580:     }
1.599     albertel 7581:     return $metaentry{':'.$what};
1.261     albertel 7582: }
                   7583: 
1.488     albertel 7584: sub metadata_create_package_def {
1.483     albertel 7585:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7586:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7587:     if ($subp eq 'default') { next; }
                   7588:     
1.599     albertel 7589:     if (defined($metaentry{':packages'})) {
                   7590: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7591:     } else {
1.599     albertel 7592: 	$metaentry{':packages'}=$package;
1.483     albertel 7593:     }
                   7594:     my $value=$packagetab{$key};
                   7595:     my $unikey;
                   7596:     $unikey='parameter_0_'.$name;
1.599     albertel 7597:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7598:     $$metathesekeys{$unikey}=1;
1.599     albertel 7599:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7600: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7601:     }
1.599     albertel 7602:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7603: 	$metaentry{':'.$unikey}=
                   7604: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7605:     }
                   7606: }
                   7607: 
1.261     albertel 7608: sub metadata_generate_part0 {
                   7609:     my ($metadata,$metacache,$uri) = @_;
                   7610:     my %allnames;
1.737     albertel 7611:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7612: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7613: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7614: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7615: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7616: 	    $allnames{$name}=$part;
                   7617: 	  }
                   7618: 	}
                   7619:     }
                   7620:     foreach my $name (keys(%allnames)) {
                   7621:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7622:       my $key=":parameter_0_$name";
1.261     albertel 7623:       $$metacache{"$key.part"}='0';
                   7624:       $$metacache{"$key.name"}=$name;
1.428     albertel 7625:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7626: 					   $allnames{$name}.'_'.$name.
                   7627: 					   '.type'};
1.428     albertel 7628:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7629: 			     '.display'};
1.644     www      7630:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7631:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7632:       $$metacache{"$key.display"}=$olddis;
                   7633:     }
1.71      www      7634: }
                   7635: 
1.764     albertel 7636: # ------------------------------------------------------ Devalidate title cache
                   7637: 
                   7638: sub devalidate_title_cache {
                   7639:     my ($url)=@_;
                   7640:     if (!$env{'request.course.id'}) { return; }
                   7641:     my $symb=&symbread($url);
                   7642:     if (!$symb) { return; }
                   7643:     my $key=$env{'request.course.id'}."\0".$symb;
                   7644:     &devalidate_cache_new('title',$key);
                   7645: }
                   7646: 
1.301     www      7647: # ------------------------------------------------- Get the title of a resource
                   7648: 
                   7649: sub gettitle {
                   7650:     my $urlsymb=shift;
                   7651:     my $symb=&symbread($urlsymb);
1.534     albertel 7652:     if ($symb) {
1.620     albertel 7653: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7654: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7655: 	if (defined($cached)) { 
                   7656: 	    return $result;
                   7657: 	}
1.534     albertel 7658: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7659: 	my $title='';
1.907     albertel 7660: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7661: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7662: 	} else {
                   7663: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7664: 		    &GDBM_READER(),0640)) {
                   7665: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7666: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7667: 		untie(%bighash);
                   7668: 	    }
1.534     albertel 7669: 	}
                   7670: 	$title=~s/\&colon\;/\:/gs;
                   7671: 	if ($title) {
1.599     albertel 7672: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7673: 	}
                   7674: 	$urlsymb=$url;
                   7675:     }
                   7676:     my $title=&metadata($urlsymb,'title');
                   7677:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7678:     return $title;
1.301     www      7679: }
1.613     albertel 7680: 
1.614     albertel 7681: sub get_slot {
                   7682:     my ($which,$cnum,$cdom)=@_;
                   7683:     if (!$cnum || !$cdom) {
1.790     albertel 7684: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7685: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7686: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7687:     }
1.703     albertel 7688:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7689:     my %slotinfo;
                   7690:     if (exists($remembered{$key})) {
                   7691: 	$slotinfo{$which} = $remembered{$key};
                   7692:     } else {
                   7693: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7694: 	&Apache::lonhomework::showhash(%slotinfo);
                   7695: 	my ($tmp)=keys(%slotinfo);
                   7696: 	if ($tmp=~/^error:/) { return (); }
                   7697: 	$remembered{$key} = $slotinfo{$which};
                   7698:     }
1.616     albertel 7699:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7700: 	return %{$slotinfo{$which}};
                   7701:     }
                   7702:     return $slotinfo{$which};
1.614     albertel 7703: }
1.31      www      7704: # ------------------------------------------------- Update symbolic store links
                   7705: 
                   7706: sub symblist {
                   7707:     my ($mapname,%newhash)=@_;
1.438     www      7708:     $mapname=&deversion(&declutter($mapname));
1.31      www      7709:     my %hash;
1.620     albertel 7710:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7711:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7712:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7713: 	    foreach my $url (keys %newhash) {
                   7714: 		next if ($url eq 'last_known'
                   7715: 			 && $env{'form.no_update_last_known'});
                   7716: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7717: 						    $newhash{$url}->[1],
                   7718: 						    $newhash{$url}->[0]);
1.191     harris41 7719:             }
1.31      www      7720:             if (untie(%hash)) {
                   7721: 		return 'ok';
                   7722:             }
                   7723:         }
                   7724:     }
                   7725:     return 'error';
1.212     www      7726: }
                   7727: 
                   7728: # --------------------------------------------------------------- Verify a symb
                   7729: 
                   7730: sub symbverify {
1.510     www      7731:     my ($symb,$thisurl)=@_;
                   7732:     my $thisfn=$thisurl;
1.439     www      7733:     $thisfn=&declutter($thisfn);
1.215     www      7734: # direct jump to resource in page or to a sequence - will construct own symbs
                   7735:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7736: # check URL part
1.409     www      7737:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7738: 
1.431     www      7739:     unless ($url eq $thisfn) { return 0; }
1.213     www      7740: 
1.216     www      7741:     $symb=&symbclean($symb);
1.510     www      7742:     $thisurl=&deversion($thisurl);
1.439     www      7743:     $thisfn=&deversion($thisfn);
1.213     www      7744: 
                   7745:     my %bighash;
                   7746:     my $okay=0;
1.431     www      7747: 
1.620     albertel 7748:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7749:                             &GDBM_READER(),0640)) {
1.510     www      7750:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7751:         unless ($ids) { 
1.510     www      7752:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7753:         }
                   7754:         if ($ids) {
                   7755: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7756: 	    foreach my $id (split(/\,/,$ids)) {
                   7757: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7758:                if (
                   7759:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7760:    eq $symb) { 
1.620     albertel 7761: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7762: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7763: 		       $okay=1; 
                   7764: 		   }
                   7765: 	       }
1.216     www      7766: 	   }
                   7767:         }
1.213     www      7768: 	untie(%bighash);
                   7769:     }
                   7770:     return $okay;
1.31      www      7771: }
                   7772: 
1.210     www      7773: # --------------------------------------------------------------- Clean-up symb
                   7774: 
                   7775: sub symbclean {
                   7776:     my $symb=shift;
1.568     albertel 7777:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7778: # remove version from map
                   7779:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7780: 
1.210     www      7781: # remove version from URL
                   7782:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7783: 
1.507     www      7784: # remove wrapper
                   7785: 
1.510     www      7786:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7787:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7788:     return $symb;
1.409     www      7789: }
                   7790: 
                   7791: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7792: 
                   7793: sub encode_symb {
                   7794:     my ($map,$resid,$url)=@_;
                   7795:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7796: }
1.409     www      7797: 
                   7798: sub decode_symb {
1.568     albertel 7799:     my $symb=shift;
                   7800:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7801:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7802:     return (&fixversion($map),$resid,&fixversion($url));
                   7803: }
                   7804: 
                   7805: sub fixversion {
                   7806:     my $fn=shift;
1.609     banghart 7807:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7808:     my %bighash;
                   7809:     my $uri=&clutter($fn);
1.620     albertel 7810:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7811: # is this cached?
1.599     albertel 7812:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7813:     if (defined($cached)) { return $result; }
                   7814: # unfortunately not cached, or expired
1.620     albertel 7815:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7816: 	    &GDBM_READER(),0640)) {
                   7817:  	if ($bighash{'version_'.$uri}) {
                   7818:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7819:  	    unless (($version eq 'mostrecent') || 
                   7820: 		    ($version==&getversion($uri))) {
1.440     www      7821:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7822:  	    }
                   7823:  	}
                   7824:  	untie %bighash;
1.413     www      7825:     }
1.599     albertel 7826:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7827: }
                   7828: 
                   7829: sub deversion {
                   7830:     my $url=shift;
                   7831:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7832:     return $url;
1.210     www      7833: }
                   7834: 
1.31      www      7835: # ------------------------------------------------------ Return symb list entry
                   7836: 
                   7837: sub symbread {
1.249     www      7838:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7839:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7840:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7841: # no filename provided? try from environment
1.44      www      7842:     unless ($thisfn) {
1.620     albertel 7843:         if ($env{'request.symb'}) {
                   7844: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7845: 	}
1.620     albertel 7846: 	$thisfn=$env{'request.filename'};
1.44      www      7847:     }
1.569     albertel 7848:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7849: # is that filename actually a symb? Verify, clean, and return
                   7850:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7851: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7852: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7853: 	}
1.242     www      7854:     }
1.44      www      7855:     $thisfn=declutter($thisfn);
1.31      www      7856:     my %hash;
1.37      www      7857:     my %bighash;
                   7858:     my $syval='';
1.620     albertel 7859:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7860:         my $targetfn = $thisfn;
1.609     banghart 7861:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7862:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7863:         }
1.687     albertel 7864: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7865: 	    $targetfn=$1;
                   7866: 	}
1.620     albertel 7867:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7868:                       &GDBM_READER(),0640)) {
1.481     raeburn  7869: 	    $syval=$hash{$targetfn};
1.37      www      7870:             untie(%hash);
                   7871:         }
                   7872: # ---------------------------------------------------------- There was an entry
                   7873:         if ($syval) {
1.601     albertel 7874: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7875: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7876: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7877: 		    #return $env{$cache_str}='';
1.601     albertel 7878: 		#}    
                   7879: 		#$syval.=$1;
                   7880: 	    #}
1.37      www      7881:         } else {
                   7882: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7883:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7884:                             &GDBM_READER(),0640)) {
1.37      www      7885: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7886:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7887:               unless ($ids) { 
                   7888:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7889:               }
                   7890:               unless ($ids) {
                   7891: # alias?
                   7892: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7893:               }
1.37      www      7894:               if ($ids) {
                   7895: # ------------------------------------------------------------------- Has ID(s)
                   7896:                  my @possibilities=split(/\,/,$ids);
1.39      www      7897:                  if ($#possibilities==0) {
                   7898: # ----------------------------------------------- There is only one possibility
1.37      www      7899: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7900: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7901: 						    $resid,$thisfn);
1.249     www      7902:                  } elsif (!$donotrecurse) {
1.39      www      7903: # ------------------------------------------ There is more than one possibility
                   7904:                      my $realpossible=0;
1.800     albertel 7905:                      foreach my $id (@possibilities) {
                   7906: 			 my $file=$bighash{'src_'.$id};
1.39      www      7907:                          if (&allowed('bre',$file)) {
1.800     albertel 7908:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7909:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7910: 				$realpossible++;
1.626     albertel 7911:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7912: 						    $resid,$thisfn);
1.39      www      7913:                             }
                   7914: 			 }
1.191     harris41 7915:                      }
1.39      www      7916: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7917:                  } else {
                   7918:                      $syval='';
1.37      www      7919:                  }
                   7920: 	      }
                   7921:               untie(%bighash)
1.481     raeburn  7922:            }
1.31      www      7923:         }
1.62      www      7924:         if ($syval) {
1.620     albertel 7925: 	    return $env{$cache_str}=$syval;
1.62      www      7926:         }
1.31      www      7927:     }
1.949     raeburn  7928:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7929:     return $env{$cache_str}='';
1.31      www      7930: }
                   7931: 
                   7932: # ---------------------------------------------------------- Return random seed
                   7933: 
1.32      www      7934: sub numval {
                   7935:     my $txt=shift;
                   7936:     $txt=~tr/A-J/0-9/;
                   7937:     $txt=~tr/a-j/0-9/;
                   7938:     $txt=~tr/K-T/0-9/;
                   7939:     $txt=~tr/k-t/0-9/;
                   7940:     $txt=~tr/U-Z/0-5/;
                   7941:     $txt=~tr/u-z/0-5/;
                   7942:     $txt=~s/\D//g;
1.564     albertel 7943:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7944:     return int($txt);
1.368     albertel 7945: }
                   7946: 
1.484     albertel 7947: sub numval2 {
                   7948:     my $txt=shift;
                   7949:     $txt=~tr/A-J/0-9/;
                   7950:     $txt=~tr/a-j/0-9/;
                   7951:     $txt=~tr/K-T/0-9/;
                   7952:     $txt=~tr/k-t/0-9/;
                   7953:     $txt=~tr/U-Z/0-5/;
                   7954:     $txt=~tr/u-z/0-5/;
                   7955:     $txt=~s/\D//g;
                   7956:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7957:     my $total;
                   7958:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7959:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7960:     return int($total);
                   7961: }
                   7962: 
1.575     albertel 7963: sub numval3 {
                   7964:     use integer;
                   7965:     my $txt=shift;
                   7966:     $txt=~tr/A-J/0-9/;
                   7967:     $txt=~tr/a-j/0-9/;
                   7968:     $txt=~tr/K-T/0-9/;
                   7969:     $txt=~tr/k-t/0-9/;
                   7970:     $txt=~tr/U-Z/0-5/;
                   7971:     $txt=~tr/u-z/0-5/;
                   7972:     $txt=~s/\D//g;
                   7973:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7974:     my $total;
                   7975:     foreach my $val (@txts) { $total+=$val; }
                   7976:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7977:     return $total;
                   7978: }
                   7979: 
1.675     albertel 7980: sub digest {
                   7981:     my ($data)=@_;
                   7982:     my $digest=&Digest::MD5::md5($data);
                   7983:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7984:     my ($e,$f);
                   7985:     {
                   7986:         use integer;
                   7987:         $e=($a+$b);
                   7988:         $f=($c+$d);
                   7989:         if ($_64bit) {
                   7990:             $e=(($e<<32)>>32);
                   7991:             $f=(($f<<32)>>32);
                   7992:         }
                   7993:     }
                   7994:     if (wantarray) {
                   7995: 	return ($e,$f);
                   7996:     } else {
                   7997: 	my $g;
                   7998: 	{
                   7999: 	    use integer;
                   8000: 	    $g=($e+$f);
                   8001: 	    if ($_64bit) {
                   8002: 		$g=(($g<<32)>>32);
                   8003: 	    }
                   8004: 	}
                   8005: 	return $g;
                   8006:     }
                   8007: }
                   8008: 
1.368     albertel 8009: sub latest_rnd_algorithm_id {
1.675     albertel 8010:     return '64bit5';
1.366     albertel 8011: }
1.32      www      8012: 
1.503     albertel 8013: sub get_rand_alg {
                   8014:     my ($courseid)=@_;
1.790     albertel 8015:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8016:     if ($courseid) {
1.620     albertel 8017: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8018:     }
                   8019:     return &latest_rnd_algorithm_id();
                   8020: }
                   8021: 
1.562     albertel 8022: sub validCODE {
                   8023:     my ($CODE)=@_;
                   8024:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8025:     return 0;
                   8026: }
                   8027: 
1.491     albertel 8028: sub getCODE {
1.620     albertel 8029:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8030:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8031: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8032: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8033: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8034:     }
                   8035:     return undef;
                   8036: }
                   8037: 
1.31      www      8038: sub rndseed {
1.155     albertel 8039:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8040:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8041:     if (!defined($symb)) {
1.366     albertel 8042: 	unless ($symb=$wsymb) { return time; }
                   8043:     }
                   8044:     if (!$courseid) { $courseid=$wcourseid; }
                   8045:     if (!$domain) { $domain=$wdomain; }
                   8046:     if (!$username) { $username=$wusername }
1.503     albertel 8047:     my $which=&get_rand_alg();
1.803     albertel 8048: 
1.491     albertel 8049:     if (defined(&getCODE())) {
1.675     albertel 8050: 	if ($which eq '64bit5') {
                   8051: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8052: 	} elsif ($which eq '64bit4') {
1.575     albertel 8053: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8054: 	} else {
                   8055: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8056: 	}
1.675     albertel 8057:     } elsif ($which eq '64bit5') {
                   8058: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8059:     } elsif ($which eq '64bit4') {
                   8060: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8061:     } elsif ($which eq '64bit3') {
                   8062: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8063:     } elsif ($which eq '64bit2') {
                   8064: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8065:     } elsif ($which eq '64bit') {
                   8066: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8067:     }
                   8068:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8069: }
                   8070: 
                   8071: sub rndseed_32bit {
                   8072:     my ($symb,$courseid,$domain,$username)=@_;
                   8073:     {
                   8074: 	use integer;
                   8075: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8076: 	my $symbseed=numval($symb) << 22;
                   8077: 	my $namechck=unpack("%32C*",$username) << 17;
                   8078: 	my $nameseed=numval($username) << 12;
                   8079: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8080: 	my $courseseed=unpack("%32C*",$courseid);
                   8081: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8082: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8083: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8084: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8085: 	return $num;
                   8086:     }
                   8087: }
                   8088: 
                   8089: sub rndseed_64bit {
                   8090:     my ($symb,$courseid,$domain,$username)=@_;
                   8091:     {
                   8092: 	use integer;
                   8093: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8094: 	my $symbseed=numval($symb) << 10;
                   8095: 	my $namechck=unpack("%32S*",$username);
                   8096: 	
                   8097: 	my $nameseed=numval($username) << 21;
                   8098: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8099: 	my $courseseed=unpack("%32S*",$courseid);
                   8100: 	
                   8101: 	my $num1=$symbchck+$symbseed+$namechck;
                   8102: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8103: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8104: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8105: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8106: 	return "$num1,$num2";
1.155     albertel 8107:     }
1.366     albertel 8108: }
                   8109: 
1.443     albertel 8110: sub rndseed_64bit2 {
                   8111:     my ($symb,$courseid,$domain,$username)=@_;
                   8112:     {
                   8113: 	use integer;
                   8114: 	# strings need to be an even # of cahracters long, it it is odd the
                   8115:         # last characters gets thrown away
                   8116: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8117: 	my $symbseed=numval($symb) << 10;
                   8118: 	my $namechck=unpack("%32S*",$username.' ');
                   8119: 	
                   8120: 	my $nameseed=numval($username) << 21;
1.501     albertel 8121: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8122: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8123: 	
                   8124: 	my $num1=$symbchck+$symbseed+$namechck;
                   8125: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8126: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8127: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8128: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8129: 	return "$num1,$num2";
                   8130:     }
                   8131: }
                   8132: 
                   8133: sub rndseed_64bit3 {
                   8134:     my ($symb,$courseid,$domain,$username)=@_;
                   8135:     {
                   8136: 	use integer;
                   8137: 	# strings need to be an even # of cahracters long, it it is odd the
                   8138:         # last characters gets thrown away
                   8139: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8140: 	my $symbseed=numval2($symb) << 10;
                   8141: 	my $namechck=unpack("%32S*",$username.' ');
                   8142: 	
                   8143: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8144: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8145: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8146: 	
                   8147: 	my $num1=$symbchck+$symbseed+$namechck;
                   8148: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8149: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8150: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8151: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8152: 	
1.503     albertel 8153: 	return "$num1:$num2";
1.443     albertel 8154:     }
                   8155: }
                   8156: 
1.575     albertel 8157: sub rndseed_64bit4 {
                   8158:     my ($symb,$courseid,$domain,$username)=@_;
                   8159:     {
                   8160: 	use integer;
                   8161: 	# strings need to be an even # of cahracters long, it it is odd the
                   8162:         # last characters gets thrown away
                   8163: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8164: 	my $symbseed=numval3($symb) << 10;
                   8165: 	my $namechck=unpack("%32S*",$username.' ');
                   8166: 	
                   8167: 	my $nameseed=numval3($username) << 21;
                   8168: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8169: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8170: 	
                   8171: 	my $num1=$symbchck+$symbseed+$namechck;
                   8172: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8173: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8174: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8175: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8176: 	
                   8177: 	return "$num1:$num2";
                   8178:     }
                   8179: }
                   8180: 
1.675     albertel 8181: sub rndseed_64bit5 {
                   8182:     my ($symb,$courseid,$domain,$username)=@_;
                   8183:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8184:     return "$num1:$num2";
                   8185: }
                   8186: 
1.366     albertel 8187: sub rndseed_CODE_64bit {
                   8188:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8189:     {
1.366     albertel 8190: 	use integer;
1.443     albertel 8191: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8192: 	my $symbseed=numval2($symb);
1.491     albertel 8193: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8194: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8195: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8196: 	my $num1=$symbseed+$CODEchck;
                   8197: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8198: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8199: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8200: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8201: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8202: 	return "$num1:$num2";
1.366     albertel 8203:     }
                   8204: }
                   8205: 
1.575     albertel 8206: sub rndseed_CODE_64bit4 {
                   8207:     my ($symb,$courseid,$domain,$username)=@_;
                   8208:     {
                   8209: 	use integer;
                   8210: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8211: 	my $symbseed=numval3($symb);
                   8212: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8213: 	my $CODEseed=numval3(&getCODE());
                   8214: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8215: 	my $num1=$symbseed+$CODEchck;
                   8216: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8217: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8218: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8219: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8220: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8221: 	return "$num1:$num2";
                   8222:     }
                   8223: }
                   8224: 
1.675     albertel 8225: sub rndseed_CODE_64bit5 {
                   8226:     my ($symb,$courseid,$domain,$username)=@_;
                   8227:     my $code = &getCODE();
                   8228:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8229:     return "$num1:$num2";
                   8230: }
                   8231: 
1.366     albertel 8232: sub setup_random_from_rndseed {
                   8233:     my ($rndseed)=@_;
1.503     albertel 8234:     if ($rndseed =~/([,:])/) {
                   8235: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8236: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8237:     } else {
                   8238: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8239:     }
1.36      albertel 8240: }
                   8241: 
1.474     albertel 8242: sub latest_receipt_algorithm_id {
1.835     albertel 8243:     return 'receipt3';
1.474     albertel 8244: }
                   8245: 
1.480     www      8246: sub recunique {
                   8247:     my $fucourseid=shift;
                   8248:     my $unique;
1.835     albertel 8249:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8250: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8251: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8252:     } else {
                   8253: 	$unique=$perlvar{'lonReceipt'};
                   8254:     }
                   8255:     return unpack("%32C*",$unique);
                   8256: }
                   8257: 
                   8258: sub recprefix {
                   8259:     my $fucourseid=shift;
                   8260:     my $prefix;
1.835     albertel 8261:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8262: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8263: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8264:     } else {
                   8265: 	$prefix=$perlvar{'lonHostID'};
                   8266:     }
                   8267:     return unpack("%32C*",$prefix);
                   8268: }
                   8269: 
1.76      www      8270: sub ireceipt {
1.474     albertel 8271:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8272: 
                   8273:     my $return =&recprefix($fucourseid).'-';
                   8274: 
                   8275:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8276: 	$env{'request.state'} eq 'construct') {
                   8277: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8278: 	return $return;
                   8279:     }
                   8280: 
1.76      www      8281:     my $cuname=unpack("%32C*",$funame);
                   8282:     my $cudom=unpack("%32C*",$fudom);
                   8283:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8284:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8285:     my $cunique=&recunique($fucourseid);
1.474     albertel 8286:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8287:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8288: 
1.790     albertel 8289: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8290: 			       
                   8291: 	$return.= ($cunique%$cuname+
                   8292: 		   $cunique%$cudom+
                   8293: 		   $cusymb%$cuname+
                   8294: 		   $cusymb%$cudom+
                   8295: 		   $cucourseid%$cuname+
                   8296: 		   $cucourseid%$cudom+
                   8297: 		   $cpart%$cuname+
                   8298: 		   $cpart%$cudom);
                   8299:     } else {
                   8300: 	$return.= ($cunique%$cuname+
                   8301: 		   $cunique%$cudom+
                   8302: 		   $cusymb%$cuname+
                   8303: 		   $cusymb%$cudom+
                   8304: 		   $cucourseid%$cuname+
                   8305: 		   $cucourseid%$cudom);
                   8306:     }
                   8307:     return $return;
1.76      www      8308: }
                   8309: 
                   8310: sub receipt {
1.474     albertel 8311:     my ($part)=@_;
1.790     albertel 8312:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8313:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8314: }
1.260     ng       8315: 
1.790     albertel 8316: sub whichuser {
                   8317:     my ($passedsymb)=@_;
                   8318:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8319:     if (defined($env{'form.grade_symb'})) {
                   8320: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8321: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8322: 	if (!$allowed &&
                   8323: 	    exists($env{'request.course.sec'}) &&
                   8324: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8325: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8326: 			      '/'.$env{'request.course.sec'});
                   8327: 	}
                   8328: 	if ($allowed) {
                   8329: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8330: 	    $courseid=$tmp_courseid;
                   8331: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8332: 	    ($name)=&get_env_multiple('form.grade_username');
                   8333: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8334: 	}
                   8335:     }
                   8336:     if (!$passedsymb) {
                   8337: 	$symb=&symbread();
                   8338:     } else {
                   8339: 	$symb=$passedsymb;
                   8340:     }
                   8341:     $courseid=$env{'request.course.id'};
                   8342:     $domain=$env{'user.domain'};
                   8343:     $name=$env{'user.name'};
                   8344:     if ($name eq 'public' && $domain eq 'public') {
                   8345: 	if (!defined($env{'form.username'})) {
                   8346: 	    $env{'form.username'}.=time.rand(10000000);
                   8347: 	}
                   8348: 	$name.=$env{'form.username'};
                   8349:     }
                   8350:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8351: 
                   8352: }
                   8353: 
1.36      albertel 8354: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8355: # returns either the contents of the file or 
                   8356: # -1 if the file doesn't exist
1.481     raeburn  8357: #
                   8358: # if the target is a file that was uploaded via DOCS, 
                   8359: # a check will be made to see if a current copy exists on the local server,
                   8360: # if it does this will be served, otherwise a copy will be retrieved from
                   8361: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8362: # the local server.   
1.472     albertel 8363: 
1.36      albertel 8364: sub getfile {
1.538     albertel 8365:     my ($file) = @_;
1.609     banghart 8366:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8367:     &repcopy($file);
                   8368:     return &readfile($file);
                   8369: }
                   8370: 
                   8371: sub repcopy_userfile {
                   8372:     my ($file)=@_;
1.609     banghart 8373:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8374:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8375:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8376: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8377:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8378:     if (-e "$file") {
1.828     www      8379: # we already have a local copy, check it out
1.538     albertel 8380: 	my @fileinfo = stat($file);
1.828     www      8381: 	my $rtncode;
                   8382: 	my $info;
1.538     albertel 8383: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8384: 	if ($lwpresp ne 'ok') {
1.828     www      8385: # there is no such file anymore, even though we had a local copy
1.482     albertel 8386: 	    if ($rtncode eq '404') {
1.538     albertel 8387: 		unlink($file);
1.482     albertel 8388: 	    }
                   8389: 	    return -1;
                   8390: 	}
                   8391: 	if ($info < $fileinfo[9]) {
1.828     www      8392: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8393: 	    return 'ok';
1.828     www      8394: 	} else {
                   8395: # the file is outdated, get rid of it
                   8396: 	    unlink($file);
1.482     albertel 8397: 	}
1.828     www      8398:     }
                   8399: # one way or the other, at this point, we don't have the file
                   8400: # construct the correct path for the file
                   8401:     my @parts = ($cdom,$cnum); 
                   8402:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8403: 	push @parts, split(/\//,$1);
                   8404:     }
                   8405:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8406:     foreach my $part (@parts) {
                   8407: 	$path .= '/'.$part;
                   8408: 	if (!-e $path) {
                   8409: 	    mkdir($path,0770);
1.482     albertel 8410: 	}
                   8411:     }
1.828     www      8412: # now the path exists for sure
                   8413: # get a user agent
                   8414:     my $ua=new LWP::UserAgent;
                   8415:     my $transferfile=$file.'.in.transfer';
                   8416: # FIXME: this should flock
                   8417:     if (-e $transferfile) { return 'ok'; }
                   8418:     my $request;
                   8419:     $uri=~s/^\///;
1.980     raeburn  8420:     my $homeserver = &homeserver($cnum,$cdom);
                   8421:     my $protocol = $protocol{$homeserver};
                   8422:     $protocol = 'http' if ($protocol ne 'https');
                   8423:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8424:     my $response=$ua->request($request,$transferfile);
                   8425: # did it work?
                   8426:     if ($response->is_error()) {
                   8427: 	unlink($transferfile);
                   8428: 	&logthis("Userfile repcopy failed for $uri");
                   8429: 	return -1;
                   8430:     }
                   8431: # worked, rename the transfer file
                   8432:     rename($transferfile,$file);
1.607     raeburn  8433:     return 'ok';
1.481     raeburn  8434: }
                   8435: 
1.517     albertel 8436: sub tokenwrapper {
                   8437:     my $uri=shift;
1.980     raeburn  8438:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8439:     $uri=~s|^/||;
1.620     albertel 8440:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8441:     my $token=$1;
1.552     albertel 8442:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8443:     if ($udom && $uname && $file) {
                   8444: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8445:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8446:         my $homeserver = &homeserver($uname,$udom);
                   8447:         my $protocol = $protocol{$homeserver};
                   8448:         $protocol = 'http' if ($protocol ne 'https');
                   8449:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8450:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8451:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8452:     } else {
                   8453:         return '/adm/notfound.html';
                   8454:     }
                   8455: }
                   8456: 
1.828     www      8457: # call with reqtype HEAD: get last modification time
                   8458: # call with reqtype GET: get the file contents
                   8459: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8460: #
1.481     raeburn  8461: sub getuploaded {
                   8462:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8463:     $uri=~s/^\///;
1.980     raeburn  8464:     my $homeserver = &homeserver($cnum,$cdom);
                   8465:     my $protocol = $protocol{$homeserver};
                   8466:     $protocol = 'http' if ($protocol ne 'https');
                   8467:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8468:     my $ua=new LWP::UserAgent;
                   8469:     my $request=new HTTP::Request($reqtype,$uri);
                   8470:     my $response=$ua->request($request);
                   8471:     $$rtncode = $response->code;
1.482     albertel 8472:     if (! $response->is_success()) {
                   8473: 	return 'failed';
                   8474:     }      
                   8475:     if ($reqtype eq 'HEAD') {
1.486     www      8476: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8477:     } elsif ($reqtype eq 'GET') {
                   8478: 	$$info = $response->content;
1.472     albertel 8479:     }
1.482     albertel 8480:     return 'ok';
1.36      albertel 8481: }
                   8482: 
1.481     raeburn  8483: sub readfile {
                   8484:     my $file = shift;
                   8485:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8486:     my $fh;
                   8487:     open($fh,"<$file");
                   8488:     my $a='';
1.800     albertel 8489:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8490:     return $a;
                   8491: }
                   8492: 
1.36      albertel 8493: sub filelocation {
1.590     banghart 8494:     my ($dir,$file) = @_;
                   8495:     my $location;
                   8496:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8497: 
                   8498:     if ($file =~ m-^/adm/-) {
                   8499: 	$file=~s-^/adm/wrapper/-/-;
                   8500: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8501:     }
1.882     albertel 8502: 
1.590     banghart 8503:     if ($file=~m:^/~:) { # is a contruction space reference
                   8504:         $location = $file;
                   8505:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8506:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8507: 	# is a correct contruction space reference
                   8508:         $location = $file;
1.956     raeburn  8509:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8510:         $location = $file;
1.609     banghart 8511:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8512:         my ($udom,$uname,$filename)=
1.811     albertel 8513:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8514:         my $home=&homeserver($uname,$udom);
                   8515:         my $is_me=0;
                   8516:         my @ids=&current_machine_ids();
                   8517:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8518:         if ($is_me) {
1.955     raeburn  8519:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8520:         } else {
                   8521:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8522:   	      $udom.'/'.$uname.'/'.$filename;
                   8523:         }
1.882     albertel 8524:     } elsif ($file =~ m-^/adm/-) {
                   8525: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8526:     } else {
                   8527:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8528:         $file=~s:^/res/:/:;
                   8529:         if ( !( $file =~ m:^/:) ) {
                   8530:             $location = $dir. '/'.$file;
                   8531:         } else {
                   8532:             $location = '/home/httpd/html/res'.$file;
                   8533:         }
1.59      albertel 8534:     }
1.590     banghart 8535:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8536:     while ($location=~m{/\.\./}) {
                   8537: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8538: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8539: 	} else {
                   8540: 	    $location=~ s{/\.\./}{/}g;
                   8541: 	}
                   8542:     } #remove dir/..
1.590     banghart 8543:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8544:     return $location;
1.46      www      8545: }
1.36      albertel 8546: 
1.46      www      8547: sub hreflocation {
                   8548:     my ($dir,$file)=@_;
1.980     raeburn  8549:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8550: 	$file=filelocation($dir,$file);
1.700     albertel 8551:     } elsif ($file=~m-^/adm/-) {
                   8552: 	$file=~s-^/adm/wrapper/-/-;
                   8553: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8554:     }
                   8555:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8556: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8557:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8558: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8559:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8560: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8561: 	    -/uploaded/$1/$2/-x;
1.46      www      8562:     }
1.913     albertel 8563:     if ($file=~ m{^/userfiles/}) {
                   8564: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8565:     }
1.462     albertel 8566:     return $file;
1.465     albertel 8567: }
                   8568: 
                   8569: sub current_machine_domains {
1.853     albertel 8570:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8571: }
                   8572: 
                   8573: sub machine_domains {
                   8574:     my ($hostname) = @_;
1.465     albertel 8575:     my @domains;
1.838     albertel 8576:     my %hostname = &all_hostnames();
1.465     albertel 8577:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8578: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8579: 	if ($hostname eq $name) {
1.844     albertel 8580: 	    push(@domains,&host_domain($id));
1.465     albertel 8581: 	}
                   8582:     }
                   8583:     return @domains;
                   8584: }
                   8585: 
                   8586: sub current_machine_ids {
1.853     albertel 8587:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8588: }
                   8589: 
                   8590: sub machine_ids {
                   8591:     my ($hostname) = @_;
                   8592:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8593:     my @ids;
1.888     albertel 8594:     my %name_to_host = &all_names();
1.889     albertel 8595:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8596: 	return @{ $name_to_host{$hostname} };
                   8597:     }
                   8598:     return;
1.31      www      8599: }
                   8600: 
1.824     raeburn  8601: sub additional_machine_domains {
                   8602:     my @domains;
                   8603:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8604:     while( my $line = <$fh>) {
                   8605:         $line =~ s/\s//g;
                   8606:         push(@domains,$line);
                   8607:     }
                   8608:     return @domains;
                   8609: }
                   8610: 
                   8611: sub default_login_domain {
                   8612:     my $domain = $perlvar{'lonDefDomain'};
                   8613:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8614:     foreach my $posdom (&current_machine_domains(),
                   8615:                         &additional_machine_domains()) {
                   8616:         if (lc($posdom) eq lc($testdomain)) {
                   8617:             $domain=$posdom;
                   8618:             last;
                   8619:         }
                   8620:     }
                   8621:     return $domain;
                   8622: }
                   8623: 
1.31      www      8624: # ------------------------------------------------------------- Declutters URLs
                   8625: 
                   8626: sub declutter {
                   8627:     my $thisfn=shift;
1.569     albertel 8628:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8629:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8630:     $thisfn=~s/^\///;
1.697     albertel 8631:     $thisfn=~s|^adm/wrapper/||;
                   8632:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8633:     $thisfn=~s/^res\///;
1.235     www      8634:     $thisfn=~s/\?.+$//;
1.268     www      8635:     return $thisfn;
                   8636: }
                   8637: 
                   8638: # ------------------------------------------------------------- Clutter up URLs
                   8639: 
                   8640: sub clutter {
                   8641:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8642:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8643: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8644:        $thisfn='/res'.$thisfn; 
                   8645:     }
1.694     albertel 8646:     if ($thisfn !~m|/adm|) {
1.695     albertel 8647: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8648: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8649: 	} else {
                   8650: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8651: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8652: 	    if ($embstyle eq 'ssi'
                   8653: 		|| ($embstyle eq 'hdn')
                   8654: 		|| ($embstyle eq 'rat')
                   8655: 		|| ($embstyle eq 'prv')
                   8656: 		|| ($embstyle eq 'ign')) {
                   8657: 		#do nothing with these
                   8658: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8659: 		|| ($embstyle eq 'emb')
                   8660: 		|| ($embstyle eq 'wrp')) {
                   8661: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8662: 	    } elsif ($embstyle eq 'unk'
                   8663: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8664: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8665: 	    } else {
1.718     www      8666: #		&logthis("Got a blank emb style");
1.695     albertel 8667: 	    }
1.694     albertel 8668: 	}
                   8669:     }
1.31      www      8670:     return $thisfn;
1.12      www      8671: }
                   8672: 
1.787     albertel 8673: sub clutter_with_no_wrapper {
                   8674:     my $uri = &clutter(shift);
                   8675:     if ($uri =~ m-^/adm/-) {
                   8676: 	$uri =~ s-^/adm/wrapper/-/-;
                   8677: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8678:     }
                   8679:     return $uri;
                   8680: }
                   8681: 
1.557     albertel 8682: sub freeze_escape {
                   8683:     my ($value)=@_;
                   8684:     if (ref($value)) {
                   8685: 	$value=&nfreeze($value);
                   8686: 	return '__FROZEN__'.&escape($value);
                   8687:     }
                   8688:     return &escape($value);
                   8689: }
                   8690: 
1.11      www      8691: 
1.557     albertel 8692: sub thaw_unescape {
                   8693:     my ($value)=@_;
                   8694:     if ($value =~ /^__FROZEN__/) {
                   8695: 	substr($value,0,10,undef);
                   8696: 	$value=&unescape($value);
                   8697: 	return &thaw($value);
                   8698:     }
                   8699:     return &unescape($value);
                   8700: }
                   8701: 
1.436     albertel 8702: sub correct_line_ends {
                   8703:     my ($result)=@_;
                   8704:     $$result =~s/\r\n/\n/mg;
                   8705:     $$result =~s/\r/\n/mg;
1.415     albertel 8706: }
1.1       albertel 8707: # ================================================================ Main Program
                   8708: 
1.184     www      8709: sub goodbye {
1.204     albertel 8710:    &logthis("Starting Shut down");
1.443     albertel 8711: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8712:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8713: #converted
1.599     albertel 8714: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8715:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8716: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8717: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8718: #1.1 only
1.870     albertel 8719: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8720: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8721: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8722: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8723:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8724:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8725:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8726:    &flushcourselogs();
                   8727:    &logthis("Shutting down");
                   8728: }
                   8729: 
1.852     albertel 8730: sub get_dns {
1.869     albertel 8731:     my ($url,$func,$ignore_cache) = @_;
                   8732:     if (!$ignore_cache) {
                   8733: 	my ($content,$cached)=
                   8734: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8735: 	if ($cached) {
                   8736: 	    &$func($content);
                   8737: 	    return;
                   8738: 	}
                   8739:     }
                   8740: 
                   8741:     my %alldns;
1.852     albertel 8742:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8743:     foreach my $dns (<$config>) {
                   8744: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8745:         my $line = $1;
                   8746:         my ($host,$protocol) = split(/:/,$line);
                   8747:         if ($protocol ne 'https') {
                   8748:             $protocol = 'http';
                   8749:         }
                   8750: 	$alldns{$host} = $protocol;
1.869     albertel 8751:     }
                   8752:     while (%alldns) {
                   8753: 	my ($dns) = keys(%alldns);
1.852     albertel 8754: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8755: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8756: 	my $response=$ua->request($request);
1.979     raeburn  8757:         delete($alldns{$dns});
1.852     albertel 8758: 	next if ($response->is_error());
                   8759: 	my @content = split("\n",$response->content);
1.869     albertel 8760: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8761: 	&$func(\@content);
1.869     albertel 8762: 	return;
1.852     albertel 8763:     }
                   8764:     close($config);
1.871     albertel 8765:     my $which = (split('/',$url))[3];
                   8766:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8767:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8768:     my @content = <$config>;
                   8769:     &$func(\@content);
                   8770:     return;
1.852     albertel 8771: }
1.327     albertel 8772: # ------------------------------------------------------------ Read domain file
                   8773: {
1.852     albertel 8774:     my $loaded;
1.846     albertel 8775:     my %domain;
                   8776: 
1.852     albertel 8777:     sub parse_domain_tab {
                   8778: 	my ($lines) = @_;
                   8779: 	foreach my $line (@$lines) {
                   8780: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8781: 
1.846     albertel 8782: 	    chomp($line);
1.852     albertel 8783: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8784: 	    my %this_domain;
                   8785: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8786: 			       'lang_def', 'city', 'longi', 'lati',
                   8787: 			       'primary') {
                   8788: 		$this_domain{$field} = shift(@elements);
                   8789: 	    }
                   8790: 	    $domain{$name} = \%this_domain;
1.852     albertel 8791: 	}
                   8792:     }
1.864     albertel 8793: 
                   8794:     sub reset_domain_info {
                   8795: 	undef($loaded);
                   8796: 	undef(%domain);
                   8797:     }
                   8798: 
1.852     albertel 8799:     sub load_domain_tab {
1.869     albertel 8800: 	my ($ignore_cache) = @_;
                   8801: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8802: 	my $fh;
                   8803: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8804: 	    my @lines = <$fh>;
                   8805: 	    &parse_domain_tab(\@lines);
1.448     albertel 8806: 	}
1.852     albertel 8807: 	close($fh);
                   8808: 	$loaded = 1;
1.327     albertel 8809:     }
1.846     albertel 8810: 
                   8811:     sub domain {
1.852     albertel 8812: 	&load_domain_tab() if (!$loaded);
                   8813: 
1.846     albertel 8814: 	my ($name,$what) = @_;
                   8815: 	return if ( !exists($domain{$name}) );
                   8816: 
                   8817: 	if (!$what) {
                   8818: 	    return $domain{$name}{'description'};
                   8819: 	}
                   8820: 	return $domain{$name}{$what};
                   8821:     }
1.974     raeburn  8822: 
                   8823:     sub domain_info {
                   8824:         &load_domain_tab() if (!$loaded);
                   8825:         return %domain;
                   8826:     }
                   8827: 
1.327     albertel 8828: }
                   8829: 
                   8830: 
1.1       albertel 8831: # ------------------------------------------------------------- Read hosts file
                   8832: {
1.838     albertel 8833:     my %hostname;
1.844     albertel 8834:     my %hostdom;
1.845     albertel 8835:     my %libserv;
1.852     albertel 8836:     my $loaded;
1.888     albertel 8837:     my %name_to_host;
1.852     albertel 8838: 
                   8839:     sub parse_hosts_tab {
                   8840: 	my ($file) = @_;
                   8841: 	foreach my $configline (@$file) {
                   8842: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8843: 	    next if ($configline =~ /^\^/);
                   8844: 	    chomp($configline);
1.968     raeburn  8845: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8846: 	    $name=~s/\s//g;
                   8847: 	    if ($id && $domain && $role && $name) {
                   8848: 		$hostname{$id}=$name;
1.888     albertel 8849: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8850: 		$hostdom{$id}=$domain;
                   8851: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8852:                 if (defined($protocol)) {
                   8853:                     if ($protocol eq 'https') {
                   8854:                         $protocol{$id} = $protocol;
                   8855:                     } else {
                   8856:                         $protocol{$id} = 'http'; 
                   8857:                     }
1.968     raeburn  8858:                 } else {
1.969     raeburn  8859:                     $protocol{$id} = 'http';
1.968     raeburn  8860:                 }
1.852     albertel 8861: 	    }
                   8862: 	}
                   8863:     }
1.864     albertel 8864:     
                   8865:     sub reset_hosts_info {
1.897     albertel 8866: 	&purge_remembered();
1.864     albertel 8867: 	&reset_domain_info();
                   8868: 	&reset_hosts_ip_info();
1.892     albertel 8869: 	undef(%name_to_host);
1.864     albertel 8870: 	undef(%hostname);
                   8871: 	undef(%hostdom);
                   8872: 	undef(%libserv);
                   8873: 	undef($loaded);
                   8874:     }
1.1       albertel 8875: 
1.852     albertel 8876:     sub load_hosts_tab {
1.869     albertel 8877: 	my ($ignore_cache) = @_;
                   8878: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8879: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8880: 	my @config = <$config>;
                   8881: 	&parse_hosts_tab(\@config);
                   8882: 	close($config);
                   8883: 	$loaded=1;
1.1       albertel 8884:     }
1.852     albertel 8885: 
1.838     albertel 8886:     sub hostname {
1.852     albertel 8887: 	&load_hosts_tab() if (!$loaded);
                   8888: 
1.838     albertel 8889: 	my ($lonid) = @_;
                   8890: 	return $hostname{$lonid};
                   8891:     }
1.845     albertel 8892: 
1.838     albertel 8893:     sub all_hostnames {
1.852     albertel 8894: 	&load_hosts_tab() if (!$loaded);
                   8895: 
1.838     albertel 8896: 	return %hostname;
                   8897:     }
1.845     albertel 8898: 
1.888     albertel 8899:     sub all_names {
                   8900: 	&load_hosts_tab() if (!$loaded);
                   8901: 
                   8902: 	return %name_to_host;
                   8903:     }
                   8904: 
1.974     raeburn  8905:     sub all_host_domain {
                   8906:         &load_hosts_tab() if (!$loaded);
                   8907:         return %hostdom;
                   8908:     }
                   8909: 
1.845     albertel 8910:     sub is_library {
1.852     albertel 8911: 	&load_hosts_tab() if (!$loaded);
                   8912: 
1.845     albertel 8913: 	return exists($libserv{$_[0]});
                   8914:     }
                   8915: 
                   8916:     sub all_library {
1.852     albertel 8917: 	&load_hosts_tab() if (!$loaded);
                   8918: 
1.845     albertel 8919: 	return %libserv;
                   8920:     }
                   8921: 
1.841     albertel 8922:     sub get_servers {
1.852     albertel 8923: 	&load_hosts_tab() if (!$loaded);
                   8924: 
1.841     albertel 8925: 	my ($domain,$type) = @_;
                   8926: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8927: 	                                          : %hostname;
                   8928: 	my %result;
1.842     albertel 8929: 	if (ref($domain) eq 'ARRAY') {
                   8930: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8931: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8932: 		    $result{$host} = $hostname;
                   8933: 		}
                   8934: 	    }
                   8935: 	} else {
                   8936: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8937: 		if ($hostdom{$host} eq $domain) {
                   8938: 		    $result{$host} = $hostname;
                   8939: 		}
1.841     albertel 8940: 	    }
                   8941: 	}
                   8942: 	return %result;
                   8943:     }
1.845     albertel 8944: 
1.844     albertel 8945:     sub host_domain {
1.852     albertel 8946: 	&load_hosts_tab() if (!$loaded);
                   8947: 
1.844     albertel 8948: 	my ($lonid) = @_;
                   8949: 	return $hostdom{$lonid};
                   8950:     }
                   8951: 
1.841     albertel 8952:     sub all_domains {
1.852     albertel 8953: 	&load_hosts_tab() if (!$loaded);
                   8954: 
1.841     albertel 8955: 	my %seen;
                   8956: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8957: 	return @uniq;
                   8958:     }
1.1       albertel 8959: }
                   8960: 
1.847     albertel 8961: { 
                   8962:     my %iphost;
1.856     albertel 8963:     my %name_to_ip;
                   8964:     my %lonid_to_ip;
1.869     albertel 8965: 
1.847     albertel 8966:     sub get_hosts_from_ip {
                   8967: 	my ($ip) = @_;
                   8968: 	my %iphosts = &get_iphost();
                   8969: 	if (ref($iphosts{$ip})) {
                   8970: 	    return @{$iphosts{$ip}};
                   8971: 	}
                   8972: 	return;
1.839     albertel 8973:     }
1.864     albertel 8974:     
                   8975:     sub reset_hosts_ip_info {
                   8976: 	undef(%iphost);
                   8977: 	undef(%name_to_ip);
                   8978: 	undef(%lonid_to_ip);
                   8979:     }
1.856     albertel 8980: 
                   8981:     sub get_host_ip {
                   8982: 	my ($lonid) = @_;
                   8983: 	if (exists($lonid_to_ip{$lonid})) {
                   8984: 	    return $lonid_to_ip{$lonid};
                   8985: 	}
                   8986: 	my $name=&hostname($lonid);
                   8987:    	my $ip = gethostbyname($name);
                   8988: 	return if (!$ip || length($ip) ne 4);
                   8989: 	$ip=inet_ntoa($ip);
                   8990: 	$name_to_ip{$name}   = $ip;
                   8991: 	$lonid_to_ip{$lonid} = $ip;
                   8992: 	return $ip;
                   8993:     }
1.847     albertel 8994:     
                   8995:     sub get_iphost {
1.869     albertel 8996: 	my ($ignore_cache) = @_;
1.894     albertel 8997: 
1.869     albertel 8998: 	if (!$ignore_cache) {
                   8999: 	    if (%iphost) {
                   9000: 		return %iphost;
                   9001: 	    }
                   9002: 	    my ($ip_info,$cached)=
                   9003: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9004: 	    if ($cached) {
                   9005: 		%iphost      = %{$ip_info->[0]};
                   9006: 		%name_to_ip  = %{$ip_info->[1]};
                   9007: 		%lonid_to_ip = %{$ip_info->[2]};
                   9008: 		return %iphost;
                   9009: 	    }
                   9010: 	}
1.894     albertel 9011: 
                   9012: 	# get yesterday's info for fallback
                   9013: 	my %old_name_to_ip;
                   9014: 	my ($ip_info,$cached)=
                   9015: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9016: 	if ($cached) {
                   9017: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9018: 	}
                   9019: 
1.888     albertel 9020: 	my %name_to_host = &all_names();
                   9021: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9022: 	    my $ip;
                   9023: 	    if (!exists($name_to_ip{$name})) {
                   9024: 		$ip = gethostbyname($name);
                   9025: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9026: 		    if (defined($old_name_to_ip{$name})) {
                   9027: 			$ip = $old_name_to_ip{$name};
                   9028: 			&logthis("Can't find $name defaulting to old $ip");
                   9029: 		    } else {
                   9030: 			&logthis("Name $name no IP found");
                   9031: 			next;
                   9032: 		    }
                   9033: 		} else {
                   9034: 		    $ip=inet_ntoa($ip);
1.847     albertel 9035: 		}
                   9036: 		$name_to_ip{$name} = $ip;
                   9037: 	    } else {
                   9038: 		$ip = $name_to_ip{$name};
1.653     albertel 9039: 	    }
1.888     albertel 9040: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9041: 		$lonid_to_ip{$id} = $ip;
                   9042: 	    }
                   9043: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9044: 	}
1.869     albertel 9045: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9046: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9047: 				      48*60*60);
1.869     albertel 9048: 
1.847     albertel 9049: 	return %iphost;
1.598     albertel 9050:     }
                   9051: }
                   9052: 
1.986     foxr     9053: #
                   9054: #  Given a DNS returns the loncapa host name for that DNS 
                   9055: # 
                   9056: sub host_from_dns {
                   9057:     my ($dns) = @_;
                   9058:     my @hosts;
                   9059:     my $ip;
                   9060: 
                   9061:     $ip = gethostbyname($dns);	# Initial translation to IP is in net order.
                   9062:     if (length($ip) == 4) { 
                   9063: 	$ip   = &IO::Socket::inet_ntoa($ip);
                   9064: 	@hosts = get_hosts_from_ip($ip);
                   9065: 	return $hosts[0];
                   9066:     }
                   9067:     return undef;
                   9068: }
                   9069: 
1.862     albertel 9070: BEGIN {
                   9071: 
                   9072: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9073:     unless ($readit) {
                   9074: {
                   9075:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9076:     %perlvar = (%perlvar,%{$configvars});
                   9077: }
                   9078: 
                   9079: 
1.1       albertel 9080: # ------------------------------------------------------ Read spare server file
                   9081: {
1.448     albertel 9082:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9083: 
                   9084:     while (my $configline=<$config>) {
                   9085:        chomp($configline);
1.284     matthew  9086:        if ($configline) {
1.784     albertel 9087: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9088: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9089: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9090:        }
                   9091:     }
1.448     albertel 9092:     close($config);
1.1       albertel 9093: }
1.11      www      9094: # ------------------------------------------------------------ Read permissions
                   9095: {
1.448     albertel 9096:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9097: 
                   9098:     while (my $configline=<$config>) {
1.448     albertel 9099: 	chomp($configline);
                   9100: 	if ($configline) {
                   9101: 	    my ($role,$perm)=split(/ /,$configline);
                   9102: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9103: 	}
1.11      www      9104:     }
1.448     albertel 9105:     close($config);
1.11      www      9106: }
                   9107: 
                   9108: # -------------------------------------------- Read plain texts for permissions
                   9109: {
1.448     albertel 9110:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9111: 
                   9112:     while (my $configline=<$config>) {
1.448     albertel 9113: 	chomp($configline);
                   9114: 	if ($configline) {
1.742     raeburn  9115: 	    my ($short,@plain)=split(/:/,$configline);
                   9116:             %{$prp{$short}} = ();
                   9117: 	    if (@plain > 0) {
                   9118:                 $prp{$short}{'std'} = $plain[0];
                   9119:                 for (my $i=1; $i<@plain; $i++) {
                   9120:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9121:                 }
                   9122:             }
1.448     albertel 9123: 	}
1.135     www      9124:     }
1.448     albertel 9125:     close($config);
1.135     www      9126: }
                   9127: 
                   9128: # ---------------------------------------------------------- Read package table
                   9129: {
1.448     albertel 9130:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9131: 
                   9132:     while (my $configline=<$config>) {
1.483     albertel 9133: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9134: 	chomp($configline);
                   9135: 	my ($short,$plain)=split(/:/,$configline);
                   9136: 	my ($pack,$name)=split(/\&/,$short);
                   9137: 	if ($plain ne '') {
                   9138: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9139: 	    $packagetab{$short}=$plain; 
                   9140: 	}
1.11      www      9141:     }
1.448     albertel 9142:     close($config);
1.329     matthew  9143: }
                   9144: 
                   9145: # ------------- set up temporary directory
                   9146: {
                   9147:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9148: 
1.11      www      9149: }
                   9150: 
1.794     albertel 9151: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9152: 				'compress_threshold'=> 20_000,
                   9153:  			        });
1.185     www      9154: 
1.281     www      9155: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9156: $dumpcount=0;
1.958     www      9157: $locknum=0;
1.22      www      9158: 
1.163     harris41 9159: &logtouch();
1.672     albertel 9160: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9161: $readit=1;
1.564     albertel 9162:     {
                   9163: 	use integer;
                   9164: 	my $test=(2**32)+1;
1.568     albertel 9165: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9166: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9167:     }
1.195     www      9168: }
1.1       albertel 9169: }
1.179     www      9170: 
1.1       albertel 9171: 1;
1.191     harris41 9172: __END__
                   9173: 
1.243     albertel 9174: =pod
                   9175: 
1.191     harris41 9176: =head1 NAME
                   9177: 
1.243     albertel 9178: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9179: 
                   9180: =head1 SYNOPSIS
                   9181: 
1.243     albertel 9182: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9183: 
                   9184:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9185: 
1.243     albertel 9186: Common parameters:
                   9187: 
                   9188: =over 4
                   9189: 
                   9190: =item *
                   9191: 
                   9192: $uname : an internal username (if $cname expecting a course Id specifically)
                   9193: 
                   9194: =item *
                   9195: 
                   9196: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9197: 
                   9198: =item *
                   9199: 
                   9200: $symb : a resource instance identifier
                   9201: 
                   9202: =item *
                   9203: 
                   9204: $namespace : the name of a .db file that contains the data needed or
                   9205: being set.
                   9206: 
                   9207: =back
                   9208: 
1.394     bowersj2 9209: =head1 OVERVIEW
1.191     harris41 9210: 
1.394     bowersj2 9211: lonnet provides subroutines which interact with the
                   9212: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9213: about classes, users, and resources.
1.243     albertel 9214: 
                   9215: For many of these objects you can also use this to store data about
                   9216: them or modify them in various ways.
1.191     harris41 9217: 
1.394     bowersj2 9218: =head2 Symbs
1.191     harris41 9219: 
1.394     bowersj2 9220: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9221: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9222: map, the resource number of the resource in the map, and the URL of
                   9223: the resource itself. The latter is somewhat redundant, but might help
                   9224: if maps change.
                   9225: 
                   9226: An example is
                   9227: 
                   9228:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9229: 
                   9230: The respective map entry is
                   9231: 
                   9232:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9233:   title="Problem 2">
                   9234:  </resource>
                   9235: 
                   9236: Symbs are used by the random number generator, as well as to store and
                   9237: restore data specific to a certain instance of for example a problem.
                   9238: 
                   9239: =head2 Storing And Retrieving Data
                   9240: 
                   9241: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9242: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9243: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9244: is is the non-critical message twin of cstore. These functions are for
                   9245: handlers to store a perl hash to a user's permanent data space in an
                   9246: easy manner, and to retrieve it again on another call. It is expected
                   9247: that a handler would use this once at the beginning to retrieve data,
                   9248: and then again once at the end to send only the new data back.
                   9249: 
                   9250: The data is stored in the user's data directory on the user's
                   9251: homeserver under the ID of the course.
                   9252: 
                   9253: The hash that is returned by restore will have all of the previous
                   9254: value for all of the elements of the hash.
                   9255: 
                   9256: Example:
                   9257: 
                   9258:  #creating a hash
                   9259:  my %hash;
                   9260:  $hash{'foo'}='bar';
                   9261: 
                   9262:  #storing it
                   9263:  &Apache::lonnet::cstore(\%hash);
                   9264: 
                   9265:  #changing a value
                   9266:  $hash{'foo'}='notbar';
                   9267: 
                   9268:  #adding a new value
                   9269:  $hash{'bar'}='foo';
                   9270:  &Apache::lonnet::cstore(\%hash);
                   9271: 
                   9272:  #retrieving the hash
                   9273:  my %history=&Apache::lonnet::restore();
                   9274: 
                   9275:  #print the hash
                   9276:  foreach my $key (sort(keys(%history))) {
                   9277:    print("\%history{$key} = $history{$key}");
                   9278:  }
                   9279: 
                   9280: Will print out:
1.191     harris41 9281: 
1.394     bowersj2 9282:  %history{1:foo} = bar
                   9283:  %history{1:keys} = foo:timestamp
                   9284:  %history{1:timestamp} = 990455579
                   9285:  %history{2:bar} = foo
                   9286:  %history{2:foo} = notbar
                   9287:  %history{2:keys} = foo:bar:timestamp
                   9288:  %history{2:timestamp} = 990455580
                   9289:  %history{bar} = foo
                   9290:  %history{foo} = notbar
                   9291:  %history{timestamp} = 990455580
                   9292:  %history{version} = 2
                   9293: 
                   9294: Note that the special hash entries C<keys>, C<version> and
                   9295: C<timestamp> were added to the hash. C<version> will be equal to the
                   9296: total number of versions of the data that have been stored. The
                   9297: C<timestamp> attribute will be the UNIX time the hash was
                   9298: stored. C<keys> is available in every historical section to list which
                   9299: keys were added or changed at a specific historical revision of a
                   9300: hash.
                   9301: 
                   9302: B<Warning>: do not store the hash that restore returns directly. This
                   9303: will cause a mess since it will restore the historical keys as if the
                   9304: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9305: 
1.394     bowersj2 9306: Calling convention:
1.191     harris41 9307: 
1.394     bowersj2 9308:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9309:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9310: 
1.394     bowersj2 9311: For more detailed information, see lonnet specific documentation.
1.191     harris41 9312: 
1.394     bowersj2 9313: =head1 RETURN MESSAGES
1.191     harris41 9314: 
1.394     bowersj2 9315: =over 4
1.191     harris41 9316: 
1.394     bowersj2 9317: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9318: 
1.394     bowersj2 9319: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9320: when the connection is brought back up
1.191     harris41 9321: 
1.394     bowersj2 9322: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9323: for later delivery
1.191     harris41 9324: 
1.967     bisitz   9325: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9326: 
1.394     bowersj2 9327: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9328: that was requested
1.191     harris41 9329: 
1.243     albertel 9330: =back
1.191     harris41 9331: 
1.243     albertel 9332: =head1 PUBLIC SUBROUTINES
1.191     harris41 9333: 
1.243     albertel 9334: =head2 Session Environment Functions
1.191     harris41 9335: 
1.243     albertel 9336: =over 4
1.191     harris41 9337: 
1.394     bowersj2 9338: =item * 
                   9339: X<appenv()>
1.949     raeburn  9340: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9341: the user envirnoment file, and will be restored for each access this
1.620     albertel 9342: user makes during this session, also modifies the %env for the current
1.949     raeburn  9343: process. Optional rolesarrayref - if defined contains a reference to an array
                   9344: of roles which are exempt from the restriction on modifying user.role entries 
                   9345: in the user's environment.db and in %env.    
1.191     harris41 9346: 
                   9347: =item *
1.394     bowersj2 9348: X<delenv()>
1.987     raeburn  9349: B<delenv($delthis,$regexp)>: removes all items from the session
                   9350: environment file that begin with $delthis. If the 
                   9351: optional second arg - $regexp - is true, $delthis is treated as a 
                   9352: regular expression, otherwise \Q$delthis\E is used. 
                   9353: The values are also deleted from the current processes %env.
1.191     harris41 9354: 
1.795     albertel 9355: =item * get_env_multiple($name) 
                   9356: 
                   9357: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9358: values may be defined and end up as an array ref.
                   9359: 
                   9360: returns an array of values
                   9361: 
1.243     albertel 9362: =back
                   9363: 
                   9364: =head2 User Information
1.191     harris41 9365: 
1.243     albertel 9366: =over 4
1.191     harris41 9367: 
                   9368: =item *
1.394     bowersj2 9369: X<queryauthenticate()>
                   9370: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9371: authentication scheme
                   9372: 
                   9373: =item *
1.394     bowersj2 9374: X<authenticate()>
                   9375: B<authenticate($uname,$upass,$udom)>: try to
                   9376: authenticate user from domain's lib servers (first use the current
                   9377: one). C<$upass> should be the users password.
1.191     harris41 9378: 
                   9379: =item *
1.394     bowersj2 9380: X<homeserver()>
                   9381: B<homeserver($uname,$udom)>: find the server which has
                   9382: the user's directory and files (there must be only one), this caches
                   9383: the answer, and also caches if there is a borken connection.
1.191     harris41 9384: 
                   9385: =item *
1.394     bowersj2 9386: X<idget()>
                   9387: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9388: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9389: username, and only 1 username per ID in a specific domain) (returns
                   9390: hash: id=>name,id=>name)
1.191     harris41 9391: 
                   9392: =item *
1.394     bowersj2 9393: X<idrget()>
                   9394: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9395: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9396: 
                   9397: =item *
1.394     bowersj2 9398: X<idput()>
                   9399: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9400: 
                   9401: =item *
1.394     bowersj2 9402: X<rolesinit()>
                   9403: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9404: 
                   9405: =item *
1.551     albertel 9406: X<getsection()>
                   9407: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9408: course $cname, return section name/number or '' for "not in course"
                   9409: and '-1' for "no section"
                   9410: 
                   9411: =item *
1.394     bowersj2 9412: X<userenvironment()>
                   9413: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9414: passed in @what from the requested user's environment, returns a hash
                   9415: 
1.858     raeburn  9416: =item * 
                   9417: X<userlog_query()>
1.859     albertel 9418: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9419: activity.log file. %filters defines filters applied when parsing the
                   9420: log file. These can be start or end timestamps, or the type of action
                   9421: - log to look for Login or Logout events, check for Checkin or
                   9422: Checkout, role for role selection. The response is in the form
                   9423: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9424: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9425: 
1.243     albertel 9426: =back
                   9427: 
                   9428: =head2 User Roles
                   9429: 
                   9430: =over 4
                   9431: 
                   9432: =item *
                   9433: 
1.810     raeburn  9434: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9435:  F: full access
                   9436:  U,I,K: authentication modes (cxx only)
                   9437:  '': forbidden
                   9438:  1: user needs to choose course
                   9439:  2: browse allowed
1.766     albertel 9440:  A: passphrase authentication needed
1.243     albertel 9441: 
                   9442: =item *
                   9443: 
                   9444: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9445: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9446: and course level
                   9447: 
                   9448: =item *
                   9449: 
1.988     raeburn  9450: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   9451: (rolesplain.tab); plain text explanation of a user role term.
                   9452: $type is Course (default) or Group.
                   9453: If $forcedefault evaluates to true, text returned will be default 
                   9454: text for $type. Otherwise, if this is a course, the text returned 
                   9455: will be a custom name for the role (if defined in the course's 
                   9456: environment).  If no custom name is defined the default is returned.
                   9457:    
1.832     raeburn  9458: =item *
                   9459: 
1.935     raeburn  9460: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9461: All arguments are optional. Returns a hash of a roles, either for
                   9462: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9463: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9464: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9465: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9466: For each key, value is set to colon-separated start and end times for
                   9467: the role.  If no username and domain are specified, will default to
1.934     raeburn  9468: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9469: of role statuses (active, future or previous), roles 
                   9470: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9471: to restrict the list of roles reported. If no array ref is 
                   9472: provided for types, will default to return only active roles.
1.834     albertel 9473: 
1.243     albertel 9474: =back
                   9475: 
                   9476: =head2 User Modification
                   9477: 
                   9478: =over 4
                   9479: 
                   9480: =item *
                   9481: 
1.957     raeburn  9482: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9483: user for the level given by URL.  Optional start and end dates (leave empty
                   9484: string or zero for "no date")
1.191     harris41 9485: 
                   9486: =item *
                   9487: 
1.243     albertel 9488: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9489: change a users, password, possible return values are: ok,
                   9490: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9491: refused
1.191     harris41 9492: 
                   9493: =item *
                   9494: 
1.243     albertel 9495: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9496: 
                   9497: =item *
                   9498: 
1.963     raeburn  9499: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9500:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9501: modify user
1.191     harris41 9502: 
                   9503: =item *
                   9504: 
1.286     matthew  9505: modifystudent
                   9506: 
1.957     raeburn  9507: modify a student's enrollment and identification information.
1.286     matthew  9508: The course id is resolved based on the current users environment.  
                   9509: This means the envoking user must be a course coordinator or otherwise
                   9510: associated with a course.
                   9511: 
1.297     matthew  9512: This call is essentially a wrapper for lonnet::modifyuser and
                   9513: lonnet::modify_student_enrollment
1.286     matthew  9514: 
                   9515: Inputs: 
                   9516: 
                   9517: =over 4
                   9518: 
1.957     raeburn  9519: =item B<$udom> Student's loncapa domain
1.286     matthew  9520: 
1.957     raeburn  9521: =item B<$uname> Student's loncapa login name
1.286     matthew  9522: 
1.964     bisitz   9523: =item B<$uid> Student/Employee ID
1.286     matthew  9524: 
1.957     raeburn  9525: =item B<$umode> Student's authentication mode
1.286     matthew  9526: 
1.957     raeburn  9527: =item B<$upass> Student's password
1.286     matthew  9528: 
1.957     raeburn  9529: =item B<$first> Student's first name
1.286     matthew  9530: 
1.957     raeburn  9531: =item B<$middle> Student's middle name
1.286     matthew  9532: 
1.957     raeburn  9533: =item B<$last> Student's last name
1.286     matthew  9534: 
1.957     raeburn  9535: =item B<$gene> Student's generation
1.286     matthew  9536: 
1.957     raeburn  9537: =item B<$usec> Student's section in course
1.286     matthew  9538: 
                   9539: =item B<$end> Unix time of the roles expiration
                   9540: 
                   9541: =item B<$start> Unix time of the roles start date
                   9542: 
                   9543: =item B<$forceid> If defined, allow $uid to be changed
                   9544: 
                   9545: =item B<$desiredhome> server to use as home server for student
                   9546: 
1.957     raeburn  9547: =item B<$email> Student's permanent e-mail address
                   9548: 
                   9549: =item B<$type> Type of enrollment (auto or manual)
                   9550: 
1.963     raeburn  9551: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9552: 
                   9553: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9554: 
1.963     raeburn  9555: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9556: 
1.963     raeburn  9557: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9558: 
1.963     raeburn  9559: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9560: 
1.286     matthew  9561: =back
1.297     matthew  9562: 
                   9563: =item *
                   9564: 
                   9565: modify_student_enrollment
                   9566: 
                   9567: Change a students enrollment status in a class.  The environment variable
                   9568: 'role.request.course' must be defined for this function to proceed.
                   9569: 
                   9570: Inputs:
                   9571: 
                   9572: =over 4
                   9573: 
                   9574: =item $udom, students domain
                   9575: 
                   9576: =item $uname, students name
                   9577: 
                   9578: =item $uid, students user id
                   9579: 
                   9580: =item $first, students first name
                   9581: 
                   9582: =item $middle
                   9583: 
                   9584: =item $last
                   9585: 
                   9586: =item $gene
                   9587: 
                   9588: =item $usec
                   9589: 
                   9590: =item $end
                   9591: 
                   9592: =item $start
                   9593: 
1.957     raeburn  9594: =item $type
                   9595: 
                   9596: =item $locktype
                   9597: 
                   9598: =item $cid
                   9599: 
                   9600: =item $selfenroll
                   9601: 
                   9602: =item $context
                   9603: 
1.297     matthew  9604: =back
                   9605: 
1.191     harris41 9606: 
                   9607: =item *
                   9608: 
1.243     albertel 9609: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9610: custom role; give a custom role to a user for the level given by URL.  Specify
                   9611: name and domain of role author, and role name
1.191     harris41 9612: 
                   9613: =item *
                   9614: 
1.243     albertel 9615: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9616: 
                   9617: =item *
                   9618: 
1.243     albertel 9619: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9620: 
                   9621: =back
                   9622: 
                   9623: =head2 Course Infomation
                   9624: 
                   9625: =over 4
1.191     harris41 9626: 
                   9627: =item *
                   9628: 
1.631     albertel 9629: coursedescription($courseid) : returns a hash of information about the
                   9630: specified course id, including all environment settings for the
                   9631: course, the description of the course will be in the hash under the
                   9632: key 'description'
1.191     harris41 9633: 
                   9634: =item *
                   9635: 
1.624     albertel 9636: resdata($name,$domain,$type,@which) : request for current parameter
                   9637: setting for a specific $type, where $type is either 'course' or 'user',
                   9638: @what should be a list of parameters to ask about. This routine caches
                   9639: answers for 5 minutes.
1.243     albertel 9640: 
1.877     foxr     9641: =item *
                   9642: 
                   9643: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9644: data base, returning a hash that is keyed by the resource name and has
                   9645: values that are the resource value.  I believe that the timestamps and
                   9646: versions are also returned.
                   9647: 
                   9648: 
1.243     albertel 9649: =back
                   9650: 
                   9651: =head2 Course Modification
                   9652: 
                   9653: =over 4
1.191     harris41 9654: 
                   9655: =item *
                   9656: 
1.243     albertel 9657: writecoursepref($courseid,%prefs) : write preferences (environment
                   9658: database) for a course
1.191     harris41 9659: 
                   9660: =item *
                   9661: 
1.243     albertel 9662: createcourse($udom,$description,$url) : make/modify course
                   9663: 
                   9664: =back
                   9665: 
                   9666: =head2 Resource Subroutines
                   9667: 
                   9668: =over 4
1.191     harris41 9669: 
                   9670: =item *
                   9671: 
1.243     albertel 9672: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9673: 
                   9674: =item *
                   9675: 
1.243     albertel 9676: repcopy($filename) : subscribes to the requested file, and attempts to
                   9677: replicate from the owning library server, Might return
1.607     raeburn  9678: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9679: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9680: resource. Expects the local filesystem pathname
                   9681: (/home/httpd/html/res/....)
                   9682: 
                   9683: =back
                   9684: 
                   9685: =head2 Resource Information
                   9686: 
                   9687: =over 4
1.191     harris41 9688: 
                   9689: =item *
                   9690: 
1.243     albertel 9691: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9692: a vairety of different possible values, $varname should be a request
                   9693: string, and the other parameters can be used to specify who and what
                   9694: one is asking about.
                   9695: 
                   9696: Possible values for $varname are environment.lastname (or other item
                   9697: from the envirnment hash), user.name (or someother aspect about the
                   9698: user), resource.0.maxtries (or some other part and parameter of a
                   9699: resource)
1.204     albertel 9700: 
                   9701: =item *
                   9702: 
1.243     albertel 9703: directcondval($number) : get current value of a condition; reads from a state
                   9704: string
1.204     albertel 9705: 
                   9706: =item *
                   9707: 
1.243     albertel 9708: condval($condidx) : value of condition index based on state
1.204     albertel 9709: 
                   9710: =item *
                   9711: 
1.243     albertel 9712: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9713: resource's metadata, $what should be either a specific key, or either
                   9714: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9715: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9716: 
                   9717: this function automatically caches all requests
1.191     harris41 9718: 
                   9719: =item *
                   9720: 
1.243     albertel 9721: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9722: network of library servers; returns file handle of where SQL and regex results
                   9723: will be stored for query
1.191     harris41 9724: 
                   9725: =item *
                   9726: 
1.243     albertel 9727: symbread($filename) : return symbolic list entry (filename argument optional);
                   9728: returns the data handle
1.191     harris41 9729: 
                   9730: =item *
                   9731: 
1.243     albertel 9732: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9733: a possible symb for the URL in $thisfn, and if is an encryypted
                   9734: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9735: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9736: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9737: 
1.191     harris41 9738: 
                   9739: =item *
                   9740: 
1.243     albertel 9741: symbclean($symb) : removes versions numbers from a symb, returns the
                   9742: cleaned symb
1.191     harris41 9743: 
                   9744: =item *
                   9745: 
1.243     albertel 9746: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9747: course map, user must be in a course for it to work.
1.191     harris41 9748: 
                   9749: =item *
                   9750: 
1.243     albertel 9751: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9752: 
                   9753: =item *
                   9754: 
1.243     albertel 9755: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9756: a random seed, all arguments are optional, if they aren't sent it uses the
                   9757: environment to derive them. Note: if symb isn't sent and it can't get one
                   9758: from &symbread it will use the current time as its return value
1.191     harris41 9759: 
                   9760: =item *
                   9761: 
1.243     albertel 9762: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9763: unfakeable, receipt
1.191     harris41 9764: 
                   9765: =item *
                   9766: 
1.620     albertel 9767: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9768: 
                   9769: =item *
                   9770: 
1.243     albertel 9771: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9772: 
                   9773: =item *
                   9774: 
1.243     albertel 9775: 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 9776: 
                   9777: =item *
                   9778: 
1.243     albertel 9779: 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 9780: 
                   9781: =item *
                   9782: 
1.243     albertel 9783: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9784: 
                   9785: =item *
                   9786: 
1.243     albertel 9787: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9788: forcing spreadsheet to reevaluate the resource scores next time.
                   9789: 
                   9790: =back
                   9791: 
                   9792: =head2 Storing/Retreiving Data
                   9793: 
                   9794: =over 4
1.191     harris41 9795: 
                   9796: =item *
                   9797: 
1.243     albertel 9798: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9799: for this url; hashref needs to be given and should be a \%hashname; the
                   9800: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9801: be derived from the env
1.191     harris41 9802: 
                   9803: =item *
                   9804: 
1.243     albertel 9805: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9806: uses critical subroutine
1.191     harris41 9807: 
                   9808: =item *
                   9809: 
1.243     albertel 9810: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9811: all args are optional
1.191     harris41 9812: 
                   9813: =item *
                   9814: 
1.717     albertel 9815: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9816: dumps the complete (or key matching regexp) namespace into a hash
                   9817: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9818: normally &store()ed into
                   9819: 
                   9820: $range should be either an integer '100' (give me the first 100
                   9821:                                            matching records)
                   9822:               or be  two integers sperated by a - with no spaces
                   9823:                  '30-50' (give me the 30th through the 50th matching
                   9824:                           records)
                   9825: 
                   9826: 
                   9827: =item *
                   9828: 
                   9829: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9830: replaces a &store() version of data with a replacement set of data
                   9831: for a particular resource in a namespace passed in the $storehash hash 
                   9832: reference
                   9833: 
                   9834: =item *
                   9835: 
1.243     albertel 9836: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9837: works very similar to store/cstore, but all data is stored in a
                   9838: temporary location and can be reset using tmpreset, $storehash should
                   9839: be a hash reference, returns nothing on success
1.191     harris41 9840: 
                   9841: =item *
                   9842: 
1.243     albertel 9843: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9844: similar to restore, but all data is stored in a temporary location and
                   9845: can be reset using tmpreset. Returns a hash of values on success,
                   9846: error string otherwise.
1.191     harris41 9847: 
                   9848: =item *
                   9849: 
1.243     albertel 9850: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9851: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9852: 
                   9853: =item *
                   9854: 
1.243     albertel 9855: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9856: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9857: 
                   9858: =item *
                   9859: 
1.243     albertel 9860: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9861: namesp ($udom and $uname are optional)
1.191     harris41 9862: 
                   9863: =item *
                   9864: 
1.702     albertel 9865: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9866: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9867: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9868: 
1.702     albertel 9869: $range should be either an integer '100' (give me the first 100
                   9870:                                            matching records)
                   9871:               or be  two integers sperated by a - with no spaces
                   9872:                  '30-50' (give me the 30th through the 50th matching
                   9873:                           records)
1.449     matthew  9874: =item *
                   9875: 
                   9876: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9877: $store can be a scalar, an array reference, or if the amount to be 
                   9878: incremented is > 1, a hash reference.
                   9879: 
                   9880: ($udom and $uname are optional)
1.191     harris41 9881: 
                   9882: =item *
                   9883: 
1.243     albertel 9884: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9885: ($udom and $uname are optional)
1.191     harris41 9886: 
                   9887: =item *
                   9888: 
1.243     albertel 9889: cput($namespace,$storehash,$udom,$uname) : critical put
                   9890: ($udom and $uname are optional)
1.191     harris41 9891: 
                   9892: =item *
                   9893: 
1.748     albertel 9894: newput($namespace,$storehash,$udom,$uname) :
                   9895: 
                   9896: Attempts to store the items in the $storehash, but only if they don't
                   9897: currently exist, if this succeeds you can be certain that you have 
                   9898: successfully created a new key value pair in the $namespace db.
                   9899: 
                   9900: 
                   9901: Args:
                   9902:  $namespace: name of database to store values to
                   9903:  $storehash: hashref to store to the db
                   9904:  $udom: (optional) domain of user containing the db
                   9905:  $uname: (optional) name of user caontaining the db
                   9906: 
                   9907: Returns:
                   9908:  'ok' -> succeeded in storing all keys of $storehash
                   9909:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9910:                         least <key> already existed in the db (other
                   9911:                         requested keys may also already exist)
1.967     bisitz   9912:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9913:  'con_lost' -> unable to contact request server
                   9914:  'refused' -> action was not allowed by remote machine
                   9915: 
                   9916: 
                   9917: =item *
                   9918: 
1.243     albertel 9919: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9920: reference filled in from namesp (encrypts the return communication)
                   9921: ($udom and $uname are optional)
1.191     harris41 9922: 
                   9923: =item *
                   9924: 
1.243     albertel 9925: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9926: critical subroutine
                   9927: 
1.806     raeburn  9928: =item *
                   9929: 
1.860     raeburn  9930: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9931: array reference filled in from namespace found in domain level on either
                   9932: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9933: 
                   9934: =item *
                   9935: 
1.860     raeburn  9936: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9937: domain level either on specified domain server ($uhome) or primary domain 
                   9938: server ($udom and $uhome are optional)
1.806     raeburn  9939: 
1.943     raeburn  9940: =item * 
                   9941: 
                   9942: get_domain_defaults($target_domain) : returns hash with defaults for
                   9943: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9944: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9945: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9946: Values are retrieved from cache (if current), or from domain's configuration.db
                   9947: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9948: or lonTabs/domain.tab. 
                   9949: 
                   9950: %domdefaults = &get_auth_defaults($target_domain);
                   9951: 
1.243     albertel 9952: =back
                   9953: 
                   9954: =head2 Network Status Functions
                   9955: 
                   9956: =over 4
1.191     harris41 9957: 
                   9958: =item *
                   9959: 
                   9960: dirlist($uri) : return directory list based on URI
                   9961: 
                   9962: =item *
                   9963: 
1.243     albertel 9964: spareserver() : find server with least workload from spare.tab
                   9965: 
1.986     foxr     9966: 
                   9967: =item *
                   9968: 
                   9969: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   9970: if there is no corresponding loncapa host.
                   9971: 
1.243     albertel 9972: =back
                   9973: 
1.986     foxr     9974: 
1.243     albertel 9975: =head2 Apache Request
                   9976: 
                   9977: =over 4
1.191     harris41 9978: 
                   9979: =item *
                   9980: 
1.243     albertel 9981: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9982: localhost, posts hash
                   9983: 
                   9984: =back
                   9985: 
                   9986: =head2 Data to String to Data
                   9987: 
                   9988: =over 4
1.191     harris41 9989: 
                   9990: =item *
                   9991: 
1.243     albertel 9992: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9993: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9994: 
                   9995: =item *
                   9996: 
1.243     albertel 9997: hashref2str($hashref) : convert a hashref into a string complete with
                   9998: escaping and '=' and '&' separators, supports elements that are
                   9999: arrayrefs and hashrefs
1.191     harris41 10000: 
                   10001: =item *
                   10002: 
1.243     albertel 10003: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10004: with escaping and '&' separators, supports elements that are arrayrefs
                   10005: and hashrefs
1.191     harris41 10006: 
                   10007: =item *
                   10008: 
1.243     albertel 10009: str2hash($string) : convert string to hash using unescaping and
                   10010: splitting on '=' and '&', supports elements that are arrayrefs and
                   10011: hashrefs
1.191     harris41 10012: 
                   10013: =item *
                   10014: 
1.243     albertel 10015: str2array($string) : convert string to hash using unescaping and
                   10016: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10017: 
                   10018: =back
                   10019: 
                   10020: =head2 Logging Routines
                   10021: 
                   10022: =over 4
                   10023: 
                   10024: These routines allow one to make log messages in the lonnet.log and
                   10025: lonnet.perm logfiles.
1.191     harris41 10026: 
                   10027: =item *
                   10028: 
1.243     albertel 10029: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10030: 
                   10031: =item *
                   10032: 
1.243     albertel 10033: logthis() : append message to the normal lonnet.log file, it gets
                   10034: preiodically rolled over and deleted.
1.191     harris41 10035: 
                   10036: =item *
                   10037: 
1.243     albertel 10038: logperm() : append a permanent message to lonnet.perm.log, this log
                   10039: file never gets deleted by any automated portion of the system, only
                   10040: messages of critical importance should go in here.
                   10041: 
                   10042: =back
                   10043: 
                   10044: =head2 General File Helper Routines
                   10045: 
                   10046: =over 4
1.191     harris41 10047: 
                   10048: =item *
                   10049: 
1.481     raeburn  10050: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10051: (a) files in /uploaded
                   10052:   (i) If a local copy of the file exists - 
                   10053:       compares modification date of local copy with last-modified date for 
                   10054:       definitive version stored on home server for course. If local copy is 
                   10055:       stale, requests a new version from the home server and stores it. 
                   10056:       If the original has been removed from the home server, then local copy 
                   10057:       is unlinked.
                   10058:   (ii) If local copy does not exist -
                   10059:       requests the file from the home server and stores it. 
                   10060:   
                   10061:   If $caller is 'uploadrep':  
                   10062:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10063:     for request for files originally uploaded via DOCS. 
                   10064:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10065:   
                   10066:   Otherwise:
                   10067:      This indicates a call from the content generation phase of the request.
                   10068:      -  returns the entire contents of the file or -1.
                   10069:      
                   10070: (b) files in /res
                   10071:    - returns the entire contents of a file or -1; 
                   10072:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10073: 
1.712     albertel 10074: 
                   10075: =item *
                   10076: 
                   10077: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10078:                   reference
                   10079: 
                   10080: returns either a stat() list of data about the file or an empty list
                   10081: if the file doesn't exist or couldn't find out about it (connection
                   10082: problems or user unknown)
                   10083: 
1.191     harris41 10084: =item *
                   10085: 
1.243     albertel 10086: filelocation($dir,$file) : returns file system location of a file
                   10087: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10088: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10089: and a file of ../bob will become /a/bob)
1.191     harris41 10090: 
                   10091: =item *
                   10092: 
                   10093: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10094: filelocation except for hrefs
                   10095: 
                   10096: =item *
                   10097: 
                   10098: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10099: 
1.243     albertel 10100: =back
                   10101: 
1.608     albertel 10102: =head2 Usererfile file routines (/uploaded*)
                   10103: 
                   10104: =over 4
                   10105: 
                   10106: =item *
                   10107: 
                   10108: userfileupload(): main rotine for putting a file in a user or course's
                   10109:                   filespace, arguments are,
                   10110: 
1.620     albertel 10111:  formname - required - this is the name of the element in $env where the
1.608     albertel 10112:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10113:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10114:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10115:  coursedoc - if true, store the file in the course of the active role
                   10116:              of the current user
                   10117:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10118:          if undefined, it will be placed in "unknown"
                   10119: 
                   10120:  (This routine calls clean_filename() to remove any dangerous
                   10121:  characters from the filename, and then calls finuserfileupload() to
                   10122:  complete the transaction)
                   10123: 
                   10124:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10125:  and /adm/notfound.html if unsuccessful
                   10126: 
                   10127: =item *
                   10128: 
                   10129: clean_filename(): routine for cleaing a filename up for storage in
                   10130:                  userfile space, argument is:
                   10131: 
                   10132:  filename - proposed filename
                   10133: 
                   10134: returns: the new clean filename
                   10135: 
                   10136: =item *
                   10137: 
                   10138: finishuserfileupload(): routine that creaes and sends the file to
                   10139: userspace, probably shouldn't be called directly
                   10140: 
                   10141:   docuname: username or courseid of destination for the file
                   10142:   docudom: domain of user/course of destination for the file
                   10143:   formname: same as for userfileupload()
                   10144:   fname: filename (inculding subdirectories) for the file
                   10145: 
                   10146:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10147:  and /adm/notfound.html if unsuccessful
                   10148: 
                   10149: =item *
                   10150: 
                   10151: renameuserfile(): renames an existing userfile to a new name
                   10152: 
                   10153:   Args:
                   10154:    docuname: username or courseid of destination for the file
                   10155:    docudom: domain of user/course of destination for the file
                   10156:    old: current file name (including any subdirs under userfiles)
                   10157:    new: desired file name (including any subdirs under userfiles)
                   10158: 
                   10159: =item *
                   10160: 
                   10161: mkdiruserfile(): creates a directory is a userfiles dir
                   10162: 
                   10163:   Args:
                   10164:    docuname: username or courseid of destination for the file
                   10165:    docudom: domain of user/course of destination for the file
                   10166:    dir: dir to create (including any subdirs under userfiles)
                   10167: 
                   10168: =item *
                   10169: 
                   10170: removeuserfile(): removes a file that exists in userfiles
                   10171: 
                   10172:   Args:
                   10173:    docuname: username or courseid of destination for the file
                   10174:    docudom: domain of user/course of destination for the file
                   10175:    fname: filname to delete (including any subdirs under userfiles)
                   10176: 
                   10177: =item *
                   10178: 
                   10179: removeuploadedurl(): convience function for removeuserfile()
                   10180: 
                   10181:   Args:
                   10182:    url:  a full /uploaded/... url to delete
                   10183: 
1.747     albertel 10184: =item * 
                   10185: 
                   10186: get_portfile_permissions():
                   10187:   Args:
                   10188:     domain: domain of user or course contain the portfolio files
                   10189:     user: name of user or num of course contain the portfolio files
                   10190:   Returns:
                   10191:     hashref of a dump of the proper file_permissions.db
                   10192:    
                   10193: 
                   10194: =item * 
                   10195: 
                   10196: get_access_controls():
                   10197: 
                   10198: Args:
                   10199:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10200:   group: (optional) the group you want the files associated with
                   10201:   file: (optional) the file you want access info on
                   10202: 
                   10203: Returns:
1.749     raeburn  10204:     a hash (keys are file names) of hashes containing
                   10205:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10206:         values are XML containing access control settings (see below) 
1.747     albertel 10207: 
                   10208: Internal notes:
                   10209: 
1.749     raeburn  10210:  access controls are stored in file_permissions.db as key=value pairs.
                   10211:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10212:         where scope -> public,guest,course,group,domains or users.
                   10213:               end -> UNIX time for end of access (0 -> no end date)
                   10214:               start -> UNIX time for start of access
                   10215: 
                   10216:     value -> XML description of access control
                   10217:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10218:             <start></start>
                   10219:             <end></end>
                   10220: 
                   10221:             <password></password>  for scope type = guest
                   10222: 
                   10223:             <domain></domain>     for scope type = course or group
                   10224:             <number></number>
                   10225:             <roles id="">
                   10226:              <role></role>
                   10227:              <access></access>
                   10228:              <section></section>
                   10229:              <group></group>
                   10230:             </roles>
                   10231: 
                   10232:             <dom></dom>         for scope type = domains
                   10233: 
                   10234:             <users>             for scope type = users
                   10235:              <user>
                   10236:               <uname></uname>
                   10237:               <udom></udom>
                   10238:              </user>
                   10239:             </users>
                   10240:            </scope> 
                   10241:               
                   10242:  Access data is also aggregated for each file in an additional key=value pair:
                   10243:  key -> path to file/file_name\0accesscontrol 
                   10244:  value -> reference to hash
                   10245:           hash contains key = value pairs
                   10246:           where key = uniqueID:scope_end_start
                   10247:                 value = UNIX time record was last updated
                   10248: 
                   10249:           Used to improve speed of look-ups of access controls for each file.  
                   10250:  
                   10251:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10252: 
                   10253: modify_access_controls():
                   10254: 
                   10255: Modifies access controls for a portfolio file
                   10256: Args
                   10257: 1. file name
                   10258: 2. reference to hash of required changes,
                   10259: 3. domain
                   10260: 4. username
                   10261:   where domain,username are the domain of the portfolio owner 
                   10262:   (either a user or a course) 
                   10263: 
                   10264: Returns:
                   10265: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10266: 2. result of deletions ('ok' or 'error', with error message).
                   10267: 3. reference to hash of any new or updated access controls.
                   10268: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10269:    key = integer (inbound ID)
                   10270:    value = uniqueID  
1.747     albertel 10271: 
1.608     albertel 10272: =back
                   10273: 
1.243     albertel 10274: =head2 HTTP Helper Routines
                   10275: 
                   10276: =over 4
                   10277: 
1.191     harris41 10278: =item *
                   10279: 
                   10280: escape() : unpack non-word characters into CGI-compatible hex codes
                   10281: 
                   10282: =item *
                   10283: 
                   10284: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10285: 
1.243     albertel 10286: =back
                   10287: 
                   10288: =head1 PRIVATE SUBROUTINES
                   10289: 
                   10290: =head2 Underlying communication routines (Shouldn't call)
                   10291: 
                   10292: =over 4
                   10293: 
                   10294: =item *
                   10295: 
                   10296: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10297: 
                   10298: =item *
                   10299: 
                   10300: reply() : uses subreply to send a message to remote machine, logs all failures
                   10301: 
                   10302: =item *
                   10303: 
                   10304: critical() : passes a critical message to another server; if cannot
                   10305: get through then place message in connection buffer directory and
                   10306: returns con_delayed, if incapable of saving message, returns
                   10307: con_failed
                   10308: 
                   10309: =item *
                   10310: 
                   10311: reconlonc() : tries to reconnect lonc client processes.
                   10312: 
                   10313: =back
                   10314: 
                   10315: =head2 Resource Access Logging
                   10316: 
                   10317: =over 4
                   10318: 
                   10319: =item *
                   10320: 
                   10321: flushcourselogs() : flush (save) buffer logs and access logs
                   10322: 
                   10323: =item *
                   10324: 
                   10325: courselog($what) : save message for course in hash
                   10326: 
                   10327: =item *
                   10328: 
                   10329: courseacclog($what) : save message for course using &courselog().  Perform
                   10330: special processing for specific resource types (problems, exams, quizzes, etc).
                   10331: 
1.191     harris41 10332: =item *
                   10333: 
                   10334: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10335: as a PerlChildExitHandler
1.243     albertel 10336: 
                   10337: =back
                   10338: 
                   10339: =head2 Other
                   10340: 
                   10341: =over 4
                   10342: 
                   10343: =item *
                   10344: 
                   10345: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10346: 
                   10347: =back
                   10348: 
                   10349: =cut
1.877     foxr     10350: 

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