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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1078  ! raeburn     4: # $Id: lonnet.pm,v 1.1077 2010/07/25 02:58:05 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1074    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.676     albertel   98: 
1.195     www        99: my $readit;
1.550     foxr      100: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  101: 
1.619     albertel  102: require Exporter;
                    103: 
                    104: our @ISA = qw (Exporter);
                    105: our @EXPORT = qw(%env);
                    106: 
1.449     matthew   107: 
1.1       albertel  108: # --------------------------------------------------------------------- Logging
1.729     www       109: {
                    110:     my $logid;
                    111:     sub instructor_log {
1.957     raeburn   112: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    113:         if (($cnum eq '') || ($cdom eq '')) {
                    114:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    115:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    116:         }
1.729     www       117: 	$logid++;
1.957     raeburn   118:         my $now = time();
                    119: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       120: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       121: 				    { $id => {
                    122: 					'exe_uname' => $env{'user.name'},
                    123: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   124: 					'exe_time'  => $now,
1.730     www       125: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    126: 					'delflag'   => $delflag,
                    127: 					'logentry'  => $storehash,
                    128: 					'uname'     => $uname,
                    129: 					'udom'      => $udom,
                    130: 				    }
1.957     raeburn   131: 				  },$cdom,$cnum);
1.729     www       132:     }
                    133: }
1.1       albertel  134: 
1.163     harris41  135: sub logtouch {
                    136:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  137:     unless (-e "$execdir/logs/lonnet.log") {	
                    138: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  139: 	close $fh;
                    140:     }
                    141:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    142:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    143: }
                    144: 
1.1       albertel  145: sub logthis {
                    146:     my $message=shift;
                    147:     my $execdir=$perlvar{'lonDaemons'};
                    148:     my $now=time;
                    149:     my $local=localtime($now);
1.448     albertel  150:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      151: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    152: 	print $fh $logstring;
1.448     albertel  153: 	close($fh);
                    154:     }
1.1       albertel  155:     return 1;
                    156: }
                    157: 
                    158: sub logperm {
                    159:     my $message=shift;
                    160:     my $execdir=$perlvar{'lonDaemons'};
                    161:     my $now=time;
                    162:     my $local=localtime($now);
1.448     albertel  163:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    164: 	print $fh "$now:$message:$local\n";
                    165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
1.850     albertel  170: sub create_connection {
1.853     albertel  171:     my ($hostname,$lonid) = @_;
1.851     albertel  172:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  173: 				     Type    => SOCK_STREAM,
                    174: 				     Timeout => 10);
                    175:     return 0 if (!$client);
1.890     albertel  176:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  177:     my $result = <$client>;
                    178:     chomp($result);
                    179:     return 1 if ($result eq 'done');
                    180:     return 0;
                    181: }
                    182: 
1.983     raeburn   183: sub get_server_timezone {
                    184:     my ($cnum,$cdom) = @_;
                    185:     my $home=&homeserver($cnum,$cdom);
                    186:     if ($home ne 'no_host') {
                    187:         my $cachetime = 24*3600;
                    188:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    189:         if (defined($cached)) {
                    190:             return $timezone;
                    191:         } else {
                    192:             my $timezone = &reply('servertimezone',$home);
                    193:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    194:         }
                    195:     }
                    196: }
1.850     albertel  197: 
1.993     raeburn   198: sub get_server_loncaparev {
1.1073    raeburn   199:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   200:     if (defined($lonhost)) {
                    201:         if (!defined(&hostname($lonhost))) {
                    202:             undef($lonhost);
                    203:         }
                    204:     }
                    205:     if (!defined($lonhost)) {
                    206:         if (defined(&domain($dom,'primary'))) {
                    207:             $lonhost=&domain($dom,'primary');
                    208:             if ($lonhost eq 'no_host') {
                    209:                 undef($lonhost);
                    210:             }
                    211:         }
                    212:     }
                    213:     if (defined($lonhost)) {
1.1073    raeburn   214:         my $cachetime = 12*3600;
                    215:         if (!$ignore_cache) {
                    216:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    217:             if (defined($cached)) {
                    218:                 return $loncaparev;
                    219:             }
                    220:         }
                    221:         my ($answer,$loncaparev);
                    222:         my @ids=&current_machine_ids();
                    223:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    224:             $answer = $perlvar{'lonVersion'};
                    225:             if ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
                    226:                 $loncaparev = $1;
                    227:             }
                    228:         } else {
                    229:             $answer = &reply('serverloncaparev',$lonhost);
                    230:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    231:                 if ($caller eq 'loncron') {
                    232:                     my $ua=new LWP::UserAgent;
                    233:                     $ua->timeout(20);
                    234:                     my $protocol = $protocol{$lonhost};
                    235:                     $protocol = 'http' if ($protocol ne 'https');
                    236:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    237:                     my $request=new HTTP::Request('GET',$url);
                    238:                     my $response=$ua->request($request);
                    239:                     unless ($response->is_error()) {
                    240:                         my $content = $response->content;
                    241:                         if ($content =~ /<p>VERSION\:\s*([\d.\-]+)<\/p>/) {
                    242:                             $loncaparev = $1;
                    243:                         }
                    244:                     }
                    245:                 } else {
                    246:                     $loncaparev = $loncaparevs{$lonhost};
                    247:                 }
                    248:             } elsif ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
                    249:                 $loncaparev = $1;
                    250:             }
1.993     raeburn   251:         }
1.1073    raeburn   252:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   253:     }
                    254: }
                    255: 
1.1074    raeburn   256: sub get_server_homeID {
                    257:     my ($hostname,$ignore_cache,$caller) = @_;
                    258:     unless ($ignore_cache) {
                    259:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    260:         if (defined($cached)) {
                    261:             return $serverhomeID;
                    262:         }
                    263:     }
                    264:     my $cachetime = 12*3600;
                    265:     my $serverhomeID;
                    266:     if ($caller eq 'loncron') { 
                    267:         my @machine_ids = &machine_ids($hostname);
                    268:         foreach my $id (@machine_ids) {
                    269:             my $response = &reply('serverhomeID',$id);
                    270:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    271:                 $serverhomeID = $response;
                    272:                 last;
                    273:             }
                    274:         }
                    275:         if ($serverhomeID eq '') {
                    276:             $serverhomeID = $machine_ids[-1];
                    277:         }
                    278:     } else {
                    279:         $serverhomeID = $serverhomeIDs{$hostname};
                    280:     }
                    281:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    282: }
                    283: 
1.1       albertel  284: # -------------------------------------------------- Non-critical communication
                    285: sub subreply {
                    286:     my ($cmd,$server)=@_;
1.838     albertel  287:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      288:     #
                    289:     #  With loncnew process trimming, there's a timing hole between lonc server
                    290:     #  process exit and the master server picking up the listen on the AF_UNIX
                    291:     #  socket.  In that time interval, a lock file will exist:
                    292: 
                    293:     my $lockfile=$peerfile.".lock";
                    294:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    295: 	sleep(1);
                    296:     }
                    297:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      298:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      299:     #
1.550     foxr      300:     #   We'll give the connection a few tries before abandoning it.  If
                    301:     #   connection is not possible, we'll con_lost back to the client.
                    302:     #   
                    303:     my $client;
                    304:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    305: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    306: 				      Type    => SOCK_STREAM,
                    307: 				      Timeout => 10);
1.869     albertel  308: 	if ($client) {
1.550     foxr      309: 	    last;		# Connected!
1.850     albertel  310: 	} else {
1.853     albertel  311: 	    &create_connection(&hostname($server),$server);
1.550     foxr      312: 	}
1.850     albertel  313:         sleep(1);		# Try again later if failed connection.
1.550     foxr      314:     }
                    315:     my $answer;
                    316:     if ($client) {
1.704     albertel  317: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      318: 	$answer=<$client>;
                    319: 	if (!$answer) { $answer="con_lost"; }
                    320: 	chomp($answer);
                    321:     } else {
                    322: 	$answer = 'con_lost';	# Failed connection.
                    323:     }
1.1       albertel  324:     return $answer;
                    325: }
                    326: 
                    327: sub reply {
                    328:     my ($cmd,$server)=@_;
1.838     albertel  329:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  330:     my $answer=subreply($cmd,$server);
1.65      www       331:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  332:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       333:                 " $cmd to $server returned $answer</font>");
                    334:     }
1.1       albertel  335:     return $answer;
                    336: }
                    337: 
                    338: # ----------------------------------------------------------- Send USR1 to lonc
                    339: 
                    340: sub reconlonc {
1.891     albertel  341:     my ($lonid) = @_;
                    342:     my $hostname = &hostname($lonid);
                    343:     if ($lonid) {
                    344: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    345: 	if ($hostname && -e $peerfile) {
                    346: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    347: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    348: 					     Type    => SOCK_STREAM,
                    349: 					     Timeout => 10);
                    350: 	    if ($client) {
                    351: 		print $client ("reset_retries\n");
                    352: 		my $answer=<$client>;
                    353: 		#reset just this one.
                    354: 	    }
                    355: 	}
                    356: 	return;
                    357:     }
                    358: 
1.836     www       359:     &logthis("Trying to reconnect lonc");
1.1       albertel  360:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  361:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  362: 	my $loncpid=<$fh>;
                    363:         chomp($loncpid);
                    364:         if (kill 0 => $loncpid) {
                    365: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    366:             kill USR1 => $loncpid;
                    367:             sleep 1;
1.836     www       368:          } else {
1.12      www       369: 	    &logthis(
1.672     albertel  370:                "<font color=\"blue\">WARNING:".
1.12      www       371:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  372:         }
                    373:     } else {
1.836     www       374: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  375:     }
                    376: }
                    377: 
                    378: # ------------------------------------------------------ Critical communication
1.12      www       379: 
1.1       albertel  380: sub critical {
                    381:     my ($cmd,$server)=@_;
1.838     albertel  382:     unless (&hostname($server)) {
1.672     albertel  383:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       384:                " Critical message to unknown server ($server)</font>");
                    385:         return 'no_such_host';
                    386:     }
1.1       albertel  387:     my $answer=reply($cmd,$server);
                    388:     if ($answer eq 'con_lost') {
                    389: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  390: 	my $answer=reply($cmd,$server);
1.1       albertel  391:         if ($answer eq 'con_lost') {
                    392:             my $now=time;
                    393:             my $middlename=$cmd;
1.5       www       394:             $middlename=substr($middlename,0,16);
1.1       albertel  395:             $middlename=~s/\W//g;
                    396:             my $dfilename=
1.305     www       397:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    398:             $dumpcount++;
1.1       albertel  399:             {
1.448     albertel  400: 		my $dfh;
                    401: 		if (open($dfh,">$dfilename")) {
                    402: 		    print $dfh "$cmd\n"; 
                    403: 		    close($dfh);
                    404: 		}
1.1       albertel  405:             }
                    406:             sleep 2;
                    407:             my $wcmd='';
                    408:             {
1.448     albertel  409: 		my $dfh;
                    410: 		if (open($dfh,"<$dfilename")) {
                    411: 		    $wcmd=<$dfh>; 
                    412: 		    close($dfh);
                    413: 		}
1.1       albertel  414:             }
                    415:             chomp($wcmd);
1.7       www       416:             if ($wcmd eq $cmd) {
1.672     albertel  417: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       418:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  419:                 &logperm("D:$server:$cmd");
                    420: 	        return 'con_delayed';
                    421:             } else {
1.672     albertel  422:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       423:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  424:                 &logperm("F:$server:$cmd");
                    425:                 return 'con_failed';
                    426:             }
                    427:         }
                    428:     }
                    429:     return $answer;
1.405     albertel  430: }
                    431: 
1.755     albertel  432: # ------------------------------------------- check if return value is an error
                    433: 
                    434: sub error {
                    435:     my ($result) = @_;
1.756     albertel  436:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  437: 	if ($2 == 2) { return undef; }
                    438: 	return $1;
                    439:     }
                    440:     return undef;
                    441: }
                    442: 
1.783     albertel  443: sub convert_and_load_session_env {
                    444:     my ($lonidsdir,$handle)=@_;
                    445:     my @profile;
                    446:     {
1.917     albertel  447: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    448: 	if (!$opened) {
1.915     albertel  449: 	    return 0;
                    450: 	}
1.783     albertel  451: 	flock($idf,LOCK_SH);
                    452: 	@profile=<$idf>;
                    453: 	close($idf);
                    454:     }
                    455:     my %temp_env;
                    456:     foreach my $line (@profile) {
1.786     albertel  457: 	if ($line !~ m/=/) {
                    458: 	    return 0;
                    459: 	}
1.783     albertel  460: 	chomp($line);
                    461: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    462: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    463:     }
                    464:     unlink("$lonidsdir/$handle.id");
                    465:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    466: 	    0640)) {
                    467: 	%disk_env = %temp_env;
                    468: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    469: 	untie(%disk_env);
                    470:     }
1.786     albertel  471:     return 1;
1.783     albertel  472: }
                    473: 
1.374     www       474: # ------------------------------------------- Transfer profile into environment
1.780     albertel  475: my $env_loaded;
                    476: sub transfer_profile_to_env {
1.788     albertel  477:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    478:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       479: 
1.720     albertel  480:     if (!defined($lonidsdir)) {
                    481: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    482:     }
                    483:     if (!defined($handle)) {
                    484:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    485:     }
                    486: 
1.786     albertel  487:     my $convert;
                    488:     {
1.917     albertel  489:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    490: 	if (!$opened) {
1.915     albertel  491: 	    return;
                    492: 	}
1.786     albertel  493: 	flock($idf,LOCK_SH);
                    494: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    495: 		&GDBM_READER(),0640)) {
                    496: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    497: 	    untie(%disk_env);
                    498: 	} else {
                    499: 	    $convert = 1;
                    500: 	}
                    501:     }
                    502:     if ($convert) {
                    503: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    504: 	    &logthis("Failed to load session, or convert session.");
                    505: 	}
1.374     www       506:     }
1.783     albertel  507: 
1.786     albertel  508:     my %remove;
1.783     albertel  509:     while ( my $envname = each(%env) ) {
1.433     matthew   510:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    511:             if ($time < time-300) {
1.783     albertel  512:                 $remove{$key}++;
1.433     matthew   513:             }
                    514:         }
                    515:     }
1.783     albertel  516: 
1.619     albertel  517:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  518:     $env_loaded=1;
1.783     albertel  519:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   520:         &delenv($expired_key);
1.374     www       521:     }
1.1       albertel  522: }
                    523: 
1.916     albertel  524: # ---------------------------------------------------- Check for valid session 
                    525: sub check_for_valid_session {
                    526:     my ($r) = @_;
                    527:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    528:     my $lonid=$cookies{'lonID'};
                    529:     return undef if (!$lonid);
                    530: 
                    531:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    532:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    533:     return undef if (!-e "$lonidsdir/$handle.id");
                    534: 
1.917     albertel  535:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    536:     return undef if (!$opened);
1.916     albertel  537: 
                    538:     flock($idf,LOCK_SH);
                    539:     my %disk_env;
                    540:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    541: 	    &GDBM_READER(),0640)) {
                    542: 	return undef;	
                    543:     }
                    544: 
                    545:     if (!defined($disk_env{'user.name'})
                    546: 	|| !defined($disk_env{'user.domain'})) {
                    547: 	return undef;
                    548:     }
                    549:     return $handle;
                    550: }
                    551: 
1.830     albertel  552: sub timed_flock {
                    553:     my ($file,$lock_type) = @_;
                    554:     my $failed=0;
                    555:     eval {
                    556: 	local $SIG{__DIE__}='DEFAULT';
                    557: 	local $SIG{ALRM}=sub {
                    558: 	    $failed=1;
                    559: 	    die("failed lock");
                    560: 	};
                    561: 	alarm(13);
                    562: 	flock($file,$lock_type);
                    563: 	alarm(0);
                    564:     };
                    565:     if ($failed) {
                    566: 	return undef;
                    567:     } else {
                    568: 	return 1;
                    569:     }
                    570: }
                    571: 
1.5       www       572: # ---------------------------------------------------------- Append Environment
                    573: 
                    574: sub appenv {
1.949     raeburn   575:     my ($newenv,$roles) = @_;
                    576:     if (ref($newenv) eq 'HASH') {
                    577:         foreach my $key (keys(%{$newenv})) {
                    578:             my $refused = 0;
                    579: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    580:                 $refused = 1;
                    581:                 if (ref($roles) eq 'ARRAY') {
                    582:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    583:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    584:                         $refused = 0;
                    585:                     }
                    586:                 }
                    587:             }
                    588:             if ($refused) {
                    589:                 &logthis("<font color=\"blue\">WARNING: ".
                    590:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    591:                          .'</font>');
                    592: 	        delete($newenv->{$key});
                    593:             } else {
                    594:                 $env{$key}=$newenv->{$key};
                    595:             }
                    596:         }
                    597:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    598:         if ($opened
                    599: 	    && &timed_flock($env_file,LOCK_EX)
                    600: 	    &&
                    601: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    602: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    603: 	    while (my ($key,$value) = each(%{$newenv})) {
                    604: 	        $disk_env{$key} = $value;
                    605: 	    }
                    606: 	    untie(%disk_env);
1.35      www       607:         }
1.191     harris41  608:     }
1.56      www       609:     return 'ok';
                    610: }
                    611: # ----------------------------------------------------- Delete from Environment
                    612: 
                    613: sub delenv {
1.987     raeburn   614:     my ($delthis,$regexp) = @_;
1.56      www       615:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  616:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       617:                 "Attempt to delete from environment ".$delthis);
                    618:         return 'error';
                    619:     }
1.917     albertel  620:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    621:     if ($opened
1.915     albertel  622: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  623: 	&&
                    624: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    625: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  626: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   627: 	    if ($regexp) {
                    628:                 if ($key=~/^$delthis/) {
                    629:                     delete($env{$key});
                    630:                     delete($disk_env{$key});
                    631:                 } 
                    632:             } else {
                    633:                 if ($key=~/^\Q$delthis\E/) {
                    634: 		    delete($env{$key});
                    635: 		    delete($disk_env{$key});
                    636: 	        }
                    637:             }
1.448     albertel  638: 	}
1.783     albertel  639: 	untie(%disk_env);
1.5       www       640:     }
                    641:     return 'ok';
1.369     albertel  642: }
                    643: 
1.790     albertel  644: sub get_env_multiple {
                    645:     my ($name) = @_;
                    646:     my @values;
                    647:     if (defined($env{$name})) {
                    648:         # exists is it an array
                    649:         if (ref($env{$name})) {
                    650:             @values=@{ $env{$name} };
                    651:         } else {
                    652:             $values[0]=$env{$name};
                    653:         }
                    654:     }
                    655:     return(@values);
                    656: }
                    657: 
1.958     www       658: # ------------------------------------------------------------------- Locking
                    659: 
                    660: sub set_lock {
                    661:     my ($text)=@_;
                    662:     $locknum++;
                    663:     my $id=$$.'-'.$locknum;
                    664:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    665:              'session.lock.'.$id => $text});
                    666:     return $id;
                    667: }
                    668: 
                    669: sub get_locks {
                    670:     my $num=0;
                    671:     my %texts=();
                    672:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    673:        if ($lock=~/\w/) {
                    674:           $num++;
                    675:           $texts{$lock}=$env{'session.lock.'.$lock};
                    676:        }
                    677:    }
                    678:    return ($num,%texts);
                    679: }
                    680: 
                    681: sub remove_lock {
                    682:     my ($id)=@_;
                    683:     my $newlocks='';
                    684:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    685:        if (($lock=~/\w/) && ($lock ne $id)) {
                    686:           $newlocks.=','.$lock;
                    687:        }
                    688:     }
                    689:     &appenv({'session.locks' => $newlocks});
                    690:     &delenv('session.lock.'.$id);
                    691: }
                    692: 
                    693: sub remove_all_locks {
                    694:     my $activelocks=$env{'session.locks'};
                    695:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    696:        if ($lock=~/\w/) {
                    697:           &remove_lock($lock);
                    698:        }
                    699:     }
                    700: }
                    701: 
                    702: 
1.369     albertel  703: # ------------------------------------------ Find out current server userload
                    704: sub userload {
                    705:     my $numusers=0;
                    706:     {
                    707: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    708: 	my $filename;
                    709: 	my $curtime=time;
                    710: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  711: 	    next if ($filename eq '.' || $filename eq '..');
                    712: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  713: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  714: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  715: 	}
                    716: 	closedir(LONIDS);
                    717:     }
                    718:     my $userloadpercent=0;
                    719:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    720:     if ($maxuserload) {
1.371     albertel  721: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  722:     }
1.372     albertel  723:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  724:     return $userloadpercent;
1.283     www       725: }
                    726: 
1.1       albertel  727: # ------------------------------ Find server with least workload from spare.tab
1.11      www       728: 
1.1       albertel  729: sub spareserver {
1.670     albertel  730:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  731:     my $spare_server;
1.370     albertel  732:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  733:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    734:                                                      :  $userloadpercent;
                    735:     
                    736:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    737: 	($spare_server, $lowest_load) =
                    738: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    739:     }
                    740: 
                    741:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    742: 
                    743:     if (!$found_server) {
                    744: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    745: 	    ($spare_server, $lowest_load) =
                    746: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    747: 	}
                    748:     }
                    749: 
                    750:     if (!$want_server_name) {
1.968     raeburn   751:         my $protocol = 'http';
                    752:         if ($protocol{$spare_server} eq 'https') {
                    753:             $protocol = $protocol{$spare_server};
                    754:         }
1.1001    raeburn   755:         if (defined($spare_server)) {
                    756:             my $hostname = &hostname($spare_server);
                    757:             if (defined($hostname)) {  
                    758: 	        $spare_server = $protocol.'://'.$hostname;
                    759:             }
                    760:         }
1.784     albertel  761:     }
                    762:     return $spare_server;
                    763: }
                    764: 
                    765: sub compare_server_load {
                    766:     my ($try_server, $spare_server, $lowest_load) = @_;
                    767: 
                    768:     my $loadans     = &reply('load',    $try_server);
                    769:     my $userloadans = &reply('userload',$try_server);
                    770: 
                    771:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072    www       772: 	return; #didn't get a number from the server
1.784     albertel  773:     }
                    774: 
                    775:     my $load;
                    776:     if ($loadans =~ /\d/) {
                    777: 	if ($userloadans =~ /\d/) {
                    778: 	    #both are numbers, pick the bigger one
                    779: 	    $load = ($loadans > $userloadans) ? $loadans 
                    780: 		                              : $userloadans;
1.411     albertel  781: 	} else {
1.784     albertel  782: 	    $load = $loadans;
1.411     albertel  783: 	}
1.784     albertel  784:     } else {
                    785: 	$load = $userloadans;
                    786:     }
                    787: 
                    788:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    789: 	$spare_server = $try_server;
                    790: 	$lowest_load  = $load;
1.370     albertel  791:     }
1.784     albertel  792:     return ($spare_server,$lowest_load);
1.202     matthew   793: }
1.914     albertel  794: 
                    795: # --------------------------- ask offload servers if user already has a session
                    796: sub find_existing_session {
                    797:     my ($udom,$uname) = @_;
                    798:     foreach my $try_server (@{ $spareid{'primary'} },
                    799: 			    @{ $spareid{'default'} }) {
                    800: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    801:     }
                    802:     return;
                    803: }
                    804: 
                    805: # -------------------------------- ask if server already has a session for user
                    806: sub has_user_session {
                    807:     my ($lonid,$udom,$uname) = @_;
                    808:     my $result = &reply(join(':','userhassession',
                    809: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    810:     return 1 if ($result eq 'ok');
                    811: 
                    812:     return 0;
                    813: }
                    814: 
1.1076    raeburn   815: # --------- determine least loaded server in a user's domain which allows login
                    816: 
                    817: sub choose_server {
                    818:     my ($udom) = @_;
                    819:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   820:     my %servers = &get_servers($udom);
1.1076    raeburn   821:     my $lowest_load = 30000;
                    822:     my ($login_host,$hostname);
                    823:     foreach my $lonhost (keys(%servers)) {
                    824:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    825:         if ($loginvia eq '') {
                    826:             ($login_host, $lowest_load) =
                    827:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    828:         }
                    829:     }
                    830:     if ($login_host ne '') {
                    831:         $hostname = $servers{$login_host};
                    832:     }
                    833:     return ($login_host,$hostname);
                    834: }
                    835: 
1.202     matthew   836: # --------------------------------------------- Try to change a user's password
                    837: 
                    838: sub changepass {
1.799     raeburn   839:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   840:     $currentpass = &escape($currentpass);
                    841:     $newpass     = &escape($newpass);
1.1030    raeburn   842:     my $lonhost = $perlvar{'lonHostID'};
                    843:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   844: 		       $server);
                    845:     if (! $answer) {
                    846: 	&logthis("No reply on password change request to $server ".
                    847: 		 "by $uname in domain $udom.");
                    848:     } elsif ($answer =~ "^ok") {
                    849:         &logthis("$uname in $udom successfully changed their password ".
                    850: 		 "on $server.");
                    851:     } elsif ($answer =~ "^pwchange_failure") {
                    852: 	&logthis("$uname in $udom was unable to change their password ".
                    853: 		 "on $server.  The action was blocked by either lcpasswd ".
                    854: 		 "or pwchange");
                    855:     } elsif ($answer =~ "^non_authorized") {
                    856:         &logthis("$uname in $udom did not get their password correct when ".
                    857: 		 "attempting to change it on $server.");
                    858:     } elsif ($answer =~ "^auth_mode_error") {
                    859:         &logthis("$uname in $udom attempted to change their password despite ".
                    860: 		 "not being locally or internally authenticated on $server.");
                    861:     } elsif ($answer =~ "^unknown_user") {
                    862:         &logthis("$uname in $udom attempted to change their password ".
                    863: 		 "on $server but were unable to because $server is not ".
                    864: 		 "their home server.");
                    865:     } elsif ($answer =~ "^refused") {
                    866: 	&logthis("$server refused to change $uname in $udom password because ".
                    867: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   868:     } elsif ($answer =~ "invalid_client") {
                    869:         &logthis("$server refused to change $uname in $udom password because ".
                    870:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   871:     }
                    872:     return $answer;
1.1       albertel  873: }
                    874: 
1.169     harris41  875: # ----------------------- Try to determine user's current authentication scheme
                    876: 
                    877: sub queryauthenticate {
                    878:     my ($uname,$udom)=@_;
1.456     albertel  879:     my $uhome=&homeserver($uname,$udom);
                    880:     if (!$uhome) {
                    881: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    882: 	return 'no_host';
                    883:     }
                    884:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    885:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    886: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  887:     }
1.456     albertel  888:     return $answer;
1.169     harris41  889: }
                    890: 
1.1       albertel  891: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       892: 
1.1       albertel  893: sub authenticate {
1.1073    raeburn   894:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  895:     $upass=&escape($upass);
                    896:     $uname= &LONCAPA::clean_username($uname);
1.836     www       897:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   898:     my $newhome;
1.836     www       899:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    900: # Maybe the machine was offline and only re-appeared again recently?
                    901:         &reconlonc();
                    902: # One more
1.952     raeburn   903: 	$uhome=&homeserver($uname,$udom,1);
                    904:         if (($uhome eq 'no_host') && $checkdefauth) {
                    905:             if (defined(&domain($udom,'primary'))) {
                    906:                 $newhome=&domain($udom,'primary');
                    907:             }
                    908:             if ($newhome ne '') {
                    909:                 $uhome = $newhome;
                    910:             }
                    911:         }
1.836     www       912: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    913: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   914: 	    return 'no_host';
                    915:         }
1.1       albertel  916:     }
1.1073    raeburn   917:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  918:     if ($answer eq 'authorized') {
1.952     raeburn   919:         if ($newhome) {
                    920:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    921:             return 'no_account_on_host'; 
                    922:         } else {
                    923:             &logthis("User $uname at $udom authorized by $uhome");
                    924:             return $uhome;
                    925:         }
1.471     albertel  926:     }
                    927:     if ($answer eq 'non_authorized') {
                    928: 	&logthis("User $uname at $udom rejected by $uhome");
                    929: 	return 'no_host'; 
1.9       www       930:     }
1.471     albertel  931:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  932:     return 'no_host';
                    933: }
                    934: 
1.1073    raeburn   935: sub can_host_session {
1.1074    raeburn   936:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn   937:     my $canhost = 1;
1.1074    raeburn   938:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn   939:     if (ref($remotesessions) eq 'HASH') {
                    940:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn   941:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn   942:                 $canhost = 0;
                    943:             } else {
                    944:                 $canhost = 1;
                    945:             }
                    946:         }
                    947:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn   948:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn   949:                 $canhost = 1;
                    950:             } else {
                    951:                 $canhost = 0;
                    952:             }
                    953:         }
                    954:         if ($canhost) {
                    955:             if ($remotesessions->{'version'} ne '') {
                    956:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                    957:                 if ($reqmajor ne '' && $reqminor ne '') {
                    958:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                    959:                         my $major = $1;
                    960:                         my $minor = $2;
                    961:                         if (($major < $reqmajor ) ||
                    962:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                    963:                             $canhost = 0;
                    964:                         }
                    965:                     } else {
                    966:                         $canhost = 0;
                    967:                     }
                    968:                 }
                    969:             }
                    970:         }
                    971:     }
                    972:     if ($canhost) {
                    973:         if (ref($hostedsessions) eq 'HASH') {
                    974:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                    975:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                    976:                     $canhost = 0;
                    977:                 } else {
                    978:                     $canhost = 1;
                    979:                 }
                    980:             }
                    981:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                    982:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                    983:                     $canhost = 1;
                    984:                 } else {
                    985:                     $canhost = 0;
                    986:                 }
                    987:             }
                    988:         }
                    989:     }
                    990:     return $canhost;
                    991: }
                    992: 
1.1       albertel  993: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       994: 
1.599     albertel  995: my %homecache;
1.1       albertel  996: sub homeserver {
1.230     stredwic  997:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  998:     my $index="$uname:$udom";
1.426     albertel  999: 
1.599     albertel 1000:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1001: 
                   1002:     my %servers = &get_servers($udom,'library');
                   1003:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1004:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1005: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1006: 
                   1007: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1008: 	if ($answer eq 'found') {
                   1009: 	    delete($badServerCache{$tryserver}); 
                   1010: 	    return $homecache{$index}=$tryserver;
                   1011: 	} elsif ($answer eq 'no_host') {
                   1012: 	    $badServerCache{$tryserver}=1;
                   1013: 	}
1.1       albertel 1014:     }    
                   1015:     return 'no_host';
1.70      www      1016: }
                   1017: 
                   1018: # ------------------------------------- Find the usernames behind a list of IDs
                   1019: 
                   1020: sub idget {
                   1021:     my ($udom,@ids)=@_;
                   1022:     my %returnhash=();
                   1023:     
1.841     albertel 1024:     my %servers = &get_servers($udom,'library');
                   1025:     foreach my $tryserver (keys(%servers)) {
                   1026: 	my $idlist=join('&',@ids);
                   1027: 	$idlist=~tr/A-Z/a-z/; 
                   1028: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1029: 	my @answer=();
                   1030: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1031: 	    @answer=split(/\&/,$reply);
                   1032: 	}                    ;
                   1033: 	my $i;
                   1034: 	for ($i=0;$i<=$#ids;$i++) {
                   1035: 	    if ($answer[$i]) {
                   1036: 		$returnhash{$ids[$i]}=$answer[$i];
                   1037: 	    } 
                   1038: 	}
                   1039:     } 
1.70      www      1040:     return %returnhash;
                   1041: }
                   1042: 
                   1043: # ------------------------------------- Find the IDs behind a list of usernames
                   1044: 
                   1045: sub idrget {
                   1046:     my ($udom,@unames)=@_;
                   1047:     my %returnhash=();
1.800     albertel 1048:     foreach my $uname (@unames) {
                   1049:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1050:     }
1.70      www      1051:     return %returnhash;
                   1052: }
                   1053: 
                   1054: # ------------------------------- Store away a list of names and associated IDs
                   1055: 
                   1056: sub idput {
                   1057:     my ($udom,%ids)=@_;
                   1058:     my %servers=();
1.800     albertel 1059:     foreach my $uname (keys(%ids)) {
                   1060: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1061:         my $uhom=&homeserver($uname,$udom);
1.70      www      1062:         if ($uhom ne 'no_host') {
1.800     albertel 1063:             my $id=&escape($ids{$uname});
1.70      www      1064:             $id=~tr/A-Z/a-z/;
1.800     albertel 1065:             my $esc_unam=&escape($uname);
1.70      www      1066: 	    if ($servers{$uhom}) {
1.800     albertel 1067: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1068:             } else {
1.800     albertel 1069:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1070:             }
                   1071:         }
1.191     harris41 1072:     }
1.800     albertel 1073:     foreach my $server (keys(%servers)) {
                   1074:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1075:     }
1.344     www      1076: }
                   1077: 
1.1023    raeburn  1078: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1079: sub dump_dom {
1.1023    raeburn  1080:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1081:     if (!$udom) {
                   1082:         $udom=$env{'user.domain'};
                   1083:     }
                   1084:     my %returnhash;
1.1023    raeburn  1085:     if ($udom) {
                   1086:         my $uname = &get_domainconfiguser($udom);
                   1087:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1088:     }
                   1089:     return %returnhash;
                   1090: }
                   1091: 
1.1023    raeburn  1092: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1093: 
                   1094: sub get_dom {
1.860     raeburn  1095:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1096:     my $items='';
                   1097:     foreach my $item (@$storearr) {
                   1098:         $items.=&escape($item).'&';
                   1099:     }
                   1100:     $items=~s/\&$//;
1.860     raeburn  1101:     if (!$udom) {
                   1102:         $udom=$env{'user.domain'};
                   1103:         if (defined(&domain($udom,'primary'))) {
                   1104:             $uhome=&domain($udom,'primary');
                   1105:         } else {
1.874     albertel 1106:             undef($uhome);
1.860     raeburn  1107:         }
                   1108:     } else {
                   1109:         if (!$uhome) {
                   1110:             if (defined(&domain($udom,'primary'))) {
                   1111:                 $uhome=&domain($udom,'primary');
                   1112:             }
                   1113:         }
                   1114:     }
                   1115:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1116:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1117:         my %returnhash;
1.875     albertel 1118:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1119:             return %returnhash;
                   1120:         }
1.806     raeburn  1121:         my @pairs=split(/\&/,$rep);
                   1122:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1123:             return @pairs;
                   1124:         }
                   1125:         my $i=0;
                   1126:         foreach my $item (@$storearr) {
                   1127:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1128:             $i++;
                   1129:         }
                   1130:         return %returnhash;
                   1131:     } else {
1.880     banghart 1132:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1133:     }
                   1134: }
                   1135: 
                   1136: # -------------------------------------------- put items in domain db files 
                   1137: 
                   1138: sub put_dom {
1.860     raeburn  1139:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1140:     if (!$udom) {
                   1141:         $udom=$env{'user.domain'};
                   1142:         if (defined(&domain($udom,'primary'))) {
                   1143:             $uhome=&domain($udom,'primary');
                   1144:         } else {
1.874     albertel 1145:             undef($uhome);
1.860     raeburn  1146:         }
                   1147:     } else {
                   1148:         if (!$uhome) {
                   1149:             if (defined(&domain($udom,'primary'))) {
                   1150:                 $uhome=&domain($udom,'primary');
                   1151:             }
                   1152:         }
                   1153:     } 
                   1154:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1155:         my $items='';
                   1156:         foreach my $item (keys(%$storehash)) {
                   1157:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1158:         }
                   1159:         $items=~s/\&$//;
                   1160:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1161:     } else {
1.860     raeburn  1162:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1163:     }
                   1164: }
                   1165: 
1.1023    raeburn  1166: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1167: sub newput_dom {
1.1023    raeburn  1168:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1169:     my $result;
                   1170:     if (!$udom) {
                   1171:         $udom=$env{'user.domain'};
                   1172:     }
1.1023    raeburn  1173:     if ($udom) {
                   1174:         my $uname = &get_domainconfiguser($udom);
                   1175:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1176:     }
                   1177:     return $result;
                   1178: }
                   1179: 
1.1023    raeburn  1180: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1181: sub del_dom {
1.1023    raeburn  1182:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1183:     if (ref($storearr) eq 'ARRAY') {
                   1184:         if (!$udom) {
                   1185:             $udom=$env{'user.domain'};
                   1186:         }
1.1023    raeburn  1187:         if ($udom) {
                   1188:             my $uname = &get_domainconfiguser($udom); 
                   1189:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1190:         }
                   1191:     }
                   1192: }
                   1193: 
1.1023    raeburn  1194: # ----------------------------------construct domainconfig user for a domain 
                   1195: sub get_domainconfiguser {
                   1196:     my ($udom) = @_;
                   1197:     return $udom.'-domainconfig';
                   1198: }
                   1199: 
1.837     raeburn  1200: sub retrieve_inst_usertypes {
                   1201:     my ($udom) = @_;
                   1202:     my (%returnhash,@order);
1.989     raeburn  1203:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1204:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1205:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1206:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1207:         @order = @{$domdefs{'inststatusorder'}};
                   1208:     } else {
                   1209:         if (defined(&domain($udom,'primary'))) {
                   1210:             my $uhome=&domain($udom,'primary');
                   1211:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1212:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1213:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1214:                 return (\%returnhash,\@order);
                   1215:             }
                   1216:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1217:             my @pairs=split(/\&/,$hashitems);
                   1218:             foreach my $item (@pairs) {
                   1219:                 my ($key,$value)=split(/=/,$item,2);
                   1220:                 $key = &unescape($key);
                   1221:                 next if ($key =~ /^error: 2 /);
                   1222:                 $returnhash{$key}=&thaw_unescape($value);
                   1223:             }
                   1224:             my @esc_order = split(/\&/,$orderitems);
                   1225:             foreach my $item (@esc_order) {
                   1226:                 push(@order,&unescape($item));
                   1227:             }
                   1228:         } else {
                   1229:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1230:         }
                   1231:     }
                   1232:     return (\%returnhash,\@order);
                   1233: }
                   1234: 
1.868     raeburn  1235: sub is_domainimage {
                   1236:     my ($url) = @_;
                   1237:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1238:         if (&domain($1) ne '') {
                   1239:             return '1';
                   1240:         }
                   1241:     }
                   1242:     return;
                   1243: }
                   1244: 
1.899     raeburn  1245: sub inst_directory_query {
                   1246:     my ($srch) = @_;
                   1247:     my $udom = $srch->{'srchdomain'};
                   1248:     my %results;
                   1249:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1250:     my $outcome;
1.899     raeburn  1251:     if ($homeserver ne '') {
1.904     albertel 1252: 	my $queryid=&reply("querysend:instdirsearch:".
                   1253: 			   &escape($srch->{'srchby'}).':'.
                   1254: 			   &escape($srch->{'srchterm'}).':'.
                   1255: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1256: 	my $host=&hostname($homeserver);
                   1257: 	if ($queryid !~/^\Q$host\E\_/) {
                   1258: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1259: 	    return;
                   1260: 	}
                   1261: 	my $response = &get_query_reply($queryid);
                   1262: 	my $maxtries = 5;
                   1263: 	my $tries = 1;
                   1264: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1265: 	    $response = &get_query_reply($queryid);
                   1266: 	    $tries ++;
                   1267: 	}
                   1268: 
                   1269:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1270:             if ($response eq 'unavailable') {
                   1271:                 $outcome = $response;
                   1272:             } else {
                   1273:                 $outcome = 'ok';
                   1274:                 my @matches = split(/\n/,$response);
                   1275:                 foreach my $match (@matches) {
                   1276:                     my ($key,$value) = split(/=/,$match);
                   1277:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1278:                 }
1.899     raeburn  1279:             }
                   1280:         }
                   1281:     }
1.909     raeburn  1282:     return ($outcome,%results);
1.899     raeburn  1283: }
                   1284: 
                   1285: sub usersearch {
                   1286:     my ($srch) = @_;
                   1287:     my $dom = $srch->{'srchdomain'};
                   1288:     my %results;
                   1289:     my %libserv = &all_library();
                   1290:     my $query = 'usersearch';
                   1291:     foreach my $tryserver (keys(%libserv)) {
                   1292:         if (&host_domain($tryserver) eq $dom) {
                   1293:             my $host=&hostname($tryserver);
                   1294:             my $queryid=
1.911     raeburn  1295:                 &reply("querysend:".&escape($query).':'.
                   1296:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1297:                        &escape($srch->{'srchtype'}).':'.
                   1298:                        &escape($srch->{'srchterm'}),$tryserver);
                   1299:             if ($queryid !~/^\Q$host\E\_/) {
                   1300:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1301:                 next;
1.899     raeburn  1302:             }
                   1303:             my $reply = &get_query_reply($queryid);
                   1304:             my $maxtries = 1;
                   1305:             my $tries = 1;
                   1306:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1307:                 $reply = &get_query_reply($queryid);
                   1308:                 $tries ++;
                   1309:             }
                   1310:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1311:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1312:             } else {
1.911     raeburn  1313:                 my @matches;
                   1314:                 if ($reply =~ /\n/) {
                   1315:                     @matches = split(/\n/,$reply);
                   1316:                 } else {
                   1317:                     @matches = split(/\&/,$reply);
                   1318:                 }
1.899     raeburn  1319:                 foreach my $match (@matches) {
                   1320:                     my ($uname,$udom,%userhash);
1.911     raeburn  1321:                     foreach my $entry (split(/:/,$match)) {
                   1322:                         my ($key,$value) =
                   1323:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1324:                         $userhash{$key} = $value;
                   1325:                         if ($key eq 'username') {
                   1326:                             $uname = $value;
                   1327:                         } elsif ($key eq 'domain') {
                   1328:                             $udom = $value;
1.911     raeburn  1329:                         }
1.899     raeburn  1330:                     }
                   1331:                     $results{$uname.':'.$udom} = \%userhash;
                   1332:                 }
                   1333:             }
                   1334:         }
                   1335:     }
                   1336:     return %results;
                   1337: }
                   1338: 
1.912     raeburn  1339: sub get_instuser {
                   1340:     my ($udom,$uname,$id) = @_;
                   1341:     my $homeserver = &domain($udom,'primary');
                   1342:     my ($outcome,%results);
                   1343:     if ($homeserver ne '') {
                   1344:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1345:                            &escape($id).':'.&escape($udom),$homeserver);
                   1346:         my $host=&hostname($homeserver);
                   1347:         if ($queryid !~/^\Q$host\E\_/) {
                   1348:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1349:             return;
                   1350:         }
                   1351:         my $response = &get_query_reply($queryid);
                   1352:         my $maxtries = 5;
                   1353:         my $tries = 1;
                   1354:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1355:             $response = &get_query_reply($queryid);
                   1356:             $tries ++;
                   1357:         }
                   1358:         if (!&error($response) && $response ne 'refused') {
                   1359:             if ($response eq 'unavailable') {
                   1360:                 $outcome = $response;
                   1361:             } else {
                   1362:                 $outcome = 'ok';
                   1363:                 my @matches = split(/\n/,$response);
                   1364:                 foreach my $match (@matches) {
                   1365:                     my ($key,$value) = split(/=/,$match);
                   1366:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1367:                 }
                   1368:             }
                   1369:         }
                   1370:     }
                   1371:     my %userinfo;
                   1372:     if (ref($results{$uname}) eq 'HASH') {
                   1373:         %userinfo = %{$results{$uname}};
                   1374:     } 
                   1375:     return ($outcome,%userinfo);
                   1376: }
                   1377: 
                   1378: sub inst_rulecheck {
1.923     raeburn  1379:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1380:     my %returnhash;
                   1381:     if ($udom ne '') {
                   1382:         if (ref($rules) eq 'ARRAY') {
                   1383:             @{$rules} = map {&escape($_);} (@{$rules});
                   1384:             my $rulestr = join(':',@{$rules});
                   1385:             my $homeserver=&domain($udom,'primary');
                   1386:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1387:                 my $response;
                   1388:                 if ($item eq 'username') {                
                   1389:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1390:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1391:                                               $homeserver));
1.923     raeburn  1392:                 } elsif ($item eq 'id') {
                   1393:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1394:                                               ':'.&escape($id).':'.$rulestr,
                   1395:                                               $homeserver));
1.945     raeburn  1396:                 } elsif ($item eq 'selfcreate') {
                   1397:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1398:                                                &escape($udom).':'.&escape($uname).
                   1399:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1400:                 }
1.912     raeburn  1401:                 if ($response ne 'refused') {
                   1402:                     my @pairs=split(/\&/,$response);
                   1403:                     foreach my $item (@pairs) {
                   1404:                         my ($key,$value)=split(/=/,$item,2);
                   1405:                         $key = &unescape($key);
                   1406:                         next if ($key =~ /^error: 2 /);
                   1407:                         $returnhash{$key}=&thaw_unescape($value);
                   1408:                     }
                   1409:                 }
                   1410:             }
                   1411:         }
                   1412:     }
                   1413:     return %returnhash;
                   1414: }
                   1415: 
                   1416: sub inst_userrules {
1.923     raeburn  1417:     my ($udom,$check) = @_;
1.912     raeburn  1418:     my (%ruleshash,@ruleorder);
                   1419:     if ($udom ne '') {
                   1420:         my $homeserver=&domain($udom,'primary');
                   1421:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1422:             my $response;
                   1423:             if ($check eq 'id') {
                   1424:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1425:                                  $homeserver);
1.943     raeburn  1426:             } elsif ($check eq 'email') {
                   1427:                 $response=&reply('instemailrules:'.&escape($udom),
                   1428:                                  $homeserver);
1.923     raeburn  1429:             } else {
                   1430:                 $response=&reply('instuserrules:'.&escape($udom),
                   1431:                                  $homeserver);
                   1432:             }
1.912     raeburn  1433:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1434:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1435:                 ($response ne 'no_such_host')) {
                   1436:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1437:                 my @pairs=split(/\&/,$hashitems);
                   1438:                 foreach my $item (@pairs) {
                   1439:                     my ($key,$value)=split(/=/,$item,2);
                   1440:                     $key = &unescape($key);
                   1441:                     next if ($key =~ /^error: 2 /);
                   1442:                     $ruleshash{$key}=&thaw_unescape($value);
                   1443:                 }
                   1444:                 my @esc_order = split(/\&/,$orderitems);
                   1445:                 foreach my $item (@esc_order) {
                   1446:                     push(@ruleorder,&unescape($item));
                   1447:                 }
                   1448:             }
                   1449:         }
                   1450:     }
                   1451:     return (\%ruleshash,\@ruleorder);
                   1452: }
                   1453: 
1.976     raeburn  1454: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1455: 
                   1456: sub get_domain_defaults {
                   1457:     my ($domain) = @_;
                   1458:     my $cachetime = 60*60*24;
                   1459:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1460:     if (defined($cached)) {
                   1461:         if (ref($result) eq 'HASH') {
                   1462:             return %{$result};
                   1463:         }
                   1464:     }
                   1465:     my %domdefaults;
                   1466:     my %domconfig =
1.989     raeburn  1467:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1468:                                   'requestcourses','inststatus',
1.1073    raeburn  1469:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1470:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1471:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1472:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1473:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1474:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1475:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1476:     } else {
                   1477:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1478:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1479:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1480:     }
1.976     raeburn  1481:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1482:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1483:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1484:         } else {
                   1485:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1486:         } 
                   1487:         my @usertools = ('aboutme','blog','portfolio');
                   1488:         foreach my $item (@usertools) {
                   1489:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1490:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1491:             }
                   1492:         }
                   1493:     }
1.985     raeburn  1494:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1495:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1496:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1497:         }
                   1498:     }
1.989     raeburn  1499:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1500:         foreach my $item ('inststatustypes','inststatusorder') {
                   1501:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1502:         }
                   1503:     }
1.1047    raeburn  1504:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1505:         foreach my $item ('canuse_pdfforms') {
                   1506:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1507:         }
                   1508:     }
1.1073    raeburn  1509:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1510:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1511:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1512:         }
                   1513:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1514:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1515:         }
                   1516:     }
1.943     raeburn  1517:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1518:                                   $cachetime);
                   1519:     return %domdefaults;
                   1520: }
                   1521: 
1.344     www      1522: # --------------------------------------------------- Assign a key to a student
                   1523: 
                   1524: sub assign_access_key {
1.364     www      1525: #
                   1526: # a valid key looks like uname:udom#comments
                   1527: # comments are being appended
                   1528: #
1.498     www      1529:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1530:     $kdom=
1.620     albertel 1531:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1532:     $knum=
1.620     albertel 1533:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1534:     $cdom=
1.620     albertel 1535:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1536:     $cnum=
1.620     albertel 1537:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1538:     $udom=$env{'user.name'} unless (defined($udom));
                   1539:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1540:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1541:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1542:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1543:                                                   # assigned to this person
                   1544:                                                   # - this should not happen,
1.345     www      1545:                                                   # unless something went wrong
                   1546:                                                   # the first time around
                   1547: # ready to assign
1.364     www      1548:         $logentry=$1.'; '.$logentry;
1.496     www      1549:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1550:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1551: # key now belongs to user
1.346     www      1552: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1553:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1554:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1555:                 return 'ok';
                   1556:             } else {
                   1557:                 return 
                   1558:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1559: 	    }
                   1560:         } else {
                   1561:             return 'error: Could not assign key, try again later.';
                   1562:         }
1.364     www      1563:     } elsif (!$existing{$ckey}) {
1.345     www      1564: # the key does not exist
                   1565: 	return 'error: The key does not exist';
                   1566:     } else {
                   1567: # the key is somebody else's
                   1568: 	return 'error: The key is already in use';
                   1569:     }
1.344     www      1570: }
                   1571: 
1.364     www      1572: # ------------------------------------------ put an additional comment on a key
                   1573: 
                   1574: sub comment_access_key {
                   1575: #
                   1576: # a valid key looks like uname:udom#comments
                   1577: # comments are being appended
                   1578: #
                   1579:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1580:     $cdom=
1.620     albertel 1581:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1582:     $cnum=
1.620     albertel 1583:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1584:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1585:     if ($existing{$ckey}) {
                   1586:         $existing{$ckey}.='; '.$logentry;
                   1587: # ready to assign
1.367     www      1588:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1589:                                                  $cdom,$cnum) eq 'ok') {
                   1590: 	    return 'ok';
                   1591:         } else {
                   1592: 	    return 'error: Count not store comment.';
                   1593:         }
                   1594:     } else {
                   1595: # the key does not exist
                   1596: 	return 'error: The key does not exist';
                   1597:     }
                   1598: }
                   1599: 
1.344     www      1600: # ------------------------------------------------------ Generate a set of keys
                   1601: 
                   1602: sub generate_access_keys {
1.364     www      1603:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1604:     $cdom=
1.620     albertel 1605:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1606:     $cnum=
1.620     albertel 1607:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1608:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1609:     unless (($cdom) && ($cnum)) { return 0; }
                   1610:     if ($number>10000) { return 0; }
                   1611:     sleep(2); # make sure don't get same seed twice
                   1612:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1613:     my $total=0;
                   1614:     for (my $i=1;$i<=$number;$i++) {
                   1615:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1616:                   sprintf("%lx",int(100000*rand)).'-'.
                   1617:                   sprintf("%lx",int(100000*rand));
                   1618:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1619:        $newkey=~s/0/h/g; # and also 0 and O
                   1620:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1621:        if ($existing{$newkey}) {
                   1622:            $i--;
                   1623:        } else {
1.364     www      1624: 	  if (&put('accesskeys',
                   1625:               { $newkey => '# generated '.localtime().
1.620     albertel 1626:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1627:                            '; '.$logentry },
                   1628: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1629:               $total++;
                   1630: 	  }
                   1631:        }
                   1632:     }
1.620     albertel 1633:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1634:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1635:     return $total;
                   1636: }
                   1637: 
                   1638: # ------------------------------------------------------- Validate an accesskey
                   1639: 
                   1640: sub validate_access_key {
                   1641:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1642:     $cdom=
1.620     albertel 1643:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1644:     $cnum=
1.620     albertel 1645:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1646:     $udom=$env{'user.domain'} unless (defined($udom));
                   1647:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1648:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1649:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1650: }
                   1651: 
                   1652: # ------------------------------------- Find the section of student in a course
1.652     albertel 1653: sub devalidate_getsection_cache {
                   1654:     my ($udom,$unam,$courseid)=@_;
                   1655:     my $hashid="$udom:$unam:$courseid";
                   1656:     &devalidate_cache_new('getsection',$hashid);
                   1657: }
1.298     matthew  1658: 
1.815     albertel 1659: sub courseid_to_courseurl {
                   1660:     my ($courseid) = @_;
                   1661:     #already url style courseid
                   1662:     return $courseid if ($courseid =~ m{^/});
                   1663: 
                   1664:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1665: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1666: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1667: 	return "/$cdom/$cnum";
                   1668:     }
                   1669: 
                   1670:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1671:     if (exists($courseinfo{'num'})) {
                   1672: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1673:     }
                   1674: 
                   1675:     return undef;
                   1676: }
                   1677: 
1.298     matthew  1678: sub getsection {
                   1679:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1680:     my $cachetime=1800;
1.551     albertel 1681: 
                   1682:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1683:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1684:     if (defined($cached)) { return $result; }
                   1685: 
1.298     matthew  1686:     my %Pending; 
                   1687:     my %Expired;
                   1688:     #
                   1689:     # Each role can either have not started yet (pending), be active, 
                   1690:     #    or have expired.
                   1691:     #
                   1692:     # If there is an active role, we are done.
                   1693:     #
                   1694:     # If there is more than one role which has not started yet, 
                   1695:     #     choose the one which will start sooner
                   1696:     # If there is one role which has not started yet, return it.
                   1697:     #
                   1698:     # If there is more than one expired role, choose the one which ended last.
                   1699:     # If there is a role which has expired, return it.
                   1700:     #
1.815     albertel 1701:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1702:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1703:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1704:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1705:         my $section=$1;
                   1706:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1707:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1708:         my $now=time;
1.548     albertel 1709:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1710:             $Expired{$end}=$section;
                   1711:             next;
                   1712:         }
1.548     albertel 1713:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1714:             $Pending{$start}=$section;
                   1715:             next;
                   1716:         }
1.599     albertel 1717:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1718:     }
                   1719:     #
                   1720:     # Presumedly there will be few matching roles from the above
                   1721:     # loop and the sorting time will be negligible.
                   1722:     if (scalar(keys(%Pending))) {
                   1723:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1724:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1725:     } 
                   1726:     if (scalar(keys(%Expired))) {
                   1727:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1728:         my $time = pop(@sorted);
1.599     albertel 1729:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1730:     }
1.599     albertel 1731:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1732: }
1.70      www      1733: 
1.599     albertel 1734: sub save_cache {
                   1735:     &purge_remembered();
1.722     albertel 1736:     #&Apache::loncommon::validate_page();
1.620     albertel 1737:     undef(%env);
1.780     albertel 1738:     undef($env_loaded);
1.599     albertel 1739: }
1.452     albertel 1740: 
1.599     albertel 1741: my $to_remember=-1;
                   1742: my %remembered;
                   1743: my %accessed;
                   1744: my $kicks=0;
                   1745: my $hits=0;
1.849     albertel 1746: sub make_key {
                   1747:     my ($name,$id) = @_;
1.872     albertel 1748:     if (length($id) > 65 
                   1749: 	&& length(&escape($id)) > 200) {
                   1750: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1751:     }
1.849     albertel 1752:     return &escape($name.':'.$id);
                   1753: }
                   1754: 
1.599     albertel 1755: sub devalidate_cache_new {
                   1756:     my ($name,$id,$debug) = @_;
                   1757:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1758:     $id=&make_key($name,$id);
1.599     albertel 1759:     $memcache->delete($id);
                   1760:     delete($remembered{$id});
                   1761:     delete($accessed{$id});
                   1762: }
                   1763: 
                   1764: sub is_cached_new {
                   1765:     my ($name,$id,$debug) = @_;
1.849     albertel 1766:     $id=&make_key($name,$id);
1.599     albertel 1767:     if (exists($remembered{$id})) {
                   1768: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1769: 	$accessed{$id}=[&gettimeofday()];
                   1770: 	$hits++;
                   1771: 	return ($remembered{$id},1);
                   1772:     }
                   1773:     my $value = $memcache->get($id);
                   1774:     if (!(defined($value))) {
                   1775: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1776: 	return (undef,undef);
1.416     albertel 1777:     }
1.599     albertel 1778:     if ($value eq '__undef__') {
                   1779: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1780: 	$value=undef;
                   1781:     }
                   1782:     &make_room($id,$value,$debug);
                   1783:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1784:     return ($value,1);
                   1785: }
                   1786: 
                   1787: sub do_cache_new {
                   1788:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1789:     $id=&make_key($name,$id);
1.599     albertel 1790:     my $setvalue=$value;
                   1791:     if (!defined($setvalue)) {
                   1792: 	$setvalue='__undef__';
                   1793:     }
1.623     albertel 1794:     if (!defined($time) ) {
                   1795: 	$time=600;
                   1796:     }
1.599     albertel 1797:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1798:     my $result = $memcache->set($id,$setvalue,$time);
                   1799:     if (! $result) {
1.872     albertel 1800: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1801: 	$memcache->disconnect_all();
1.872     albertel 1802:     }
1.600     albertel 1803:     # need to make a copy of $value
1.919     albertel 1804:     &make_room($id,$value,$debug);
1.599     albertel 1805:     return $value;
                   1806: }
                   1807: 
                   1808: sub make_room {
                   1809:     my ($id,$value,$debug)=@_;
1.919     albertel 1810: 
                   1811:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1812:                                     : $value;
1.599     albertel 1813:     if ($to_remember<0) { return; }
                   1814:     $accessed{$id}=[&gettimeofday()];
                   1815:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1816:     my $to_kick;
                   1817:     my $max_time=0;
                   1818:     foreach my $other (keys(%accessed)) {
                   1819: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1820: 	    $to_kick=$other;
                   1821: 	    $max_time=&tv_interval($accessed{$other});
                   1822: 	}
                   1823:     }
                   1824:     delete($remembered{$to_kick});
                   1825:     delete($accessed{$to_kick});
                   1826:     $kicks++;
                   1827:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1828:     return;
                   1829: }
                   1830: 
1.599     albertel 1831: sub purge_remembered {
1.604     albertel 1832:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1833:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1834:     undef(%remembered);
                   1835:     undef(%accessed);
1.428     albertel 1836: }
1.70      www      1837: # ------------------------------------- Read an entry from a user's environment
                   1838: 
                   1839: sub userenvironment {
                   1840:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1841:     my $items;
                   1842:     foreach my $item (@what) {
                   1843:         $items.=&escape($item).'&';
                   1844:     }
                   1845:     $items=~s/\&$//;
1.70      www      1846:     my %returnhash=();
1.1009    raeburn  1847:     my $uhome = &homeserver($unam,$udom);
                   1848:     unless ($uhome eq 'no_host') {
                   1849:         my @answer=split(/\&/, 
                   1850:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1851:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1852:             return %returnhash;
                   1853:         }
1.1009    raeburn  1854:         my $i;
                   1855:         for ($i=0;$i<=$#what;$i++) {
                   1856: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1857:         }
1.70      www      1858:     }
                   1859:     return %returnhash;
1.1       albertel 1860: }
                   1861: 
1.617     albertel 1862: # ---------------------------------------------------------- Get a studentphoto
                   1863: sub studentphoto {
                   1864:     my ($udom,$unam,$ext) = @_;
                   1865:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1866:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1867:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1868:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1869:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1870:             } else {
                   1871:                 my ($result,$perm_reqd)=
1.707     albertel 1872: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1873:                 if ($result eq 'ok') {
                   1874:                     if (!($perm_reqd eq 'yes')) {
                   1875:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1876:                     }
                   1877:                 }
                   1878:             }
                   1879:         }
                   1880:     } else {
                   1881:         my ($result,$perm_reqd) = 
1.707     albertel 1882: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1883:         if ($result eq 'ok') {
                   1884:             if (!($perm_reqd eq 'yes')) {
                   1885:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1886:             }
                   1887:         }
                   1888:     }
                   1889:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1890: }
                   1891: 
                   1892: sub retrievestudentphoto {
                   1893:     my ($udom,$unam,$ext,$type) = @_;
                   1894:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1895:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1896:     if ($ret eq 'ok') {
                   1897:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1898:         if ($type eq 'thumbnail') {
                   1899:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1900:         }
                   1901:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1902:         return $tokenurl;
                   1903:     } else {
                   1904:         if ($type eq 'thumbnail') {
                   1905:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1906:         } else { 
                   1907:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1908:         }
1.617     albertel 1909:     }
                   1910: }
                   1911: 
1.263     www      1912: # -------------------------------------------------------------------- New chat
                   1913: 
                   1914: sub chatsend {
1.724     raeburn  1915:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1916:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1917:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1918:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1919:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1920: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1921: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1922: }
                   1923: 
                   1924: # ------------------------------------------ Find current version of a resource
                   1925: 
                   1926: sub getversion {
                   1927:     my $fname=&clutter(shift);
                   1928:     unless ($fname=~/^\/res\//) { return -1; }
                   1929:     return &currentversion(&filelocation('',$fname));
                   1930: }
                   1931: 
                   1932: sub currentversion {
                   1933:     my $fname=shift;
1.599     albertel 1934:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1935:     if (defined($cached)) { return $result; }
1.292     www      1936:     my $author=$fname;
                   1937:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1938:     my ($udom,$uname)=split(/\//,$author);
                   1939:     my $home=homeserver($uname,$udom);
                   1940:     if ($home eq 'no_host') { 
                   1941:         return -1; 
                   1942:     }
                   1943:     my $answer=reply("currentversion:$fname",$home);
                   1944:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1945: 	return -1;
                   1946:     }
1.599     albertel 1947:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1948: }
                   1949: 
1.1       albertel 1950: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1951: 
1.1       albertel 1952: sub subscribe {
                   1953:     my $fname=shift;
1.761     raeburn  1954:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1955:     $fname=~s/[\n\r]//g;
1.1       albertel 1956:     my $author=$fname;
                   1957:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1958:     my ($udom,$uname)=split(/\//,$author);
                   1959:     my $home=homeserver($uname,$udom);
1.335     albertel 1960:     if ($home eq 'no_host') {
                   1961:         return 'not_found';
1.1       albertel 1962:     }
                   1963:     my $answer=reply("sub:$fname",$home);
1.64      www      1964:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1965: 	$answer.=' by '.$home;
                   1966:     }
1.1       albertel 1967:     return $answer;
                   1968: }
                   1969:     
1.8       www      1970: # -------------------------------------------------------------- Replicate file
                   1971: 
                   1972: sub repcopy {
                   1973:     my $filename=shift;
1.23      www      1974:     $filename=~s/\/+/\//g;
1.607     raeburn  1975:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1976:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1977:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1978: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1979: 	return &repcopy_userfile($filename);
                   1980:     }
1.532     albertel 1981:     $filename=~s/[\n\r]//g;
1.8       www      1982:     my $transname="$filename.in.transfer";
1.828     www      1983: # FIXME: this should flock
1.607     raeburn  1984:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1985:     my $remoteurl=subscribe($filename);
1.64      www      1986:     if ($remoteurl =~ /^con_lost by/) {
                   1987: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1988:            return 'unavailable';
1.8       www      1989:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1990: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1991: 	   return 'not_found';
1.64      www      1992:     } elsif ($remoteurl =~ /^rejected by/) {
                   1993: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1994:            return 'forbidden';
1.20      www      1995:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1996:            return 'ok';
1.8       www      1997:     } else {
1.290     www      1998:         my $author=$filename;
                   1999:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2000:         my ($udom,$uname)=split(/\//,$author);
                   2001:         my $home=homeserver($uname,$udom);
                   2002:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2003:            my @parts=split(/\//,$filename);
                   2004:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2005:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2006:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2007: 	       return 'bad_request';
1.8       www      2008:            }
                   2009:            my $count;
                   2010:            for ($count=5;$count<$#parts;$count++) {
                   2011:                $path.="/$parts[$count]";
                   2012:                if ((-e $path)!=1) {
                   2013: 		   mkdir($path,0777);
                   2014:                }
                   2015:            }
                   2016:            my $ua=new LWP::UserAgent;
                   2017:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2018:            my $response=$ua->request($request,$transname);
                   2019:            if ($response->is_error()) {
                   2020: 	       unlink($transname);
                   2021:                my $message=$response->status_line;
1.672     albertel 2022:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2023:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2024:                return 'unavailable';
1.8       www      2025:            } else {
1.16      www      2026: 	       if ($remoteurl!~/\.meta$/) {
                   2027:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2028:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2029:                   if ($mresponse->is_error()) {
                   2030: 		      unlink($filename.'.meta');
                   2031:                       &logthis(
1.672     albertel 2032:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2033:                   }
                   2034: 	       }
1.8       www      2035:                rename($transname,$filename);
1.607     raeburn  2036:                return 'ok';
1.8       www      2037:            }
1.290     www      2038:        }
1.8       www      2039:     }
1.330     www      2040: }
                   2041: 
                   2042: # ------------------------------------------------ Get server side include body
                   2043: sub ssi_body {
1.381     albertel 2044:     my ($filelink,%form)=@_;
1.606     matthew  2045:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2046:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2047:     }
1.953     www      2048:     my $output='';
                   2049:     my $response;
1.980     raeburn  2050:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2051:        ($output,$response)=&externalssi($filelink);
1.953     www      2052:     } else {
1.1004    droeschl 2053:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2054:        $filelink .= 'inhibitmenu=yes';
1.953     www      2055:        ($output,$response)=&ssi($filelink,%form);
                   2056:     }
1.778     albertel 2057:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2058:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2059:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2060:     if (wantarray) {
                   2061:         return ($output, $response);
                   2062:     } else {
                   2063:         return $output;
                   2064:     }
1.8       www      2065: }
                   2066: 
1.15      www      2067: # --------------------------------------------------------- Server Side Include
                   2068: 
1.782     albertel 2069: sub absolute_url {
                   2070:     my ($host_name) = @_;
                   2071:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2072:     if ($host_name eq '') {
                   2073: 	$host_name = $ENV{'SERVER_NAME'};
                   2074:     }
                   2075:     return $protocol.$host_name;
                   2076: }
                   2077: 
1.942     foxr     2078: #
                   2079: #   Server side include.
                   2080: # Parameters:
                   2081: #  fn     Possibly encrypted resource name/id.
                   2082: #  form   Hash that describes how the rendering should be done
                   2083: #         and other things.
1.944     foxr     2084: # Returns:
1.950     raeburn  2085: #   Scalar context: The content of the response.
                   2086: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2087: #     
1.15      www      2088: sub ssi {
                   2089: 
1.944     foxr     2090:     my ($fn,%form)=@_;
1.15      www      2091:     my $ua=new LWP::UserAgent;
1.23      www      2092:     my $request;
1.711     albertel 2093: 
                   2094:     $form{'no_update_last_known'}=1;
1.895     albertel 2095:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2096:     if (%form) {
1.782     albertel 2097:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2098:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2099:     } else {
1.782     albertel 2100:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2101:     }
                   2102: 
1.15      www      2103:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2104:     my $response=$ua->request($request);
                   2105: 
1.944     foxr     2106:     if (wantarray) {
                   2107: 	return ($response->content, $response);
                   2108:     } else {
                   2109: 	return $response->content;
1.942     foxr     2110:     }
1.324     www      2111: }
                   2112: 
                   2113: sub externalssi {
                   2114:     my ($url)=@_;
                   2115:     my $ua=new LWP::UserAgent;
                   2116:     my $request=new HTTP::Request('GET',$url);
                   2117:     my $response=$ua->request($request);
1.954     raeburn  2118:     if (wantarray) {
                   2119:         return ($response->content, $response);
                   2120:     } else {
                   2121:         return $response->content;
                   2122:     }
1.15      www      2123: }
1.254     www      2124: 
1.492     albertel 2125: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2126: 
                   2127: sub allowuploaded {
                   2128:     my ($srcurl,$url)=@_;
                   2129:     $url=&clutter(&declutter($url));
                   2130:     my $dir=$url;
                   2131:     $dir=~s/\/[^\/]+$//;
                   2132:     my %httpref=();
                   2133:     my $httpurl=&hreflocation('',$url);
                   2134:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2135:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2136: }
1.477     raeburn  2137: 
1.478     albertel 2138: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2139: # input: action, courseID, current domain, intended
1.637     raeburn  2140: #        path to file, source of file, instruction to parse file for objects,
                   2141: #        ref to hash for embedded objects,
                   2142: #        ref to hash for codebase of java objects.
                   2143: #
1.485     raeburn  2144: # output: url to file (if action was uploaddoc), 
                   2145: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2146: #
1.478     albertel 2147: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2148: # course.
1.477     raeburn  2149: #
1.478     albertel 2150: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2151: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2152: #          course's home server.
1.477     raeburn  2153: #
1.478     albertel 2154: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2155: #          be copied from $source (current location) to 
                   2156: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2157: #         and will then be copied to
                   2158: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2159: #         course's home server.
1.485     raeburn  2160: #
1.481     raeburn  2161: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2162: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2163: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2164: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2165: #         in course's home server.
1.637     raeburn  2166: #
1.477     raeburn  2167: 
                   2168: sub process_coursefile {
1.638     albertel 2169:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2170:     my $fetchresult;
1.638     albertel 2171:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2172:     if ($action eq 'propagate') {
1.638     albertel 2173:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2174: 			     $home);
1.481     raeburn  2175:     } else {
1.477     raeburn  2176:         my $fpath = '';
                   2177:         my $fname = $file;
1.478     albertel 2178:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2179:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2180:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2181:         if ($action eq 'copy') {
                   2182:             if ($source eq '') {
                   2183:                 $fetchresult = 'no source file';
                   2184:                 return $fetchresult;
                   2185:             } else {
                   2186:                 my $destination = $filepath.'/'.$fname;
                   2187:                 rename($source,$destination);
                   2188:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2189:                                  $home);
1.481     raeburn  2190:             }
                   2191:         } elsif ($action eq 'uploaddoc') {
                   2192:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2193:             print $fh $env{'form.'.$source};
1.481     raeburn  2194:             close($fh);
1.637     raeburn  2195:             if ($parser eq 'parse') {
1.1024    raeburn  2196:                 my $mm = new File::MMagic;
                   2197:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2198:                 if ($mime_type eq 'text/html') {
                   2199:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2200:                     unless ($parse_result eq 'ok') {
                   2201:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2202:                     }
1.637     raeburn  2203:                 }
                   2204:             }
1.477     raeburn  2205:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2206:                                  $home);
1.481     raeburn  2207:             if ($fetchresult eq 'ok') {
                   2208:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2209:             } else {
                   2210:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2211:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2212:                 return '/adm/notfound.html';
                   2213:             }
1.477     raeburn  2214:         }
                   2215:     }
1.485     raeburn  2216:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2217:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2218:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2219:     }
                   2220:     return $fetchresult;
                   2221: }
                   2222: 
1.637     raeburn  2223: sub build_filepath {
                   2224:     my ($fpath) = @_;
                   2225:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2226:     unless ($fpath eq '') {
                   2227:         my @parts=split('/',$fpath);
                   2228:         foreach my $part (@parts) {
                   2229:             $filepath.= '/'.$part;
                   2230:             if ((-e $filepath)!=1) {
                   2231:                 mkdir($filepath,0777);
                   2232:             }
                   2233:         }
                   2234:     }
                   2235:     return $filepath;
                   2236: }
                   2237: 
                   2238: sub store_edited_file {
1.638     albertel 2239:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2240:     my $file = $primary_url;
                   2241:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2242:     my $fpath = '';
                   2243:     my $fname = $file;
                   2244:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2245:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2246:     my $filepath = &build_filepath($fpath);
                   2247:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2248:     print $fh $content;
                   2249:     close($fh);
1.638     albertel 2250:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2251:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2252: 			  $home);
1.637     raeburn  2253:     if ($$fetchresult eq 'ok') {
                   2254:         return '/uploaded/'.$fpath.'/'.$fname;
                   2255:     } else {
1.638     albertel 2256:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2257: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2258:         return '/adm/notfound.html';
                   2259:     }
                   2260: }
                   2261: 
1.531     albertel 2262: sub clean_filename {
1.831     albertel 2263:     my ($fname,$args)=@_;
1.315     www      2264: # Replace Windows backslashes by forward slashes
1.257     www      2265:     $fname=~s/\\/\//g;
1.831     albertel 2266:     if (!$args->{'keep_path'}) {
                   2267:         # Get rid of everything but the actual filename
                   2268: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2269:     }
1.315     www      2270: # Replace spaces by underscores
                   2271:     $fname=~s/\s+/\_/g;
                   2272: # Replace all other weird characters by nothing
1.831     albertel 2273:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2274: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2275: # numbers
                   2276:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2277:     return $fname;
                   2278: }
1.1051    raeburn  2279: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2280: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2281: # image with the same aspect ratio as the original, but with dimensions which do 
                   2282: # not exceed $resizewidth and $resizeheight.
                   2283:  
1.984     neumanie 2284: sub resizeImage {
1.1051    raeburn  2285:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2286:     my $ima = Image::Magick->new;
                   2287:     my $resized;
                   2288:     if (-e $img_path) {
                   2289:         $ima->Read($img_path);
                   2290:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2291:             my $width = $ima->Get('width');
                   2292:             my $height = $ima->Get('height');
                   2293:             if ($width > $resizewidth) {
                   2294: 	        my $factor = $width/$resizewidth;
                   2295:                 my $newheight = $height/$factor;
                   2296:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2297:                 $resized = 1;
                   2298:             }
                   2299:         }
                   2300:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2301:             my $width = $ima->Get('width');
                   2302:             my $height = $ima->Get('height');
                   2303:             if ($height > $resizeheight) {
                   2304:                 my $factor = $height/$resizeheight;
                   2305:                 my $newwidth = $width/$factor;
                   2306:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2307:                 $resized = 1;
                   2308:             }
                   2309:         }
                   2310:         if ($resized) {
                   2311:             $ima->Write($img_path);
                   2312:         }
                   2313:     }
                   2314:     return;
1.977     amueller 2315: }
                   2316: 
1.608     albertel 2317: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2318: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2319: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2320: #        $coursedoc - if true up to the current course
                   2321: #                     if false
                   2322: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2323: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2324: #        $allfiles - reference to hash for embedded objects
                   2325: #        $codebase - reference to hash for codebase of java objects
                   2326: #        $desuname - username for permanent storage of uploaded file
                   2327: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2328: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2329: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2330: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2331: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2332: # 
1.686     albertel 2333: # output: url of file in userspace, or error: <message> 
                   2334: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2335: 
1.531     albertel 2336: sub userfileupload {
1.860     raeburn  2337:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2338:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2339:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2340:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2341:     $fname=&clean_filename($fname);
1.315     www      2342: # See if there is anything left
1.257     www      2343:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2344:     chop($env{'form.'.$formname});
1.523     raeburn  2345:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2346:         my $now = time;
                   2347:         my $filepath = 'tmp/helprequests/'.$now;
                   2348:         my @parts=split(/\//,$filepath);
                   2349:         my $fullpath = $perlvar{'lonDaemons'};
                   2350:         for (my $i=0;$i<@parts;$i++) {
                   2351:             $fullpath .= '/'.$parts[$i];
                   2352:             if ((-e $fullpath)!=1) {
                   2353:                 mkdir($fullpath,0777);
                   2354:             }
                   2355:         }
                   2356:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2357:         print $fh $env{'form.'.$formname};
1.523     raeburn  2358:         close($fh);
1.741     raeburn  2359:         return $fullpath.'/'.$fname;
                   2360:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2361:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2362:                        '_'.$env{'user.domain'}.'/pending';
                   2363:         my @parts=split(/\//,$filepath);
                   2364:         my $fullpath = $perlvar{'lonDaemons'};
                   2365:         for (my $i=0;$i<@parts;$i++) {
                   2366:             $fullpath .= '/'.$parts[$i];
                   2367:             if ((-e $fullpath)!=1) {
                   2368:                 mkdir($fullpath,0777);
                   2369:             }
                   2370:         }
                   2371:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2372:         print $fh $env{'form.'.$formname};
                   2373:         close($fh);
                   2374:         return $fullpath.'/'.$fname;
1.523     raeburn  2375:     }
1.995     raeburn  2376:     if ($subdir eq 'scantron') {
                   2377:         $fname = 'scantron_orig_'.$fname;
                   2378:     } else {   
1.258     www      2379: # Create the directory if not present
1.995     raeburn  2380:         $fname="$subdir/$fname";
                   2381:     }
1.259     www      2382:     if ($coursedoc) {
1.638     albertel 2383: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2384: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2385:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2386:             return &finishuserfileupload($docuname,$docudom,
                   2387: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2388: 					 $codebase,$thumbwidth,$thumbheight,
                   2389:                                          $resizewidth,$resizeheight);
1.481     raeburn  2390:         } else {
1.620     albertel 2391:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2392:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2393: 				       $fname,$formname,$parser,
                   2394: 				       $allfiles,$codebase);
1.481     raeburn  2395:         }
1.719     banghart 2396:     } elsif (defined($destuname)) {
                   2397:         my $docuname=$destuname;
                   2398:         my $docudom=$destudom;
1.860     raeburn  2399: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2400: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2401:                                      $thumbwidth,$thumbheight,
                   2402:                                      $resizewidth,$resizeheight);
1.719     banghart 2403:         
1.259     www      2404:     } else {
1.638     albertel 2405:         my $docuname=$env{'user.name'};
                   2406:         my $docudom=$env{'user.domain'};
1.714     raeburn  2407:         if (exists($env{'form.group'})) {
                   2408:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2409:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2410:         }
1.860     raeburn  2411: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2412: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2413:                                      $thumbwidth,$thumbheight,
                   2414:                                      $resizewidth,$resizeheight);
1.259     www      2415:     }
1.271     www      2416: }
                   2417: 
                   2418: sub finishuserfileupload {
1.860     raeburn  2419:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051    raeburn  2420:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477     raeburn  2421:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2422:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2423:   
1.860     raeburn  2424:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2425:     $file=$fname;
                   2426:     if ($fname=~m|/|) {
                   2427:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2428: 	$path.=$fnamepath.'/';
                   2429:     }
1.259     www      2430:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2431:     my $count;
                   2432:     for ($count=4;$count<=$#parts;$count++) {
                   2433:         $filepath.="/$parts[$count]";
                   2434:         if ((-e $filepath)!=1) {
                   2435: 	    mkdir($filepath,0777);
                   2436:         }
                   2437:     }
1.984     neumanie 2438: 
1.258     www      2439: # Save the file
                   2440:     {
1.701     albertel 2441: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2442: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2443: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2444: 	    return '/adm/notfound.html';
                   2445: 	}
                   2446: 	if (!print FH ($env{'form.'.$formname})) {
                   2447: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2448: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2449: 	    return '/adm/notfound.html';
                   2450: 	}
1.570     albertel 2451: 	close(FH);
1.1051    raeburn  2452:         if ($resizewidth && $resizeheight) {
                   2453:             my $mm = new File::MMagic;
                   2454:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2455:             if ($mime_type =~ m{^image/}) {
                   2456: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2457:             }  
1.977     amueller 2458: 	}
1.258     www      2459:     }
1.637     raeburn  2460:     if ($parser eq 'parse') {
1.1024    raeburn  2461:         my $mm = new File::MMagic;
                   2462:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2463:         if ($mime_type eq 'text/html') {
                   2464:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2465:                                                        $allfiles,$codebase);
                   2466:             unless ($parse_result eq 'ok') {
                   2467:                 &logthis('Failed to parse '.$filepath.$file.
                   2468: 	   	         ' for embedded media: '.$parse_result); 
                   2469:             }
1.637     raeburn  2470:         }
                   2471:     }
1.860     raeburn  2472:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2473:         my $input = $filepath.'/'.$file;
                   2474:         my $output = $filepath.'/'.'tn-'.$file;
                   2475:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2476:         system("convert -sample $thumbsize $input $output");
                   2477:         if (-e $filepath.'/'.'tn-'.$file) {
                   2478:             $fetchthumb  = 1; 
                   2479:         }
                   2480:     }
1.858     raeburn  2481:  
1.259     www      2482: # Notify homeserver to grep it
                   2483: #
1.984     neumanie 2484:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2485:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2486:     if ($fetchresult eq 'ok') {
1.860     raeburn  2487:         if ($fetchthumb) {
                   2488:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2489:             if ($thumbresult ne 'ok') {
                   2490:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2491:                          $docuhome.': '.$thumbresult);
                   2492:             }
                   2493:         }
1.259     www      2494: #
1.258     www      2495: # Return the URL to it
1.494     albertel 2496:         return '/uploaded/'.$path.$file;
1.263     www      2497:     } else {
1.494     albertel 2498:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2499: 		 ': '.$fetchresult);
1.263     www      2500:         return '/adm/notfound.html';
1.858     raeburn  2501:     }
1.493     albertel 2502: }
                   2503: 
1.637     raeburn  2504: sub extract_embedded_items {
1.961     raeburn  2505:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2506:     my @state = ();
                   2507:     my %javafiles = (
                   2508:                       codebase => '',
                   2509:                       code => '',
                   2510:                       archive => ''
                   2511:                     );
                   2512:     my %mediafiles = (
                   2513:                       src => '',
                   2514:                       movie => '',
                   2515:                      );
1.648     raeburn  2516:     my $p;
                   2517:     if ($content) {
                   2518:         $p = HTML::LCParser->new($content);
                   2519:     } else {
1.961     raeburn  2520:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2521:     }
1.641     albertel 2522:     while (my $t=$p->get_token()) {
1.640     albertel 2523: 	if ($t->[0] eq 'S') {
                   2524: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2525: 	    push(@state, $tagname);
1.648     raeburn  2526:             if (lc($tagname) eq 'allow') {
                   2527:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2528:             }
1.640     albertel 2529: 	    if (lc($tagname) eq 'img') {
                   2530: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2531: 	    }
1.886     albertel 2532: 	    if (lc($tagname) eq 'a') {
                   2533: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2534: 	    }
1.645     raeburn  2535:             if (lc($tagname) eq 'script') {
                   2536:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2537:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2538:                 } else {
                   2539:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2540:                 }
                   2541:             }
                   2542:             if (lc($tagname) eq 'link') {
                   2543:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2544:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2545:                 }
                   2546:             }
1.640     albertel 2547: 	    if (lc($tagname) eq 'object' ||
                   2548: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2549: 		foreach my $item (keys(%javafiles)) {
                   2550: 		    $javafiles{$item} = '';
                   2551: 		}
                   2552: 	    }
                   2553: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2554: 		my $name = lc($attr->{'name'});
                   2555: 		foreach my $item (keys(%javafiles)) {
                   2556: 		    if ($name eq $item) {
                   2557: 			$javafiles{$item} = $attr->{'value'};
                   2558: 			last;
                   2559: 		    }
                   2560: 		}
                   2561: 		foreach my $item (keys(%mediafiles)) {
                   2562: 		    if ($name eq $item) {
                   2563: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2564: 			last;
                   2565: 		    }
                   2566: 		}
                   2567: 	    }
                   2568: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2569: 		foreach my $item (keys(%javafiles)) {
                   2570: 		    if ($attr->{$item}) {
                   2571: 			$javafiles{$item} = $attr->{$item};
                   2572: 			last;
                   2573: 		    }
                   2574: 		}
                   2575: 		foreach my $item (keys(%mediafiles)) {
                   2576: 		    if ($attr->{$item}) {
                   2577: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2578: 			last;
                   2579: 		    }
                   2580: 		}
                   2581: 	    }
                   2582: 	} elsif ($t->[0] eq 'E') {
                   2583: 	    my ($tagname) = ($t->[1]);
                   2584: 	    if ($javafiles{'codebase'} ne '') {
                   2585: 		$javafiles{'codebase'} .= '/';
                   2586: 	    }  
                   2587: 	    if (lc($tagname) eq 'applet' ||
                   2588: 		lc($tagname) eq 'object' ||
                   2589: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2590: 		) {
                   2591: 		foreach my $item (keys(%javafiles)) {
                   2592: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2593: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2594: 			&add_filetype($allfiles,$file,$item);
                   2595: 		    }
                   2596: 		}
                   2597: 	    } 
                   2598: 	    pop @state;
                   2599: 	}
                   2600:     }
1.637     raeburn  2601:     return 'ok';
                   2602: }
                   2603: 
1.639     albertel 2604: sub add_filetype {
                   2605:     my ($allfiles,$file,$type)=@_;
                   2606:     if (exists($allfiles->{$file})) {
                   2607: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2608: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2609: 	}
                   2610:     } else {
                   2611: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2612:     }
                   2613: }
                   2614: 
1.493     albertel 2615: sub removeuploadedurl {
1.984     neumanie 2616:     my ($url)=@_;	
                   2617:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2618:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2619: }
                   2620: 
                   2621: sub removeuserfile {
                   2622:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2623:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2624:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2625:     if ($result eq 'ok') {	
1.798     raeburn  2626:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2627:             my $metafile = $fname.'.meta';
                   2628:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2629: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2630:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2631:             my $sqlresult = 
1.823     albertel 2632:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2633:                                         'portfolio_metadata',$group,
                   2634:                                         'delete');
1.798     raeburn  2635:         }
                   2636:     }
                   2637:     return $result;
1.257     www      2638: }
1.15      www      2639: 
1.530     albertel 2640: sub mkdiruserfile {
                   2641:     my ($docuname,$docudom,$dir)=@_;
                   2642:     my $home=&homeserver($docuname,$docudom);
                   2643:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2644: }
                   2645: 
1.531     albertel 2646: sub renameuserfile {
                   2647:     my ($docuname,$docudom,$old,$new)=@_;
                   2648:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2649:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2650:                         &escape("$old").':'.&escape("$new"),$home);
                   2651:     if ($result eq 'ok') {
                   2652:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2653:             my $oldmeta = $old.'.meta';
                   2654:             my $newmeta = $new.'.meta';
                   2655:             my $metaresult = 
                   2656:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2657: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2658:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2659:             my $sqlresult = 
1.823     albertel 2660:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2661:                                         'portfolio_metadata',$group,
                   2662:                                         'delete');
1.798     raeburn  2663:         }
                   2664:     }
                   2665:     return $result;
1.531     albertel 2666: }
                   2667: 
1.14      www      2668: # ------------------------------------------------------------------------- Log
                   2669: 
                   2670: sub log {
                   2671:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2672:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2673: }
                   2674: 
                   2675: # ------------------------------------------------------------------ Course Log
1.352     www      2676: #
                   2677: # This routine flushes several buffers of non-mission-critical nature
                   2678: #
1.157     www      2679: 
                   2680: sub flushcourselogs {
1.352     www      2681:     &logthis('Flushing log buffers');
                   2682: #
                   2683: # course logs
                   2684: # This is a log of all transactions in a course, which can be used
                   2685: # for data mining purposes
                   2686: #
                   2687: # It also collects the courseid database, which lists last transaction
                   2688: # times and course titles for all courseids
                   2689: #
                   2690:     my %courseidbuffer=();
1.921     raeburn  2691:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2692:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2693: 		          &escape($courselogs{$crsid}),
                   2694: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2695: 	    delete $courselogs{$crsid};
                   2696:         } else {
                   2697:             &logthis('Failed to flush log buffer for '.$crsid);
                   2698:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2699:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2700:                         " exceeded maximum size, deleting.</font>");
                   2701:                delete $courselogs{$crsid};
                   2702:             }
1.352     www      2703:         }
1.920     raeburn  2704:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2705:             'description' => $coursedescrbuf{$crsid},
                   2706:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2707:             'type'        => $coursetypebuf{$crsid},
                   2708:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2709:         };
1.191     harris41 2710:     }
1.352     www      2711: #
                   2712: # Write course id database (reverse lookup) to homeserver of courses 
                   2713: # Is used in pickcourse
                   2714: #
1.840     albertel 2715:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2716:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2717:                                     $courseidbuffer{$crs_home},
                   2718:                                     $crs_home,'timeonly');
1.352     www      2719:     }
                   2720: #
                   2721: # File accesses
                   2722: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2723: #
1.449     matthew  2724:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2725:         if ($entry =~ /___count$/) {
                   2726:             my ($dom,$name);
1.807     albertel 2727:             ($dom,$name,undef)=
1.811     albertel 2728: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2729:             if (! defined($dom) || $dom eq '' || 
                   2730:                 ! defined($name) || $name eq '') {
1.620     albertel 2731:                 my $cid = $env{'request.course.id'};
                   2732:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2733:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2734:             }
1.450     matthew  2735:             my $value = $accesshash{$entry};
                   2736:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2737:             my %temphash=($url => $value);
1.449     matthew  2738:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2739:             if ($result eq 'ok') {
                   2740:                 delete $accesshash{$entry};
                   2741:             } elsif ($result eq 'unknown_cmd') {
                   2742:                 # Target server has old code running on it.
1.450     matthew  2743:                 my %temphash=($entry => $value);
1.449     matthew  2744:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2745:                     delete $accesshash{$entry};
                   2746:                 }
                   2747:             }
                   2748:         } else {
1.811     albertel 2749:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2750:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2751:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2752:                 delete $accesshash{$entry};
                   2753:             }
1.185     www      2754:         }
1.191     harris41 2755:     }
1.352     www      2756: #
                   2757: # Roles
                   2758: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2759: #
1.800     albertel 2760:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2761:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2762: 	    split(/\:/,$entry);
                   2763:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2764:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2765:                 $rudom,$runame) eq 'ok') {
                   2766: 	    delete $userrolehash{$entry};
                   2767:         }
                   2768:     }
1.662     raeburn  2769: #
                   2770: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2771: #
                   2772:     my %domrolebuffer = ();
1.1000    raeburn  2773:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2774:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2775:         if ($domrolebuffer{$rudom}) {
                   2776:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2777:                       '='.&escape($domainrolehash{$entry});
                   2778:         } else {
                   2779:             $domrolebuffer{$rudom}.=&escape($entry).
                   2780:                       '='.&escape($domainrolehash{$entry});
                   2781:         }
                   2782:         delete $domainrolehash{$entry};
                   2783:     }
                   2784:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2785: 	my %servers = &get_servers($dom,'library');
                   2786: 	foreach my $tryserver (keys(%servers)) {
                   2787: 	    unless (&reply('domroleput:'.$dom.':'.
                   2788: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2789: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2790: 	    }
1.662     raeburn  2791:         }
                   2792:     }
1.186     www      2793:     $dumpcount++;
1.157     www      2794: }
                   2795: 
                   2796: sub courselog {
                   2797:     my $what=shift;
1.158     www      2798:     $what=time.':'.$what;
1.620     albertel 2799:     unless ($env{'request.course.id'}) { return ''; }
                   2800:     $coursedombuf{$env{'request.course.id'}}=
                   2801:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2802:     $coursenumbuf{$env{'request.course.id'}}=
                   2803:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2804:     $coursehombuf{$env{'request.course.id'}}=
                   2805:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2806:     $coursedescrbuf{$env{'request.course.id'}}=
                   2807:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2808:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2809:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2810:     $courseownerbuf{$env{'request.course.id'}}=
                   2811:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2812:     $coursetypebuf{$env{'request.course.id'}}=
                   2813:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2814:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2815: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2816:     } else {
1.620     albertel 2817: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2818:     }
1.620     albertel 2819:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2820: 	&flushcourselogs();
                   2821:     }
1.158     www      2822: }
                   2823: 
                   2824: sub courseacclog {
                   2825:     my $fnsymb=shift;
1.620     albertel 2826:     unless ($env{'request.course.id'}) { return ''; }
                   2827:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2828:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2829:         $what.=':POST';
1.583     matthew  2830:         # FIXME: Probably ought to escape things....
1.800     albertel 2831: 	foreach my $key (keys(%env)) {
                   2832:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2833:                 my $formitem = $1;
                   2834:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2835:                     $what.=':'.$formitem.'='.$env{$key};
                   2836:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2837:                     $what.=':'.$formitem.'='.$env{$key};
                   2838:                 }
1.158     www      2839:             }
1.191     harris41 2840:         }
1.583     matthew  2841:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2842:         # FIXME: We should not be depending on a form parameter that someone
                   2843:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2844:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2845:             $what.= ':POST';
                   2846:             # FIXME: Probably ought to escape things....
                   2847:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2848:                                  'crsdiscuss') {
1.620     albertel 2849:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2850:             }
                   2851:         }
1.158     www      2852:     }
                   2853:     &courselog($what);
1.149     www      2854: }
                   2855: 
1.185     www      2856: sub countacc {
                   2857:     my $url=&declutter(shift);
1.458     matthew  2858:     return if (! defined($url) || $url eq '');
1.620     albertel 2859:     unless ($env{'request.course.id'}) { return ''; }
                   2860:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2861:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2862:     $accesshash{$key}++;
1.185     www      2863: }
1.349     www      2864: 
1.361     www      2865: sub linklog {
                   2866:     my ($from,$to)=@_;
                   2867:     $from=&declutter($from);
                   2868:     $to=&declutter($to);
                   2869:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2870:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2871: }
                   2872:   
1.349     www      2873: sub userrolelog {
                   2874:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2875:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2876:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2877:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2878:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2879:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2880:        $userrolehash
                   2881:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2882:                     =$tend.':'.$tstart;
1.662     raeburn  2883:     }
1.898     albertel 2884:     if (($env{'request.role'} =~ /dc\./) &&
                   2885: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2886: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2887: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2888:          ($trole=~/^co/))) {
1.898     albertel 2889:        $userrolehash
                   2890:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2891:                     =$tend.':'.$tstart;
                   2892:     }
1.662     raeburn  2893:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2894:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2895:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2896:         ($trole=~/^sc/)) {
                   2897:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2898:        $domainrolehash
                   2899:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2900:                     = $tend.':'.$tstart;
                   2901:     }
1.351     www      2902: }
                   2903: 
1.957     raeburn  2904: sub courserolelog {
                   2905:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2906:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2907:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2908:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2909:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2910:         ($trole eq 'co')) {
1.957     raeburn  2911:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2912:             my $cdom = $1;
                   2913:             my $cnum = $2;
                   2914:             my $sec = $3;
                   2915:             my $namespace = 'rolelog';
                   2916:             my %storehash = (
                   2917:                                role    => $trole,
                   2918:                                start   => $tstart,
                   2919:                                end     => $tend,
                   2920:                                selfenroll => $selfenroll,
                   2921:                                context    => $context,
                   2922:                             );
                   2923:             if ($trole eq 'gr') {
                   2924:                 $namespace = 'groupslog';
                   2925:                 $storehash{'group'} = $sec;
                   2926:             } else {
                   2927:                 $storehash{'section'} = $sec;
                   2928:             }
                   2929:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2930:             if (($trole ne 'st') || ($sec ne '')) {
                   2931:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2932:             }
1.957     raeburn  2933:         }
                   2934:     }
                   2935:     return;
                   2936: }
                   2937: 
1.351     www      2938: sub get_course_adv_roles {
1.948     raeburn  2939:     my ($cid,$codes) = @_;
1.620     albertel 2940:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2941:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2942:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2943:     my %nothide=();
1.800     albertel 2944:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2945:         if ($user !~ /:/) {
                   2946: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2947:         } else {
                   2948:             $nothide{$user}=1;
                   2949:         }
1.470     www      2950:     }
1.351     www      2951:     my %returnhash=();
                   2952:     my %dumphash=
                   2953:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2954:     my $now=time;
1.997     raeburn  2955:     my %privileged;
1.1000    raeburn  2956:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2957: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2958:         if (($tstart) && ($tstart<0)) { next; }
                   2959:         if (($tend) && ($tend<$now)) { next; }
                   2960:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2961:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2962: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2963:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2964:             my %dompersonnel =
1.998     raeburn  2965:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2966:             $privileged{$domain} = {};
                   2967:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2968:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2969:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2970:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2971:                         $privileged{$udom}{$uname} = 1;
                   2972:                     }
                   2973:                 }
                   2974:             }
                   2975:         }
                   2976:         if ((exists($privileged{$domain}{$username})) && 
                   2977:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2978: 	if ($role eq 'cr') { next; }
1.948     raeburn  2979:         if ($codes) {
                   2980:             if ($section) { $role .= ':'.$section; }
                   2981:             if ($returnhash{$role}) {
                   2982:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2983:             } else {
                   2984:                 $returnhash{$role}=$username.':'.$domain;
                   2985:             }
1.351     www      2986:         } else {
1.988     raeburn  2987:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2988:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2989:             if ($returnhash{$key}) {
                   2990: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2991:             } else {
                   2992:                 $returnhash{$key}=$username.':'.$domain;
                   2993:             }
1.351     www      2994:         }
1.948     raeburn  2995:     }
1.400     www      2996:     return %returnhash;
                   2997: }
                   2998: 
                   2999: sub get_my_roles {
1.937     raeburn  3000:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3001:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3002:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3003:     my (%dumphash,%nothide);
1.858     raeburn  3004:     if ($context eq 'userroles') { 
                   3005:         %dumphash = &dump('roles',$udom,$uname);
                   3006:     } else {
                   3007:         %dumphash=
1.400     www      3008:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3009:         if ($hidepriv) {
                   3010:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3011:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3012:                 if ($user !~ /:/) {
                   3013:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3014:                 } else {
                   3015:                     $nothide{$user} = 1;
                   3016:                 }
                   3017:             }
                   3018:         }
1.858     raeburn  3019:     }
1.400     www      3020:     my %returnhash=();
                   3021:     my $now=time;
1.999     raeburn  3022:     my %privileged;
1.800     albertel 3023:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3024:         my ($role,$tend,$tstart);
                   3025:         if ($context eq 'userroles') {
                   3026: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3027:         } else {
                   3028:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3029:         }
1.400     www      3030:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3031:         my $status = 'active';
1.939     raeburn  3032:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3033:             $status = 'previous';
                   3034:         } 
                   3035:         if (($tstart) && ($now<$tstart)) {
                   3036:             $status = 'future';
                   3037:         }
                   3038:         if (ref($types) eq 'ARRAY') {
                   3039:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3040:                 next;
                   3041:             } 
                   3042:         } else {
                   3043:             if ($status ne 'active') {
                   3044:                 next;
                   3045:             }
                   3046:         }
1.867     raeburn  3047:         my ($rolecode,$username,$domain,$section,$area);
                   3048:         if ($context eq 'userroles') {
                   3049:             ($area,$rolecode) = split(/_/,$entry);
                   3050:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3051:         } else {
                   3052:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3053:         }
1.832     raeburn  3054:         if (ref($roledoms) eq 'ARRAY') {
                   3055:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3056:                 next;
                   3057:             }
                   3058:         }
                   3059:         if (ref($roles) eq 'ARRAY') {
                   3060:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3061:                 if ($role =~ /^cr\//) {
                   3062:                     if (!grep(/^cr$/,@{$roles})) {
                   3063:                         next;
                   3064:                     }
                   3065:                 } else {
                   3066:                     next;
                   3067:                 }
1.832     raeburn  3068:             }
1.867     raeburn  3069:         }
1.937     raeburn  3070:         if ($hidepriv) {
1.999     raeburn  3071:             if ($context eq 'userroles') {
                   3072:                 if ((&privileged($username,$domain)) &&
                   3073:                     (!$nothide{$username.':'.$domain})) {
                   3074:                     next;
                   3075:                 }
                   3076:             } else {
                   3077:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3078:                     my %dompersonnel =
                   3079:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3080:                     $privileged{$domain} = {};
                   3081:                     if (keys(%dompersonnel)) {
                   3082:                         foreach my $server (keys(%dompersonnel)) {
                   3083:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3084:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3085:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3086:                                     $privileged{$udom}{$uname} = $trole;
                   3087:                                 }
                   3088:                             }
                   3089:                         }
                   3090:                     }
                   3091:                 }
                   3092:                 if (exists($privileged{$domain}{$username})) {
                   3093:                     if (!$nothide{$username.':'.$domain}) {
                   3094:                         next;
                   3095:                     }
                   3096:                 }
1.937     raeburn  3097:             }
                   3098:         }
1.933     raeburn  3099:         if ($withsec) {
                   3100:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3101:                 $tstart.':'.$tend;
                   3102:         } else {
                   3103:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3104:         }
1.832     raeburn  3105:     }
1.373     www      3106:     return %returnhash;
1.399     www      3107: }
                   3108: 
                   3109: # ----------------------------------------------------- Frontpage Announcements
                   3110: #
                   3111: #
                   3112: 
                   3113: sub postannounce {
                   3114:     my ($server,$text)=@_;
1.844     albertel 3115:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3116:     unless ($text=~/\w/) { $text=''; }
                   3117:     return &reply('setannounce:'.&escape($text),$server);
                   3118: }
                   3119: 
                   3120: sub getannounce {
1.448     albertel 3121: 
                   3122:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3123: 	my $announcement='';
1.800     albertel 3124: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3125: 	close($fh);
1.399     www      3126: 	if ($announcement=~/\w/) { 
                   3127: 	    return 
                   3128:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3129:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3130: 	} else {
                   3131: 	    return '';
                   3132: 	}
                   3133:     } else {
                   3134: 	return '';
                   3135:     }
1.351     www      3136: }
1.353     www      3137: 
                   3138: # ---------------------------------------------------------- Course ID routines
                   3139: # Deal with domain's nohist_courseid.db files
                   3140: #
                   3141: 
                   3142: sub courseidput {
1.921     raeburn  3143:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3144:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3145:     my $outcome;
                   3146:     if ($caller eq 'timeonly') {
                   3147:         my $cids = '';
                   3148:         foreach my $item (keys(%$storehash)) {
                   3149:             $cids.=&escape($item).'&';
                   3150:         }
                   3151:         $cids=~s/\&$//;
                   3152:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3153:                           $coursehome);       
                   3154:     } else {
                   3155:         my $items = '';
                   3156:         foreach my $item (keys(%$storehash)) {
                   3157:             $items.= &escape($item).'='.
                   3158:                      &freeze_escape($$storehash{$item}).'&';
                   3159:         }
                   3160:         $items=~s/\&$//;
                   3161:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3162:                           $coursehome);
1.918     raeburn  3163:     }
                   3164:     if ($outcome eq 'unknown_cmd') {
                   3165:         my $what;
                   3166:         foreach my $cid (keys(%$storehash)) {
                   3167:             $what .= &escape($cid).'=';
1.921     raeburn  3168:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3169:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3170:             }
                   3171:             $what =~ s/\:$/&/;
                   3172:         }
                   3173:         $what =~ s/\&$//;  
                   3174:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3175:     } else {
                   3176:         return $outcome;
                   3177:     }
1.353     www      3178: }
                   3179: 
                   3180: sub courseiddump {
1.921     raeburn  3181:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3182:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3183:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3184:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3185:     my $as_hash = 1;
                   3186:     my %returnhash;
                   3187:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3188:     my %libserv = &all_library();
                   3189:     foreach my $tryserver (keys(%libserv)) {
                   3190:         if ( (  $hostidflag == 1 
                   3191: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3192: 	     || (!defined($hostidflag)) ) {
                   3193: 
1.918     raeburn  3194: 	    if (($domfilter eq '') ||
                   3195: 		(&host_domain($tryserver) eq $domfilter)) {
                   3196:                 my $rep = 
                   3197:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3198:                          $sincefilter.':'.&escape($descfilter).':'.
                   3199:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3200:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3201:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3202:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3203:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3204:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3205:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3206:                          &escape($creationcontext).':'.$domcloner,
                   3207:                          $tryserver);
1.918     raeburn  3208:                 my @pairs=split(/\&/,$rep);
                   3209:                 foreach my $item (@pairs) {
                   3210:                     my ($key,$value)=split(/\=/,$item,2);
                   3211:                     $key = &unescape($key);
                   3212:                     next if ($key =~ /^error: 2 /);
                   3213:                     my $result = &thaw_unescape($value);
                   3214:                     if (ref($result) eq 'HASH') {
                   3215:                         $returnhash{$key}=$result;
                   3216:                     } else {
1.921     raeburn  3217:                         my @responses = split(/:/,$value);
                   3218:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3219:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3220:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3221:                         }
1.1008    raeburn  3222:                     }
1.353     www      3223:                 }
                   3224:             }
                   3225:         }
                   3226:     }
                   3227:     return %returnhash;
                   3228: }
                   3229: 
1.1055    raeburn  3230: sub courselastaccess {
                   3231:     my ($cdom,$cnum,$hostidref) = @_;
                   3232:     my %returnhash;
                   3233:     if ($cdom && $cnum) {
                   3234:         my $chome = &homeserver($cnum,$cdom);
                   3235:         if ($chome ne 'no_host') {
                   3236:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3237:             &extract_lastaccess(\%returnhash,$rep);
                   3238:         }
                   3239:     } else {
                   3240:         if (!$cdom) { $cdom=''; }
                   3241:         my %libserv = &all_library();
                   3242:         foreach my $tryserver (keys(%libserv)) {
                   3243:             if (ref($hostidref) eq 'ARRAY') {
                   3244:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3245:             } 
                   3246:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3247:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3248:                 &extract_lastaccess(\%returnhash,$rep);
                   3249:             }
                   3250:         }
                   3251:     }
                   3252:     return %returnhash;
                   3253: }
                   3254: 
                   3255: sub extract_lastaccess {
                   3256:     my ($returnhash,$rep) = @_;
                   3257:     if (ref($returnhash) eq 'HASH') {
                   3258:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3259:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3260:                  $rep eq '') {
                   3261:             my @pairs=split(/\&/,$rep);
                   3262:             foreach my $item (@pairs) {
                   3263:                 my ($key,$value)=split(/\=/,$item,2);
                   3264:                 $key = &unescape($key);
                   3265:                 next if ($key =~ /^error: 2 /);
                   3266:                 $returnhash->{$key} = &thaw_unescape($value);
                   3267:             }
                   3268:         }
                   3269:     }
                   3270:     return;
                   3271: }
                   3272: 
1.658     raeburn  3273: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3274: 
                   3275: sub dcmailput {
1.685     raeburn  3276:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3277:     my $status = &Apache::lonnet::critical(
1.740     www      3278:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3279:        &escape($message),$server);
1.662     raeburn  3280:     return $status;
                   3281: }
                   3282: 
1.658     raeburn  3283: sub dcmaildump {
                   3284:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3285:     my %returnhash=();
1.846     albertel 3286: 
                   3287:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3288:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3289:                                                          &escape($enddate).':';
                   3290: 	my @esc_senders=map { &escape($_)} @$senders;
                   3291: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3292: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3293:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3294:             if (($key) && ($value)) {
                   3295:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3296:             }
                   3297:         }
                   3298:     }
                   3299:     return %returnhash;
                   3300: }
1.662     raeburn  3301: # ---------------------------------------------------------- Domain roles
                   3302: 
                   3303: sub get_domain_roles {
                   3304:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3305:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3306:         $startdate = '.';
                   3307:     }
1.1018    raeburn  3308:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3309:         $enddate = '.';
                   3310:     }
1.922     raeburn  3311:     my $rolelist;
                   3312:     if (ref($roles) eq 'ARRAY') {
                   3313:         $rolelist = join(':',@{$roles});
                   3314:     }
1.662     raeburn  3315:     my %personnel = ();
1.841     albertel 3316: 
                   3317:     my %servers = &get_servers($dom,'library');
                   3318:     foreach my $tryserver (keys(%servers)) {
                   3319: 	%{$personnel{$tryserver}}=();
                   3320: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3321: 					    &escape($startdate).':'.
                   3322: 					    &escape($enddate).':'.
                   3323: 					    &escape($rolelist), $tryserver))) {
                   3324: 	    my ($key,$value) = split(/\=/,$line,2);
                   3325: 	    if (($key) && ($value)) {
                   3326: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3327: 	    }
                   3328: 	}
1.662     raeburn  3329:     }
                   3330:     return %personnel;
                   3331: }
1.658     raeburn  3332: 
1.1057    www      3333: # ----------------------------------------------------------- Interval timing 
1.149     www      3334: 
1.504     albertel 3335: sub get_first_access {
                   3336:     my ($type,$argsymb)=@_;
1.790     albertel 3337:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3338:     if ($argsymb) { $symb=$argsymb; }
                   3339:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3340:     if ($type eq 'course') {
                   3341: 	$res='course';
                   3342:     } elsif ($type eq 'map') {
1.588     albertel 3343: 	$res=&symbread($map);
                   3344:     } else {
                   3345: 	$res=$symb;
                   3346:     }
                   3347:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3348:     return $times{"$courseid\0$res"};
1.504     albertel 3349: }
                   3350: 
                   3351: sub set_first_access {
                   3352:     my ($type)=@_;
1.790     albertel 3353:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3354:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3355:     if ($type eq 'course') {
                   3356: 	$res='course';
                   3357:     } elsif ($type eq 'map') {
1.588     albertel 3358: 	$res=&symbread($map);
                   3359:     } else {
                   3360: 	$res=$symb;
                   3361:     }
                   3362:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3363:     if (!$firstaccess) {
1.588     albertel 3364: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3365:     }
                   3366:     return 'already_set';
1.504     albertel 3367: }
                   3368: 
1.110     www      3369: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3370: 
                   3371: sub expirespread {
                   3372:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3373:     my $cid=$env{'request.course.id'}; 
1.110     www      3374:     if ($cid) {
                   3375:        my $now=time;
                   3376:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3377:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3378:                             $env{'course.'.$cid.'.num'}.
1.110     www      3379: 	        	    ':nohist_expirationdates:'.
                   3380:                             &escape($key).'='.$now,
1.620     albertel 3381:                             $env{'course.'.$cid.'.home'})
1.110     www      3382:     }
                   3383:     return 'ok';
1.14      www      3384: }
                   3385: 
1.109     www      3386: # ----------------------------------------------------- Devalidate Spreadsheets
                   3387: 
                   3388: sub devalidate {
1.325     www      3389:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3390:     my $cid=$env{'request.course.id'}; 
1.109     www      3391:     if ($cid) {
1.391     matthew  3392:         # delete the stored spreadsheets for
                   3393:         # - the student level sheet of this user in course's homespace
                   3394:         # - the assessment level sheet for this resource 
                   3395:         #   for this user in user's homespace
1.553     albertel 3396: 	# - current conditional state info
1.325     www      3397: 	my $key=$uname.':'.$udom.':';
1.109     www      3398:         my $status=
1.299     matthew  3399: 	    &del('nohist_calculatedsheets',
1.391     matthew  3400: 		 [$key.'studentcalc:'],
1.620     albertel 3401: 		 $env{'course.'.$cid.'.domain'},
                   3402: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3403: 		.' '.
                   3404: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3405: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3406:         unless ($status eq 'ok ok') {
                   3407:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3408:                     $uname.' at '.$udom.' for '.
1.109     www      3409: 		    $symb.': '.$status);
1.133     albertel 3410:         }
1.553     albertel 3411: 	&delenv('user.state.'.$cid);
1.109     www      3412:     }
                   3413: }
                   3414: 
1.265     albertel 3415: sub get_scalar {
                   3416:     my ($string,$end) = @_;
                   3417:     my $value;
                   3418:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3419: 	$value = $1;
                   3420:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3421: 	$value = $1;
                   3422:     }
                   3423:     return &unescape($value);
                   3424: }
                   3425: 
                   3426: sub array2str {
                   3427:   my (@array) = @_;
                   3428:   my $result=&arrayref2str(\@array);
                   3429:   $result=~s/^__ARRAY_REF__//;
                   3430:   $result=~s/__END_ARRAY_REF__$//;
                   3431:   return $result;
                   3432: }
                   3433: 
1.204     albertel 3434: sub arrayref2str {
                   3435:   my ($arrayref) = @_;
1.265     albertel 3436:   my $result='__ARRAY_REF__';
1.204     albertel 3437:   foreach my $elem (@$arrayref) {
1.265     albertel 3438:     if(ref($elem) eq 'ARRAY') {
                   3439:       $result.=&arrayref2str($elem).'&';
                   3440:     } elsif(ref($elem) eq 'HASH') {
                   3441:       $result.=&hashref2str($elem).'&';
                   3442:     } elsif(ref($elem)) {
                   3443:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3444:     } else {
                   3445:       $result.=&escape($elem).'&';
                   3446:     }
                   3447:   }
                   3448:   $result=~s/\&$//;
1.265     albertel 3449:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3450:   return $result;
                   3451: }
                   3452: 
1.168     albertel 3453: sub hash2str {
1.204     albertel 3454:   my (%hash) = @_;
                   3455:   my $result=&hashref2str(\%hash);
1.265     albertel 3456:   $result=~s/^__HASH_REF__//;
                   3457:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3458:   return $result;
                   3459: }
                   3460: 
                   3461: sub hashref2str {
                   3462:   my ($hashref)=@_;
1.265     albertel 3463:   my $result='__HASH_REF__';
1.800     albertel 3464:   foreach my $key (sort(keys(%$hashref))) {
                   3465:     if (ref($key) eq 'ARRAY') {
                   3466:       $result.=&arrayref2str($key).'=';
                   3467:     } elsif (ref($key) eq 'HASH') {
                   3468:       $result.=&hashref2str($key).'=';
                   3469:     } elsif (ref($key)) {
1.265     albertel 3470:       $result.='=';
1.800     albertel 3471:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3472:     } else {
1.800     albertel 3473: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3474:     }
                   3475: 
1.800     albertel 3476:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3477:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3478:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3479:       $result.=&hashref2str($hashref->{$key}).'&';
                   3480:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3481:        $result.='&';
1.800     albertel 3482:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3483:     } else {
1.800     albertel 3484:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3485:     }
                   3486:   }
1.168     albertel 3487:   $result=~s/\&$//;
1.265     albertel 3488:   $result .= '__END_HASH_REF__';
1.168     albertel 3489:   return $result;
                   3490: }
                   3491: 
                   3492: sub str2hash {
1.265     albertel 3493:     my ($string)=@_;
                   3494:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3495:     return %$hash;
                   3496: }
                   3497: 
                   3498: sub str2hashref {
1.168     albertel 3499:   my ($string) = @_;
1.265     albertel 3500: 
                   3501:   my %hash;
                   3502: 
                   3503:   if($string !~ /^__HASH_REF__/) {
                   3504:       if (! ($string eq '' || !defined($string))) {
                   3505: 	  $hash{'error'}='Not hash reference';
                   3506:       }
                   3507:       return (\%hash, $string);
                   3508:   }
                   3509: 
                   3510:   $string =~ s/^__HASH_REF__//;
                   3511: 
                   3512:   while($string !~ /^__END_HASH_REF__/) {
                   3513:       #key
                   3514:       my $key='';
                   3515:       if($string =~ /^__HASH_REF__/) {
                   3516:           ($key, $string)=&str2hashref($string);
                   3517:           if(defined($key->{'error'})) {
                   3518:               $hash{'error'}='Bad data';
                   3519:               return (\%hash, $string);
                   3520:           }
                   3521:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3522:           ($key, $string)=&str2arrayref($string);
                   3523:           if($key->[0] eq 'Array reference error') {
                   3524:               $hash{'error'}='Bad data';
                   3525:               return (\%hash, $string);
                   3526:           }
                   3527:       } else {
                   3528:           $string =~ s/^(.*?)=//;
1.267     albertel 3529: 	  $key=&unescape($1);
1.265     albertel 3530:       }
                   3531:       $string =~ s/^=//;
                   3532: 
                   3533:       #value
                   3534:       my $value='';
                   3535:       if($string =~ /^__HASH_REF__/) {
                   3536:           ($value, $string)=&str2hashref($string);
                   3537:           if(defined($value->{'error'})) {
                   3538:               $hash{'error'}='Bad data';
                   3539:               return (\%hash, $string);
                   3540:           }
                   3541:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3542:           ($value, $string)=&str2arrayref($string);
                   3543:           if($value->[0] eq 'Array reference error') {
                   3544:               $hash{'error'}='Bad data';
                   3545:               return (\%hash, $string);
                   3546:           }
                   3547:       } else {
                   3548: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3549:       }
                   3550:       $string =~ s/^&//;
                   3551: 
                   3552:       $hash{$key}=$value;
1.204     albertel 3553:   }
1.265     albertel 3554: 
                   3555:   $string =~ s/^__END_HASH_REF__//;
                   3556: 
                   3557:   return (\%hash, $string);
1.204     albertel 3558: }
                   3559: 
                   3560: sub str2array {
1.265     albertel 3561:     my ($string)=@_;
                   3562:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3563:     return @$array;
                   3564: }
                   3565: 
                   3566: sub str2arrayref {
1.204     albertel 3567:   my ($string) = @_;
1.265     albertel 3568:   my @array;
                   3569: 
                   3570:   if($string !~ /^__ARRAY_REF__/) {
                   3571:       if (! ($string eq '' || !defined($string))) {
                   3572: 	  $array[0]='Array reference error';
                   3573:       }
                   3574:       return (\@array, $string);
                   3575:   }
                   3576: 
                   3577:   $string =~ s/^__ARRAY_REF__//;
                   3578: 
                   3579:   while($string !~ /^__END_ARRAY_REF__/) {
                   3580:       my $value='';
                   3581:       if($string =~ /^__HASH_REF__/) {
                   3582:           ($value, $string)=&str2hashref($string);
                   3583:           if(defined($value->{'error'})) {
                   3584:               $array[0] ='Array reference error';
                   3585:               return (\@array, $string);
                   3586:           }
                   3587:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3588:           ($value, $string)=&str2arrayref($string);
                   3589:           if($value->[0] eq 'Array reference error') {
                   3590:               $array[0] ='Array reference error';
                   3591:               return (\@array, $string);
                   3592:           }
                   3593:       } else {
                   3594: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3595:       }
                   3596:       $string =~ s/^&//;
                   3597: 
                   3598:       push(@array, $value);
1.191     harris41 3599:   }
1.265     albertel 3600: 
                   3601:   $string =~ s/^__END_ARRAY_REF__//;
                   3602: 
                   3603:   return (\@array, $string);
1.168     albertel 3604: }
                   3605: 
1.167     albertel 3606: # -------------------------------------------------------------------Temp Store
                   3607: 
1.168     albertel 3608: sub tmpreset {
                   3609:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3610:   if (!$symb) {
                   3611:     $symb=&symbread();
1.620     albertel 3612:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3613:   }
                   3614:   $symb=escape($symb);
                   3615: 
1.620     albertel 3616:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3617:   $namespace=~s/\//\_/g;
                   3618:   $namespace=~s/\W//g;
                   3619: 
1.620     albertel 3620:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3621:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3622:   if ($domain eq 'public' && $stuname eq 'public') {
                   3623:       $stuname=$ENV{'REMOTE_ADDR'};
                   3624:   }
1.168     albertel 3625:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3626:   my %hash;
                   3627:   if (tie(%hash,'GDBM_File',
                   3628: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3629: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3630:     foreach my $key (keys(%hash)) {
1.180     albertel 3631:       if ($key=~ /:$symb/) {
1.168     albertel 3632: 	delete($hash{$key});
                   3633:       }
                   3634:     }
                   3635:   }
                   3636: }
                   3637: 
1.167     albertel 3638: sub tmpstore {
1.168     albertel 3639:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3640: 
                   3641:   if (!$symb) {
                   3642:     $symb=&symbread();
1.620     albertel 3643:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3644:   }
                   3645:   $symb=escape($symb);
                   3646: 
                   3647:   if (!$namespace) {
                   3648:     # I don't think we would ever want to store this for a course.
                   3649:     # it seems this will only be used if we don't have a course.
1.620     albertel 3650:     #$namespace=$env{'request.course.id'};
1.168     albertel 3651:     #if (!$namespace) {
1.620     albertel 3652:       $namespace=$env{'request.state'};
1.168     albertel 3653:     #}
                   3654:   }
                   3655:   $namespace=~s/\//\_/g;
                   3656:   $namespace=~s/\W//g;
1.620     albertel 3657:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3658:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3659:   if ($domain eq 'public' && $stuname eq 'public') {
                   3660:       $stuname=$ENV{'REMOTE_ADDR'};
                   3661:   }
1.168     albertel 3662:   my $now=time;
                   3663:   my %hash;
                   3664:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3665:   if (tie(%hash,'GDBM_File',
                   3666: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3667: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3668:     $hash{"version:$symb"}++;
                   3669:     my $version=$hash{"version:$symb"};
                   3670:     my $allkeys=''; 
                   3671:     foreach my $key (keys(%$storehash)) {
                   3672:       $allkeys.=$key.':';
1.591     albertel 3673:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3674:     }
                   3675:     $hash{"$version:$symb:timestamp"}=$now;
                   3676:     $allkeys.='timestamp';
                   3677:     $hash{"$version:keys:$symb"}=$allkeys;
                   3678:     if (untie(%hash)) {
                   3679:       return 'ok';
                   3680:     } else {
                   3681:       return "error:$!";
                   3682:     }
                   3683:   } else {
                   3684:     return "error:$!";
                   3685:   }
                   3686: }
1.167     albertel 3687: 
1.168     albertel 3688: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3689: 
1.168     albertel 3690: sub tmprestore {
                   3691:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3692: 
1.168     albertel 3693:   if (!$symb) {
                   3694:     $symb=&symbread();
1.620     albertel 3695:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3696:   }
                   3697:   $symb=escape($symb);
                   3698: 
1.620     albertel 3699:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3700: 
1.620     albertel 3701:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3702:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3703:   if ($domain eq 'public' && $stuname eq 'public') {
                   3704:       $stuname=$ENV{'REMOTE_ADDR'};
                   3705:   }
1.168     albertel 3706:   my %returnhash;
                   3707:   $namespace=~s/\//\_/g;
                   3708:   $namespace=~s/\W//g;
                   3709:   my %hash;
                   3710:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3711:   if (tie(%hash,'GDBM_File',
                   3712: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3713: 	  &GDBM_READER(),0640)) {
1.168     albertel 3714:     my $version=$hash{"version:$symb"};
                   3715:     $returnhash{'version'}=$version;
                   3716:     my $scope;
                   3717:     for ($scope=1;$scope<=$version;$scope++) {
                   3718:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3719:       my @keys=split(/:/,$vkeys);
                   3720:       my $key;
                   3721:       $returnhash{"$scope:keys"}=$vkeys;
                   3722:       foreach $key (@keys) {
1.591     albertel 3723: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3724: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3725:       }
                   3726:     }
1.168     albertel 3727:     if (!(untie(%hash))) {
                   3728:       return "error:$!";
                   3729:     }
                   3730:   } else {
                   3731:     return "error:$!";
                   3732:   }
                   3733:   return %returnhash;
1.167     albertel 3734: }
                   3735: 
1.9       www      3736: # ----------------------------------------------------------------------- Store
                   3737: 
                   3738: sub store {
1.124     www      3739:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3740:     my $home='';
                   3741: 
1.168     albertel 3742:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3743: 
1.213     www      3744:     $symb=&symbclean($symb);
1.122     albertel 3745:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3746: 
1.620     albertel 3747:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3748:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3749: 
                   3750:     &devalidate($symb,$stuname,$domain);
1.109     www      3751: 
                   3752:     $symb=escape($symb);
1.187     www      3753:     if (!$namespace) { 
1.620     albertel 3754:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3755:           return ''; 
                   3756:        } 
                   3757:     }
1.620     albertel 3758:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3759: 
                   3760:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3761:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3762: 
1.12      www      3763:     my $namevalue='';
1.800     albertel 3764:     foreach my $key (keys(%$storehash)) {
                   3765:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3766:     }
1.12      www      3767:     $namevalue=~s/\&$//;
1.187     www      3768:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3769:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3770: }
                   3771: 
1.47      www      3772: # -------------------------------------------------------------- Critical Store
                   3773: 
                   3774: sub cstore {
1.124     www      3775:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3776:     my $home='';
                   3777: 
1.168     albertel 3778:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3779: 
1.213     www      3780:     $symb=&symbclean($symb);
1.122     albertel 3781:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3782: 
1.620     albertel 3783:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3784:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3785: 
                   3786:     &devalidate($symb,$stuname,$domain);
1.109     www      3787: 
                   3788:     $symb=escape($symb);
1.187     www      3789:     if (!$namespace) { 
1.620     albertel 3790:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3791:           return ''; 
                   3792:        } 
                   3793:     }
1.620     albertel 3794:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3795: 
                   3796:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3797:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3798: 
1.47      www      3799:     my $namevalue='';
1.800     albertel 3800:     foreach my $key (keys(%$storehash)) {
                   3801:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3802:     }
1.47      www      3803:     $namevalue=~s/\&$//;
1.187     www      3804:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3805:     return critical
                   3806:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3807: }
                   3808: 
1.9       www      3809: # --------------------------------------------------------------------- Restore
                   3810: 
                   3811: sub restore {
1.124     www      3812:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3813:     my $home='';
                   3814: 
1.168     albertel 3815:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3816: 
1.122     albertel 3817:     if (!$symb) {
                   3818:       unless ($symb=escape(&symbread())) { return ''; }
                   3819:     } else {
1.213     www      3820:       $symb=&escape(&symbclean($symb));
1.122     albertel 3821:     }
1.188     www      3822:     if (!$namespace) { 
1.620     albertel 3823:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3824:           return ''; 
                   3825:        } 
                   3826:     }
1.620     albertel 3827:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3828:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3829:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3830:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3831: 
1.12      www      3832:     my %returnhash=();
1.800     albertel 3833:     foreach my $line (split(/\&/,$answer)) {
                   3834: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3835:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3836:     }
1.75      www      3837:     my $version;
                   3838:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3839:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3840:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3841:        }
1.75      www      3842:     }
1.13      www      3843:     return %returnhash;
1.34      www      3844: }
                   3845: 
                   3846: # ---------------------------------------------------------- Course Description
                   3847: 
                   3848: sub coursedescription {
1.731     albertel 3849:     my ($courseid,$args)=@_;
1.34      www      3850:     $courseid=~s/^\///;
1.49      www      3851:     $courseid=~s/\_/\//g;
1.34      www      3852:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3853:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3854:     my $normalid=$cdomain.'_'.$cnum;
                   3855:     # need to always cache even if we get errors otherwise we keep 
                   3856:     # trying and trying and trying to get the course description.
                   3857:     my %envhash=();
                   3858:     my %returnhash=();
1.731     albertel 3859:     
                   3860:     my $expiretime=600;
                   3861:     if ($env{'request.course.id'} eq $normalid) {
                   3862: 	$expiretime=120;
                   3863:     }
                   3864: 
                   3865:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3866:     if (!$args->{'freshen_cache'}
                   3867: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3868: 	foreach my $key (keys(%env)) {
                   3869: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3870: 	    my ($setting) = $1;
                   3871: 	    $returnhash{$setting} = $env{$key};
                   3872: 	}
                   3873: 	return %returnhash;
                   3874:     }
                   3875: 
                   3876:     # get the data agin
                   3877:     if (!$args->{'one_time'}) {
                   3878: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3879:     }
1.811     albertel 3880: 
1.34      www      3881:     if ($chome ne 'no_host') {
1.302     albertel 3882:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3883:        if (!exists($returnhash{'con_lost'})) {
                   3884:            $returnhash{'home'}= $chome;
                   3885: 	   $returnhash{'domain'} = $cdomain;
                   3886: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3887:            if (!defined($returnhash{'type'})) {
                   3888:                $returnhash{'type'} = 'Course';
                   3889:            }
1.130     albertel 3890:            while (my ($name,$value) = each %returnhash) {
1.53      www      3891:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3892:            }
1.270     www      3893:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3894:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3895: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3896:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3897:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3898:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3899:        }
                   3900:     }
1.731     albertel 3901:     if (!$args->{'one_time'}) {
1.949     raeburn  3902: 	&appenv(\%envhash);
1.731     albertel 3903:     }
1.302     albertel 3904:     return %returnhash;
1.461     www      3905: }
                   3906: 
                   3907: # -------------------------------------------------See if a user is privileged
                   3908: 
                   3909: sub privileged {
                   3910:     my ($username,$domain)=@_;
                   3911:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3912: 			&homeserver($username,$domain));
1.1033    raeburn  3913:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3914:         ($rolesdump =~ /^error:/)) {
                   3915:         return 0;
                   3916:     }
1.461     www      3917:     my $now=time;
                   3918:     if ($rolesdump ne '') {
1.800     albertel 3919:         foreach my $entry (split(/&/,$rolesdump)) {
                   3920: 	    if ($entry!~/^rolesdef_/) {
                   3921: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3922: 		$area=~s/\_\w\w$//;
                   3923: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3924: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3925: 		    my $active=1;
                   3926: 		    if ($tend) {
                   3927: 			if ($tend<$now) { $active=0; }
                   3928: 		    }
                   3929: 		    if ($tstart) {
                   3930: 			if ($tstart>$now) { $active=0; }
                   3931: 		    }
                   3932: 		    if ($active) { return 1; }
                   3933: 		}
                   3934: 	    }
                   3935: 	}
                   3936:     }
                   3937:     return 0;
1.9       www      3938: }
1.1       albertel 3939: 
1.103     harris41 3940: # -------------------------------------------------------- Get user privileges
1.11      www      3941: 
                   3942: sub rolesinit {
                   3943:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  3944:     my $now=time;
                   3945:     my %userroles = ('user.login.time' => $now);
1.1078  ! raeburn  3946:     my $extra = &freeze_escape({'clientcheckrole' => 1});
        !          3947:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  3948:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078  ! raeburn  3949:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  3950:         return \%userroles;
                   3951:     }
1.11      www      3952:     my %allroles=();
1.678     raeburn  3953:     my %allgroups=();   
                   3954:     my $group_privs;
1.11      www      3955: 
                   3956:     if ($rolesdump ne '') {
1.800     albertel 3957:         foreach my $entry (split(/&/,$rolesdump)) {
                   3958: 	  if ($entry!~/^rolesdef_/) {
                   3959:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3960: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3961:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3962: 	    if ($role=~/^cr/) { 
1.807     albertel 3963: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3964: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3965: 		    ($tend,$tstart)=split('_',$trest);
                   3966: 		} else {
                   3967: 		    $trole=$role;
                   3968: 		}
1.678     raeburn  3969:             } elsif ($role =~ m|^gr/|) {
                   3970:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3971:                 ($trole,$group_privs) = split(/\//,$trole);
                   3972:                 $group_privs = &unescape($group_privs);
1.587     albertel 3973: 	    } else {
                   3974: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3975: 	    }
1.743     albertel 3976: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3977: 					 $username);
                   3978: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3979:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3980:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3981:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3982: 		my $spec=$trole.'.'.$area;
                   3983: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3984: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3985:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3986:                 } elsif ($trole eq 'gr') {
                   3987:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3988: 		} else {
1.567     raeburn  3989:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3990: 		}
1.12      www      3991:             }
1.662     raeburn  3992:           }
1.191     harris41 3993:         }
1.743     albertel 3994:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3995:         $userroles{'user.adv'}    = $adv;
                   3996: 	$userroles{'user.author'} = $author;
1.620     albertel 3997:         $env{'user.adv'}=$adv;
1.11      www      3998:     }
1.743     albertel 3999:     return \%userroles;  
1.11      www      4000: }
                   4001: 
1.567     raeburn  4002: sub set_arearole {
                   4003:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4004: # log the associated role with the area
                   4005:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4006:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4007: }
                   4008: 
                   4009: sub custom_roleprivs {
                   4010:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4011:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4012:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4013:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4014:         my ($rdummy,$roledef)=
                   4015:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4016:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4017:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4018:             if (defined($syspriv)) {
1.1043    raeburn  4019:                 if ($trest =~ /^$match_community$/) {
                   4020:                     $syspriv =~ s/bre\&S//; 
                   4021:                 }
1.567     raeburn  4022:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4023:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4024:             }
                   4025:             if ($tdomain ne '') {
                   4026:                 if (defined($dompriv)) {
                   4027:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4028:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4029:                 }
                   4030:                 if (($trest ne '') && (defined($coursepriv))) {
                   4031:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4032:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4033:                 }
                   4034:             }
                   4035:         }
                   4036:     }
                   4037: }
                   4038: 
1.678     raeburn  4039: sub group_roleprivs {
                   4040:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4041:     my $access = 1;
                   4042:     my $now = time;
                   4043:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4044:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4045:     if ($access) {
1.811     albertel 4046:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4047:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4048:     }
                   4049: }
1.567     raeburn  4050: 
                   4051: sub standard_roleprivs {
                   4052:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4053:     if (defined($pr{$trole.':s'})) {
                   4054:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4055:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4056:     }
                   4057:     if ($tdomain ne '') {
                   4058:         if (defined($pr{$trole.':d'})) {
                   4059:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4060:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4061:         }
                   4062:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4063:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4064:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4065:         }
                   4066:     }
                   4067: }
                   4068: 
                   4069: sub set_userprivs {
1.1064    raeburn  4070:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4071:     my $author=0;
                   4072:     my $adv=0;
1.678     raeburn  4073:     my %grouproles = ();
                   4074:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4075:         my @groupkeys; 
1.1000    raeburn  4076:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4077:             push(@groupkeys,$role);
                   4078:         }
                   4079:         if (ref($groups_roles) eq 'HASH') {
                   4080:             foreach my $key (keys(%{$groups_roles})) {
                   4081:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4082:                     push(@groupkeys,$key);
                   4083:                 }
                   4084:             }
                   4085:         }
                   4086:         if (@groupkeys > 0) {
                   4087:             foreach my $role (@groupkeys) {
                   4088:                 my ($trole,$area,$sec,$extendedarea);
                   4089:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4090:                     $trole = $1;
                   4091:                     $area = $2;
                   4092:                     $sec = $3;
                   4093:                     $extendedarea = $area.$sec;
                   4094:                     if (exists($$allgroups{$area})) {
                   4095:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4096:                             my $spec = $trole.'.'.$extendedarea;
                   4097:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4098:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4099:                         }
1.678     raeburn  4100:                     }
                   4101:                 }
                   4102:             }
                   4103:         }
                   4104:     }
1.800     albertel 4105:     foreach my $group (keys(%grouproles)) {
                   4106:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4107:     }
1.800     albertel 4108:     foreach my $role (keys(%{$allroles})) {
                   4109:         my %thesepriv;
1.941     raeburn  4110:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4111:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4112:             if ($item ne '') {
                   4113:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4114:                 if ($restrictions eq '') {
                   4115:                     $thesepriv{$privilege}='F';
                   4116:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4117:                     $thesepriv{$privilege}.=$restrictions;
                   4118:                 }
                   4119:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4120:             }
                   4121:         }
                   4122:         my $thesestr='';
1.800     albertel 4123:         foreach my $priv (keys(%thesepriv)) {
                   4124: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4125: 	}
                   4126:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4127:     }
                   4128:     return ($author,$adv);
                   4129: }
                   4130: 
1.994     raeburn  4131: sub role_status {
1.1002    raeburn  4132:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4133:     my @pwhere = ();
                   4134:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4135:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4136:         unless (!defined($$role) || $$role eq '') {
                   4137:             $$where=join('.',@pwhere);
                   4138:             $$trolecode=$$role.'.'.$$where;
                   4139:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4140:             $$tstatus='is';
                   4141:             if ($$tstart && $$tstart>$then) {
                   4142:                 $$tstatus='future';
1.1034    raeburn  4143:                 if ($$tstart<$now) {
                   4144:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4145:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4146:                             my (%allroles,%allgroups,$group_privs,
                   4147:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4148:                             my %userroles = (
                   4149:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4150:                             );
1.1064    raeburn  4151:                             @rolecodes = ('cm'); 
1.1002    raeburn  4152:                             my $spec=$$role.'.'.$$where;
                   4153:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4154:                             if ($$role =~ /^cr\//) {
                   4155:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4156:                                 push(@rolecodes,'cr');
1.1002    raeburn  4157:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4158:                                 push(@rolecodes,$$role);
1.1002    raeburn  4159:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4160:                                                     $env{'user.name'});
1.1064    raeburn  4161:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4162:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4163:                                 $group_privs = &unescape($group_privs);
                   4164:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4165:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4166:                                 if (keys(%course_roles) > 0) {
                   4167:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4168:                                     if ($tdomain ne '' && $tnum ne '') { 
                   4169:                                         foreach my $key (keys(%course_roles)) {
                   4170:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4171:                                                 my $crsrole = $1;
                   4172:                                                 my $crssec = $2;
                   4173:                                                 if ($crsrole =~ /^cr/) {
                   4174:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4175:                                                         push(@rolecodes,'cr');
                   4176:                                                     }
                   4177:                                                 } else {
                   4178:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4179:                                                         push(@rolecodes,$crsrole);
                   4180:                                                     }
                   4181:                                                 }
                   4182:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4183:                                                 if ($crssec ne '') {
                   4184:                                                     $rolekey .= '/'.$crssec;
                   4185:                                                 }
                   4186:                                                 $rolekey .= './';
                   4187:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4188:                                             }
                   4189:                                         }
                   4190:                                     }
                   4191:                                 }
1.1002    raeburn  4192:                             } else {
1.1064    raeburn  4193:                                 push(@rolecodes,$$role);
1.1002    raeburn  4194:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4195:                             }
1.1064    raeburn  4196:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4197:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4198:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4199:                         }
                   4200:                     }
1.1034    raeburn  4201:                     $$tstatus = 'is';
1.1002    raeburn  4202:                 }
1.994     raeburn  4203:             }
                   4204:             if ($$tend) {
                   4205:                 if ($$tend<$then) {
                   4206:                     $$tstatus='expired';
                   4207:                 } elsif ($$tend<$now) {
                   4208:                     $$tstatus='will_not';
                   4209:                 }
                   4210:             }
                   4211:         }
                   4212:     }
                   4213: }
                   4214: 
                   4215: sub check_adhoc_privs {
1.1002    raeburn  4216:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4217:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4218:     if ($env{$cckey}) {
                   4219:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4220:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4221:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4222:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4223:         }
                   4224:     } else {
                   4225:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4226:     }
                   4227: }
                   4228: 
                   4229: sub set_adhoc_privileges {
                   4230: # role can be cc or ca
                   4231:     my ($dcdom,$pickedcourse,$role) = @_;
                   4232:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4233:     my $spec = $role.'.'.$area;
                   4234:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4235:                                   $env{'user.name'});
                   4236:     my %ccrole = ();
                   4237:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4238:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4239:     &appenv(\%userroles,[$role,'cm']);
                   4240:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4241:     &appenv( {'request.role'        => $spec,
                   4242:               'request.role.domain' => $dcdom,
                   4243:               'request.course.sec'  => ''
                   4244:              }
                   4245:            );
                   4246:     my $tadv=0;
                   4247:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4248:     &appenv({'request.role.adv'    => $tadv});
                   4249: }
                   4250: 
1.12      www      4251: # --------------------------------------------------------------- get interface
                   4252: 
                   4253: sub get {
1.131     albertel 4254:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4255:    my $items='';
1.800     albertel 4256:    foreach my $item (@$storearr) {
                   4257:        $items.=&escape($item).'&';
1.191     harris41 4258:    }
1.12      www      4259:    $items=~s/\&$//;
1.620     albertel 4260:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4261:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4262:    my $uhome=&homeserver($uname,$udomain);
                   4263: 
1.133     albertel 4264:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4265:    my @pairs=split(/\&/,$rep);
1.273     albertel 4266:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4267:      return @pairs;
                   4268:    }
1.15      www      4269:    my %returnhash=();
1.42      www      4270:    my $i=0;
1.800     albertel 4271:    foreach my $item (@$storearr) {
                   4272:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4273:       $i++;
1.191     harris41 4274:    }
1.15      www      4275:    return %returnhash;
1.27      www      4276: }
                   4277: 
                   4278: # --------------------------------------------------------------- del interface
                   4279: 
                   4280: sub del {
1.133     albertel 4281:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4282:    my $items='';
1.800     albertel 4283:    foreach my $item (@$storearr) {
                   4284:        $items.=&escape($item).'&';
1.191     harris41 4285:    }
1.984     neumanie 4286: 
1.27      www      4287:    $items=~s/\&$//;
1.620     albertel 4288:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4289:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4290:    my $uhome=&homeserver($uname,$udomain);
                   4291:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4292: }
                   4293: 
                   4294: # -------------------------------------------------------------- dump interface
                   4295: 
                   4296: sub dump {
1.755     albertel 4297:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4298:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4299:     if (!$uname) { $uname=$env{'user.name'}; }
                   4300:     my $uhome=&homeserver($uname,$udomain);
                   4301:     if ($regexp) {
                   4302: 	$regexp=&escape($regexp);
                   4303:     } else {
                   4304: 	$regexp='.';
                   4305:     }
                   4306:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4307:     my @pairs=split(/\&/,$rep);
                   4308:     my %returnhash=();
                   4309:     foreach my $item (@pairs) {
                   4310: 	my ($key,$value)=split(/=/,$item,2);
                   4311: 	$key = &unescape($key);
                   4312: 	next if ($key =~ /^error: 2 /);
                   4313: 	$returnhash{$key}=&thaw_unescape($value);
                   4314:     }
                   4315:     return %returnhash;
1.407     www      4316: }
                   4317: 
1.717     albertel 4318: # --------------------------------------------------------- dumpstore interface
                   4319: 
                   4320: sub dumpstore {
                   4321:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4322:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4323:    if (!$uname) { $uname=$env{'user.name'}; }
                   4324:    my $uhome=&homeserver($uname,$udomain);
                   4325:    if ($regexp) {
                   4326:        $regexp=&escape($regexp);
                   4327:    } else {
                   4328:        $regexp='.';
                   4329:    }
                   4330:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4331:    my @pairs=split(/\&/,$rep);
                   4332:    my %returnhash=();
                   4333:    foreach my $item (@pairs) {
                   4334:        my ($key,$value)=split(/=/,$item,2);
                   4335:        next if ($key =~ /^error: 2 /);
                   4336:        $returnhash{$key}=&thaw_unescape($value);
                   4337:    }
                   4338:    return %returnhash;
1.717     albertel 4339: }
                   4340: 
1.407     www      4341: # -------------------------------------------------------------- keys interface
                   4342: 
                   4343: sub getkeys {
                   4344:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4345:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4346:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4347:    my $uhome=&homeserver($uname,$udomain);
                   4348:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4349:    my @keyarray=();
1.800     albertel 4350:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4351:       next if ($key =~ /^error: 2 /);
1.800     albertel 4352:       push(@keyarray,&unescape($key));
1.407     www      4353:    }
                   4354:    return @keyarray;
1.318     matthew  4355: }
                   4356: 
1.319     matthew  4357: # --------------------------------------------------------------- currentdump
                   4358: sub currentdump {
1.328     matthew  4359:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4360:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4361:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4362:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4363:    my $uhome = &homeserver($sname,$sdom);
                   4364:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4365:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4366:    #
1.318     matthew  4367:    my %returnhash=();
1.319     matthew  4368:    #
                   4369:    if ($rep eq "unknown_cmd") { 
                   4370:        # an old lond will not know currentdump
                   4371:        # Do a dump and make it look like a currentdump
1.822     albertel 4372:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4373:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4374:        my %hash = @tmp;
                   4375:        @tmp=();
1.424     matthew  4376:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4377:    } else {
                   4378:        my @pairs=split(/\&/,$rep);
1.800     albertel 4379:        foreach my $pair (@pairs) {
                   4380:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4381:            my ($symb,$param) = split(/:/,$key);
                   4382:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4383:                                                         &thaw_unescape($value);
1.319     matthew  4384:        }
1.191     harris41 4385:    }
1.12      www      4386:    return %returnhash;
1.424     matthew  4387: }
                   4388: 
                   4389: sub convert_dump_to_currentdump{
                   4390:     my %hash = %{shift()};
                   4391:     my %returnhash;
                   4392:     # Code ripped from lond, essentially.  The only difference
                   4393:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4394:     # we might run in to problems with parameter names =~ /^v\./
                   4395:     while (my ($key,$value) = each(%hash)) {
                   4396:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4397: 	$symb  = &unescape($symb);
                   4398: 	$param = &unescape($param);
1.424     matthew  4399:         next if ($v eq 'version' || $symb eq 'keys');
                   4400:         next if (exists($returnhash{$symb}) &&
                   4401:                  exists($returnhash{$symb}->{$param}) &&
                   4402:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4403:         $returnhash{$symb}->{$param}=$value;
                   4404:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4405:     }
                   4406:     #
                   4407:     # Remove all of the keys in the hashes which keep track of
                   4408:     # the version of the parameter.
                   4409:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4410:         # use a foreach because we are going to delete from the hash.
                   4411:         foreach my $key (keys(%$param_hash)) {
                   4412:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4413:         }
                   4414:     }
                   4415:     return \%returnhash;
1.12      www      4416: }
                   4417: 
1.627     albertel 4418: # ------------------------------------------------------ critical inc interface
                   4419: 
                   4420: sub cinc {
                   4421:     return &inc(@_,'critical');
                   4422: }
                   4423: 
1.449     matthew  4424: # --------------------------------------------------------------- inc interface
                   4425: 
                   4426: sub inc {
1.627     albertel 4427:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4428:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4429:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4430:     my $uhome=&homeserver($uname,$udomain);
                   4431:     my $items='';
                   4432:     if (! ref($store)) {
                   4433:         # got a single value, so use that instead
                   4434:         $items = &escape($store).'=&';
                   4435:     } elsif (ref($store) eq 'SCALAR') {
                   4436:         $items = &escape($$store).'=&';        
                   4437:     } elsif (ref($store) eq 'ARRAY') {
                   4438:         $items = join('=&',map {&escape($_);} @{$store});
                   4439:     } elsif (ref($store) eq 'HASH') {
                   4440:         while (my($key,$value) = each(%{$store})) {
                   4441:             $items.= &escape($key).'='.&escape($value).'&';
                   4442:         }
                   4443:     }
                   4444:     $items=~s/\&$//;
1.627     albertel 4445:     if ($critical) {
                   4446: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4447:     } else {
                   4448: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4449:     }
1.449     matthew  4450: }
                   4451: 
1.12      www      4452: # --------------------------------------------------------------- put interface
                   4453: 
                   4454: sub put {
1.134     albertel 4455:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4456:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4457:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4458:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4459:    my $items='';
1.800     albertel 4460:    foreach my $item (keys(%$storehash)) {
                   4461:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4462:    }
1.12      www      4463:    $items=~s/\&$//;
1.134     albertel 4464:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4465: }
                   4466: 
1.631     albertel 4467: # ------------------------------------------------------------ newput interface
                   4468: 
                   4469: sub newput {
                   4470:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4471:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4472:    if (!$uname) { $uname=$env{'user.name'}; }
                   4473:    my $uhome=&homeserver($uname,$udomain);
                   4474:    my $items='';
                   4475:    foreach my $key (keys(%$storehash)) {
                   4476:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4477:    }
                   4478:    $items=~s/\&$//;
                   4479:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4480: }
                   4481: 
                   4482: # ---------------------------------------------------------  putstore interface
                   4483: 
1.524     raeburn  4484: sub putstore {
1.715     albertel 4485:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4486:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4487:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4488:    my $uhome=&homeserver($uname,$udomain);
                   4489:    my $items='';
1.715     albertel 4490:    foreach my $key (keys(%$storehash)) {
                   4491:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4492:    }
1.715     albertel 4493:    $items=~s/\&$//;
1.716     albertel 4494:    my $esc_symb=&escape($symb);
                   4495:    my $esc_v=&escape($version);
1.715     albertel 4496:    my $reply =
1.716     albertel 4497:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4498: 	      $uhome);
                   4499:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4500:        # gfall back to way things use to be done
1.715     albertel 4501:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4502: 			    $uname);
1.524     raeburn  4503:    }
1.715     albertel 4504:    return $reply;
                   4505: }
                   4506: 
                   4507: sub old_putstore {
1.716     albertel 4508:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4509:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4510:     if (!$uname) { $uname=$env{'user.name'}; }
                   4511:     my $uhome=&homeserver($uname,$udomain);
                   4512:     my %newstorehash;
1.800     albertel 4513:     foreach my $item (keys(%$storehash)) {
                   4514: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4515: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4516:     }
                   4517:     my $items='';
                   4518:     my %allitems = ();
1.800     albertel 4519:     foreach my $item (keys(%newstorehash)) {
                   4520: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4521: 	    my $key = $1.':keys:'.$2;
                   4522: 	    $allitems{$key} .= $3.':';
                   4523: 	}
1.800     albertel 4524: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4525:     }
1.800     albertel 4526:     foreach my $item (keys(%allitems)) {
                   4527: 	$allitems{$item} =~ s/\:$//;
                   4528: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4529:     }
                   4530:     $items=~s/\&$//;
                   4531:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4532: }
                   4533: 
1.47      www      4534: # ------------------------------------------------------ critical put interface
                   4535: 
                   4536: sub cput {
1.134     albertel 4537:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4538:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4539:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4540:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4541:    my $items='';
1.800     albertel 4542:    foreach my $item (keys(%$storehash)) {
                   4543:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4544:    }
1.47      www      4545:    $items=~s/\&$//;
1.134     albertel 4546:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4547: }
                   4548: 
                   4549: # -------------------------------------------------------------- eget interface
                   4550: 
                   4551: sub eget {
1.133     albertel 4552:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4553:    my $items='';
1.800     albertel 4554:    foreach my $item (@$storearr) {
                   4555:        $items.=&escape($item).'&';
1.191     harris41 4556:    }
1.12      www      4557:    $items=~s/\&$//;
1.620     albertel 4558:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4559:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4560:    my $uhome=&homeserver($uname,$udomain);
                   4561:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4562:    my @pairs=split(/\&/,$rep);
                   4563:    my %returnhash=();
1.42      www      4564:    my $i=0;
1.800     albertel 4565:    foreach my $item (@$storearr) {
                   4566:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4567:       $i++;
1.191     harris41 4568:    }
1.12      www      4569:    return %returnhash;
                   4570: }
                   4571: 
1.667     albertel 4572: # ------------------------------------------------------------ tmpput interface
                   4573: sub tmpput {
1.802     raeburn  4574:     my ($storehash,$server,$context)=@_;
1.667     albertel 4575:     my $items='';
1.800     albertel 4576:     foreach my $item (keys(%$storehash)) {
                   4577: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4578:     }
                   4579:     $items=~s/\&$//;
1.802     raeburn  4580:     if (defined($context)) {
                   4581:         $items .= ':'.&escape($context);
                   4582:     }
1.667     albertel 4583:     return &reply("tmpput:$items",$server);
                   4584: }
                   4585: 
                   4586: # ------------------------------------------------------------ tmpget interface
                   4587: sub tmpget {
1.688     albertel 4588:     my ($token,$server)=@_;
                   4589:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4590:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4591:     my %returnhash;
                   4592:     foreach my $item (split(/\&/,$rep)) {
                   4593: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4594:         next if ($key =~ /^error: 2 /);
1.667     albertel 4595: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4596:     }
                   4597:     return %returnhash;
                   4598: }
                   4599: 
1.688     albertel 4600: # ------------------------------------------------------------ tmpget interface
                   4601: sub tmpdel {
                   4602:     my ($token,$server)=@_;
                   4603:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4604:     return &reply("tmpdel:$token",$server);
                   4605: }
                   4606: 
1.765     albertel 4607: # -------------------------------------------------- portfolio access checking
                   4608: 
                   4609: sub portfolio_access {
1.766     albertel 4610:     my ($requrl) = @_;
1.765     albertel 4611:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4612:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4613:     if ($result) {
                   4614:         my %setters;
                   4615:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4616:             my ($startblock,$endblock) =
                   4617:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4618:             if ($startblock && $endblock) {
                   4619:                 return 'B';
                   4620:             }
                   4621:         } else {
                   4622:             my ($startblock,$endblock) =
                   4623:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4624:             if ($startblock && $endblock) {
                   4625:                 return 'B';
                   4626:             }
                   4627:         }
                   4628:     }
1.765     albertel 4629:     if ($result eq 'ok') {
1.766     albertel 4630:        return 'F';
1.765     albertel 4631:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4632:        return 'A';
1.765     albertel 4633:     }
1.766     albertel 4634:     return '';
1.765     albertel 4635: }
                   4636: 
                   4637: sub get_portfolio_access {
1.767     albertel 4638:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4639: 
                   4640:     if (!ref($access_hash)) {
                   4641: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4642: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4643: 						   $file_name);
                   4644: 	$access_hash = $access_controls{$file_name};
                   4645:     }
                   4646: 
1.765     albertel 4647:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4648:     my $now = time;
                   4649:     if (ref($access_hash) eq 'HASH') {
                   4650:         foreach my $key (keys(%{$access_hash})) {
                   4651:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4652:             if ($start > $now) {
                   4653:                 next;
                   4654:             }
                   4655:             if ($end && $end<$now) {
                   4656:                 next;
                   4657:             }
                   4658:             if ($scope eq 'public') {
                   4659:                 $public = $key;
                   4660:                 last;
                   4661:             } elsif ($scope eq 'guest') {
                   4662:                 $guest = $key;
                   4663:             } elsif ($scope eq 'domains') {
                   4664:                 push(@domains,$key);
                   4665:             } elsif ($scope eq 'users') {
                   4666:                 push(@users,$key);
                   4667:             } elsif ($scope eq 'course') {
                   4668:                 push(@courses,$key);
                   4669:             } elsif ($scope eq 'group') {
                   4670:                 push(@groups,$key);
                   4671:             }
                   4672:         }
                   4673:         if ($public) {
                   4674:             return 'ok';
                   4675:         }
                   4676:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4677:             if ($guest) {
                   4678:                 return $guest;
                   4679:             }
                   4680:         } else {
                   4681:             if (@domains > 0) {
                   4682:                 foreach my $domkey (@domains) {
                   4683:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4684:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4685:                             return 'ok';
                   4686:                         }
                   4687:                     }
                   4688:                 }
                   4689:             }
                   4690:             if (@users > 0) {
                   4691:                 foreach my $userkey (@users) {
1.865     raeburn  4692:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4693:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4694:                             if (ref($item) eq 'HASH') {
                   4695:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4696:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4697:                                     return 'ok';
                   4698:                                 }
                   4699:                             }
                   4700:                         }
                   4701:                     } 
1.765     albertel 4702:                 }
                   4703:             }
                   4704:             my %roleshash;
                   4705:             my @courses_and_groups = @courses;
                   4706:             push(@courses_and_groups,@groups); 
                   4707:             if (@courses_and_groups > 0) {
                   4708:                 my (%allgroups,%allroles); 
                   4709:                 my ($start,$end,$role,$sec,$group);
                   4710:                 foreach my $envkey (%env) {
1.1060    raeburn  4711:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4712:                         my $cid = $2.'_'.$3; 
                   4713:                         if ($1 eq 'gr') {
                   4714:                             $group = $4;
                   4715:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4716:                         } else {
                   4717:                             if ($4 eq '') {
                   4718:                                 $sec = 'none';
                   4719:                             } else {
                   4720:                                 $sec = $4;
                   4721:                             }
                   4722:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4723:                         }
1.811     albertel 4724:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4725:                         my $cid = $2.'_'.$3;
                   4726:                         if ($4 eq '') {
                   4727:                             $sec = 'none';
                   4728:                         } else {
                   4729:                             $sec = $4;
                   4730:                         }
                   4731:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4732:                     }
                   4733:                 }
                   4734:                 if (keys(%allroles) == 0) {
                   4735:                     return;
                   4736:                 }
                   4737:                 foreach my $key (@courses_and_groups) {
                   4738:                     my %content = %{$$access_hash{$key}};
                   4739:                     my $cnum = $content{'number'};
                   4740:                     my $cdom = $content{'domain'};
                   4741:                     my $cid = $cdom.'_'.$cnum;
                   4742:                     if (!exists($allroles{$cid})) {
                   4743:                         next;
                   4744:                     }    
                   4745:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4746:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4747:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4748:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4749:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4750:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4751:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4752:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4753:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4754:                                         if (grep/^all$/,@sections) {
                   4755:                                             return 'ok';
                   4756:                                         } else {
                   4757:                                             if (grep/^$sec$/,@sections) {
                   4758:                                                 return 'ok';
                   4759:                                             }
                   4760:                                         }
                   4761:                                     }
                   4762:                                 }
                   4763:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4764:                                     if (grep/^none$/,@groups) {
                   4765:                                         return 'ok';
                   4766:                                     }
                   4767:                                 } else {
                   4768:                                     if (grep/^all$/,@groups) {
                   4769:                                         return 'ok';
                   4770:                                     } 
                   4771:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4772:                                         if (grep/^$group$/,@groups) {
                   4773:                                             return 'ok';
                   4774:                                         }
                   4775:                                     }
                   4776:                                 } 
                   4777:                             }
                   4778:                         }
                   4779:                     }
                   4780:                 }
                   4781:             }
                   4782:             if ($guest) {
                   4783:                 return $guest;
                   4784:             }
                   4785:         }
                   4786:     }
                   4787:     return;
                   4788: }
                   4789: 
                   4790: sub course_group_datechecker {
                   4791:     my ($dates,$now,$status) = @_;
                   4792:     my ($start,$end) = split(/\./,$dates);
                   4793:     if (!$start && !$end) {
                   4794:         return 'ok';
                   4795:     }
                   4796:     if (grep/^active$/,@{$status}) {
                   4797:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4798:             return 'ok';
                   4799:         }
                   4800:     }
                   4801:     if (grep/^previous$/,@{$status}) {
                   4802:         if ($end > $now ) {
                   4803:             return 'ok';
                   4804:         }
                   4805:     }
                   4806:     if (grep/^future$/,@{$status}) {
                   4807:         if ($start > $now) {
                   4808:             return 'ok';
                   4809:         }
                   4810:     }
                   4811:     return; 
                   4812: }
                   4813: 
                   4814: sub parse_portfolio_url {
                   4815:     my ($url) = @_;
                   4816: 
                   4817:     my ($type,$udom,$unum,$group,$file_name);
                   4818:     
1.823     albertel 4819:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4820: 	$type = 1;
                   4821:         $udom = $1;
                   4822:         $unum = $2;
                   4823:         $file_name = $3;
1.823     albertel 4824:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4825: 	$type = 2;
                   4826:         $udom = $1;
                   4827:         $unum = $2;
                   4828:         $group = $3;
                   4829:         $file_name = $3.'/'.$4;
                   4830:     }
                   4831:     if (wantarray) {
                   4832: 	return ($type,$udom,$unum,$file_name,$group);
                   4833:     }
                   4834:     return $type;
                   4835: }
                   4836: 
                   4837: sub is_portfolio_url {
                   4838:     my ($url) = @_;
                   4839:     return scalar(&parse_portfolio_url($url));
                   4840: }
                   4841: 
1.798     raeburn  4842: sub is_portfolio_file {
                   4843:     my ($file) = @_;
1.820     raeburn  4844:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4845:         return 1;
                   4846:     }
                   4847:     return;
                   4848: }
                   4849: 
1.976     raeburn  4850: sub usertools_access {
1.985     raeburn  4851:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4852:     my ($access,%tools);
                   4853:     if ($context eq '') {
                   4854:         $context = 'tools';
                   4855:     }
                   4856:     if ($context eq 'requestcourses') {
                   4857:         %tools = (
                   4858:                       official   => 1,
                   4859:                       unofficial => 1,
1.1006    raeburn  4860:                       community  => 1,
1.985     raeburn  4861:                  );
                   4862:     } else {
                   4863:         %tools = (
                   4864:                       aboutme   => 1,
                   4865:                       blog      => 1,
                   4866:                       portfolio => 1,
                   4867:                  );
                   4868:     }
1.976     raeburn  4869:     return if (!defined($tools{$tool}));
                   4870: 
                   4871:     if ((!defined($udom)) || (!defined($uname))) {
                   4872:         $udom = $env{'user.domain'};
                   4873:         $uname = $env{'user.name'};
                   4874:     }
                   4875: 
1.978     raeburn  4876:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4877:         if ($action ne 'reload') {
1.985     raeburn  4878:             if ($context eq 'requestcourses') {
                   4879:                 return $env{'environment.canrequest.'.$tool};
                   4880:             } else {
                   4881:                 return $env{'environment.availabletools.'.$tool};
                   4882:             }
                   4883:         }
1.976     raeburn  4884:     }
                   4885: 
                   4886:     my ($toolstatus,$inststatus);
                   4887: 
1.985     raeburn  4888:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4889:          ($action ne 'reload')) {
                   4890:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4891:         $inststatus = $env{'environment.inststatus'};
                   4892:     } else {
1.1025    raeburn  4893:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985     raeburn  4894:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4895:         $inststatus = $userenv{'inststatus'};
                   4896:     }
                   4897: 
                   4898:     if ($toolstatus ne '') {
                   4899:         if ($toolstatus) {
                   4900:             $access = 1;
                   4901:         } else {
                   4902:             $access = 0;
                   4903:         }
                   4904:         return $access;
                   4905:     }
                   4906: 
                   4907:     my $is_adv = &is_advanced_user($udom,$uname);
                   4908:     my %domdef = &get_domain_defaults($udom);
                   4909:     if (ref($domdef{$tool}) eq 'HASH') {
                   4910:         if ($is_adv) {
                   4911:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4912:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4913:                     $access = 1;
                   4914:                 } else {
                   4915:                     $access = 0;
                   4916:                 }
                   4917:                 return $access;
                   4918:             }
                   4919:         }
                   4920:         if ($inststatus ne '') {
                   4921:             my ($hasaccess,$hasnoaccess);
                   4922:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4923:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4924:                     if ($domdef{$tool}{$affiliation}) {
                   4925:                         $hasaccess = 1;
                   4926:                     } else {
                   4927:                         $hasnoaccess = 1;
                   4928:                     }
                   4929:                 }
                   4930:             }
                   4931:             if ($hasaccess || $hasnoaccess) {
                   4932:                 if ($hasaccess) {
                   4933:                     $access = 1;
                   4934:                 } elsif ($hasnoaccess) {
                   4935:                     $access = 0; 
                   4936:                 }
                   4937:                 return $access;
                   4938:             }
                   4939:         } else {
                   4940:             if ($domdef{$tool}{'default'} ne '') {
                   4941:                 if ($domdef{$tool}{'default'}) {
                   4942:                     $access = 1;
                   4943:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4944:                     $access = 0;
                   4945:                 }
                   4946:                 return $access;
                   4947:             }
                   4948:         }
                   4949:     } else {
1.985     raeburn  4950:         if ($context eq 'tools') {
                   4951:             $access = 1;
                   4952:         } else {
                   4953:             $access = 0;
                   4954:         }
1.976     raeburn  4955:         return $access;
                   4956:     }
                   4957: }
                   4958: 
1.1050    raeburn  4959: sub is_course_owner {
                   4960:     my ($cdom,$cnum,$udom,$uname) = @_;
                   4961:     if (($udom eq '') || ($uname eq '')) {
                   4962:         $udom = $env{'user.domain'};
                   4963:         $uname = $env{'user.name'};
                   4964:     }
                   4965:     unless (($udom eq '') || ($uname eq '')) {
                   4966:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   4967:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   4968:                 return 1;
                   4969:             } else {
                   4970:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   4971:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   4972:                     return 1;
                   4973:                 }
                   4974:             }
                   4975:         }
                   4976:     }
                   4977:     return;
                   4978: }
                   4979: 
1.976     raeburn  4980: sub is_advanced_user {
                   4981:     my ($udom,$uname) = @_;
                   4982:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4983:     my %allroles;
                   4984:     my $is_adv;
                   4985:     foreach my $role (keys(%roleshash)) {
                   4986:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4987:         my $area = '/'.$tdomain.'/'.$trest;
                   4988:         if ($sec ne '') {
                   4989:             $area .= '/'.$sec;
                   4990:         }
                   4991:         if (($area ne '') && ($trole ne '')) {
                   4992:             my $spec=$trole.'.'.$area;
                   4993:             if ($trole =~ /^cr\//) {
                   4994:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4995:             } elsif ($trole ne 'gr') {
                   4996:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4997:             }
                   4998:         }
                   4999:     }
                   5000:     foreach my $role (keys(%allroles)) {
                   5001:         last if ($is_adv);
                   5002:         foreach my $item (split(/:/,$allroles{$role})) {
                   5003:             if ($item ne '') {
                   5004:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5005:                 if ($privilege eq 'adv') {
                   5006:                     $is_adv = 1;
                   5007:                     last;
                   5008:                 }
                   5009:             }
                   5010:         }
                   5011:     }
                   5012:     return $is_adv;
                   5013: }
1.798     raeburn  5014: 
1.1035    raeburn  5015: sub check_can_request {
1.1036    raeburn  5016:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5017:     my $canreq = 0;
                   5018:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5019:     my @options = ('approval','validate','autolimit');
                   5020:     my $optregex = join('|',@options);
                   5021:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5022:         foreach my $type (@{$types}) {
                   5023:             if (&usertools_access($env{'user.name'},
                   5024:                                   $env{'user.domain'},
                   5025:                                   $type,undef,'requestcourses')) {
                   5026:                 $canreq ++;
1.1036    raeburn  5027:                 if (ref($request_domains) eq 'HASH') {
                   5028:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5029:                 }
1.1035    raeburn  5030:                 if ($dom eq $env{'user.domain'}) {
                   5031:                     $can_request->{$type} = 1;
                   5032:                 }
                   5033:             }
                   5034:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5035:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5036:                 if (@curr > 0) {
1.1036    raeburn  5037:                     foreach my $item (@curr) {
                   5038:                         if (ref($request_domains) eq 'HASH') {
                   5039:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5040:                             if ($otherdom ne '') {
                   5041:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5042:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5043:                                         push(@{$request_domains->{$type}},$otherdom);
                   5044:                                     }
                   5045:                                 } else {
                   5046:                                     push(@{$request_domains->{$type}},$otherdom);
                   5047:                                 }
                   5048:                             }
                   5049:                         }
                   5050:                     }
                   5051:                     unless($dom eq $env{'user.domain'}) {
                   5052:                         $canreq ++;
1.1035    raeburn  5053:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5054:                             $can_request->{$type} = 1;
                   5055:                         }
                   5056:                     }
                   5057:                 }
                   5058:             }
                   5059:         }
                   5060:     }
                   5061:     return $canreq;
                   5062: }
                   5063: 
1.341     www      5064: # ---------------------------------------------- Custom access rule evaluation
                   5065: 
                   5066: sub customaccess {
                   5067:     my ($priv,$uri)=@_;
1.807     albertel 5068:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5069:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5070:     $udom = &LONCAPA::clean_domain($udom);
                   5071:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5072:     my $access=0;
1.800     albertel 5073:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5074: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5075: 	if ($type eq 'user') {
                   5076: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5077: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5078: 		if ($tdom) {
                   5079: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5080: 		}
1.896     albertel 5081: 		if ($tuname) {
                   5082: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5083: 		}
                   5084: 		$access=($effect eq 'allow');
                   5085: 		last;
                   5086: 	    }
                   5087: 	} else {
                   5088: 	    if ($role) {
                   5089: 		if ($role ne $urole) { next; }
                   5090: 	    }
                   5091: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5092: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5093: 		if ($tdom) {
                   5094: 		    if ($tdom ne $udom) { next; }
                   5095: 		}
                   5096: 		if ($tcrs) {
                   5097: 		    if ($tcrs ne $ucrs) { next; }
                   5098: 		}
                   5099: 		if ($tsec) {
                   5100: 		    if ($tsec ne $usec) { next; }
                   5101: 		}
                   5102: 		$access=($effect eq 'allow');
                   5103: 		last;
                   5104: 	    }
                   5105: 	    if ($realm eq '' && $role eq '') {
                   5106: 		$access=($effect eq 'allow');
                   5107: 	    }
1.402     bowersj2 5108: 	}
1.341     www      5109:     }
                   5110:     return $access;
                   5111: }
                   5112: 
1.103     harris41 5113: # ------------------------------------------------- Check for a user privilege
1.12      www      5114: 
                   5115: sub allowed {
1.810     raeburn  5116:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5117:     my $ver_orguri=$uri;
1.439     www      5118:     $uri=&deversion($uri);
1.152     www      5119:     my $orguri=$uri;
1.52      www      5120:     $uri=&declutter($uri);
1.809     raeburn  5121: 
1.810     raeburn  5122:     if ($priv eq 'evb') {
                   5123: # Evade communication block restrictions for specified role in a course
                   5124:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5125:             return $1;
                   5126:         } else {
                   5127:             return;
                   5128:         }
                   5129:     }
                   5130: 
1.620     albertel 5131:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5132: # Free bre access to adm and meta resources
1.775     albertel 5133:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5134: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5135: 	&& ($priv eq 'bre')) {
1.14      www      5136: 	return 'F';
1.159     www      5137:     }
                   5138: 
1.545     banghart 5139: # Free bre access to user's own portfolio contents
1.714     raeburn  5140:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5141:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5142: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5143:         my %setters;
                   5144:         my ($startblock,$endblock) = 
                   5145:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5146:         if ($startblock && $endblock) {
                   5147:             return 'B';
                   5148:         } else {
                   5149:             return 'F';
                   5150:         }
1.545     banghart 5151:     }
                   5152: 
1.762     raeburn  5153: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5154:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5155:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5156:         if (exists($env{'request.course.id'})) {
                   5157:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5158:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5159:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5160:                 my $courseprivid=$env{'request.course.id'};
                   5161:                 $courseprivid=~s/\_/\//;
                   5162:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5163:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5164:                     return $1; 
1.762     raeburn  5165:                 } else {
                   5166:                     if ($env{'request.course.sec'}) {
                   5167:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5168:                     }
                   5169:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5170:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5171:                         return $2;
                   5172:                     }
1.714     raeburn  5173:                 }
                   5174:             }
                   5175:         }
                   5176:     }
                   5177: 
1.159     www      5178: # Free bre to public access
                   5179: 
                   5180:     if ($priv eq 'bre') {
1.238     www      5181:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5182: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5183:            return 'F'; 
                   5184:         }
1.238     www      5185:         if ($copyright eq 'priv') {
                   5186:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5187: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5188: 		return '';
                   5189:             }
                   5190:         }
                   5191:         if ($copyright eq 'domain') {
                   5192:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5193: 	    unless (($env{'user.domain'} eq $1) ||
                   5194:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5195: 		return '';
                   5196:             }
1.262     matthew  5197:         }
1.620     albertel 5198:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5199:             # Library role, so allow browsing of resources in this domain.
                   5200:             return 'F';
1.238     www      5201:         }
1.341     www      5202:         if ($copyright eq 'custom') {
                   5203: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5204:         }
1.14      www      5205:     }
1.264     matthew  5206:     # Domain coordinator is trying to create a course
1.620     albertel 5207:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5208:         # uri is the requested domain in this case.
                   5209:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5210:         # a role of dc for the domain in question.
1.620     albertel 5211:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5212:     }
1.29      www      5213: 
1.52      www      5214:     my $thisallowed='';
                   5215:     my $statecond=0;
                   5216:     my $courseprivid='';
                   5217: 
1.1039    raeburn  5218:     my $ownaccess;
1.1043    raeburn  5219:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5220:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5221:         if ($uri eq '') {
                   5222:             $ownaccess = 1;
                   5223:         } else {
                   5224:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5225:                 my $udom = $env{'user.domain'};
                   5226:                 my $uname = $env{'user.name'};
                   5227:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5228:                     $ownaccess = 1;
1.1040    raeburn  5229:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5230:                     unless ($uri =~ m{\.\./}) {
                   5231:                         $ownaccess = 1;
                   5232:                     }
                   5233:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5234:                     my $now = time;
                   5235:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5236:                         my $adom = $1;
                   5237:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5238:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5239:                                 my ($start,$end) = split('.',$env{$key});
                   5240:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5241:                                     $ownaccess = 1;
                   5242:                                     last;
                   5243:                                 }
                   5244:                             }
                   5245:                         }
                   5246:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5247:                         my $adom = $1;
                   5248:                         my $aname = $2;
1.1042    raeburn  5249:                         foreach my $role ('ca','aa') { 
                   5250:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5251:                                 my ($start,$end) =
                   5252:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5253:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5254:                                     $ownaccess = 1;
                   5255:                                     last;
                   5256:                                 }
1.1039    raeburn  5257:                             }
                   5258:                         }
                   5259:                     }
                   5260:                 }
                   5261:             }
                   5262:         }
                   5263:     }
                   5264: 
1.52      www      5265: # Course
                   5266: 
1.620     albertel 5267:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5268:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5269:             $thisallowed.=$1;
                   5270:         }
1.52      www      5271:     }
1.29      www      5272: 
1.52      www      5273: # Domain
                   5274: 
1.620     albertel 5275:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5276:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5277:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5278:             $thisallowed.=$1;
                   5279:         }
1.12      www      5280:     }
1.52      www      5281: 
                   5282: # Course: uri itself is a course
1.66      www      5283:     my $courseuri=$uri;
                   5284:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5285:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5286: 
1.620     albertel 5287:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5288:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5289:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5290:             $thisallowed.=$1;
                   5291:         }
1.12      www      5292:     }
1.29      www      5293: 
1.665     albertel 5294: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5295: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5296:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5297: 	$thisallowed='';
1.671     raeburn  5298:         my ($match)=&is_on_map($uri);
                   5299:         if ($match) {
                   5300:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5301:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5302:                 $thisallowed.=$1;
                   5303:             }
                   5304:         } else {
1.705     albertel 5305:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5306:             if ($refuri) {
                   5307:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5308:                     $thisallowed='F';
1.671     raeburn  5309:                 } else {
                   5310:                     $refuri=&declutter($refuri);
                   5311:                     my ($match) = &is_on_map($refuri);
                   5312:                     if ($match) {
                   5313:                         $thisallowed='F';
                   5314:                     }
1.669     raeburn  5315:                 }
1.671     raeburn  5316:             }
                   5317:         }
1.314     www      5318:     }
1.492     albertel 5319: 
1.766     albertel 5320:     if ($priv eq 'bre'
                   5321: 	&& $thisallowed ne 'F' 
                   5322: 	&& $thisallowed ne '2'
                   5323: 	&& &is_portfolio_url($uri)) {
                   5324: 	$thisallowed = &portfolio_access($uri);
                   5325:     }
                   5326:     
1.52      www      5327: # Full access at system, domain or course-wide level? Exit.
1.29      www      5328:     if ($thisallowed=~/F/) {
                   5329: 	return 'F';
                   5330:     }
                   5331: 
1.52      www      5332: # If this is generating or modifying users, exit with special codes
1.29      www      5333: 
1.643     www      5334:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5335: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5336: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5337: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5338: 	    unless ($auname) { return $thisallowed; }
                   5339: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5340: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5341: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5342: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5343: 	}
1.52      www      5344: 	return $thisallowed;
                   5345:     }
                   5346: #
1.103     harris41 5347: # Gathered so far: system, domain and course wide privileges
1.52      www      5348: #
                   5349: # Course: See if uri or referer is an individual resource that is part of 
                   5350: # the course
                   5351: 
1.620     albertel 5352:     if ($env{'request.course.id'}) {
1.232     www      5353: 
1.620     albertel 5354:        $courseprivid=$env{'request.course.id'};
                   5355:        if ($env{'request.course.sec'}) {
                   5356:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5357:        }
                   5358:        $courseprivid=~s/\_/\//;
                   5359:        my $checkreferer=1;
1.232     www      5360:        my ($match,$cond)=&is_on_map($uri);
                   5361:        if ($match) {
                   5362:            $statecond=$cond;
1.620     albertel 5363:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5364:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5365:                $thisallowed.=$1;
                   5366:                $checkreferer=0;
                   5367:            }
1.29      www      5368:        }
1.83      www      5369:        
1.148     www      5370:        if ($checkreferer) {
1.620     albertel 5371: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5372:             unless ($refuri) {
1.800     albertel 5373:                 foreach my $key (keys(%env)) {
                   5374: 		    if ($key=~/^httpref\..*\*/) {
                   5375: 			my $pattern=$key;
1.156     www      5376:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5377:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5378:                         $pattern=~s/\//\\\//g;
1.152     www      5379:                         if ($orguri=~/$pattern/) {
1.800     albertel 5380: 			    $refuri=$env{$key};
1.148     www      5381:                         }
                   5382:                     }
1.191     harris41 5383:                 }
1.148     www      5384:             }
1.232     www      5385: 
1.148     www      5386:          if ($refuri) { 
1.152     www      5387: 	  $refuri=&declutter($refuri);
1.232     www      5388:           my ($match,$cond)=&is_on_map($refuri);
                   5389:             if ($match) {
                   5390:               my $refstatecond=$cond;
1.620     albertel 5391:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5392:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5393:                   $thisallowed.=$1;
1.53      www      5394:                   $uri=$refuri;
                   5395:                   $statecond=$refstatecond;
1.52      www      5396:               }
                   5397:           }
1.148     www      5398:         }
1.29      www      5399:        }
1.52      www      5400:    }
1.29      www      5401: 
1.52      www      5402: #
1.103     harris41 5403: # Gathered now: all privileges that could apply, and condition number
1.52      www      5404: # 
                   5405: #
                   5406: # Full or no access?
                   5407: #
1.29      www      5408: 
1.52      www      5409:     if ($thisallowed=~/F/) {
                   5410: 	return 'F';
                   5411:     }
1.29      www      5412: 
1.52      www      5413:     unless ($thisallowed) {
                   5414:         return '';
                   5415:     }
1.29      www      5416: 
1.52      www      5417: # Restrictions exist, deal with them
                   5418: #
                   5419: #   C:according to course preferences
                   5420: #   R:according to resource settings
                   5421: #   L:unless locked
                   5422: #   X:according to user session state
                   5423: #
                   5424: 
                   5425: # Possibly locked functionality, check all courses
1.54      www      5426: # Locks might take effect only after 10 minutes cache expiration for other
                   5427: # courses, and 2 minutes for current course
1.52      www      5428: 
                   5429:     my $envkey;
                   5430:     if ($thisallowed=~/L/) {
1.1000    raeburn  5431:         foreach $envkey (keys(%env)) {
1.54      www      5432:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5433:                my $courseid=$2;
                   5434:                my $roleid=$1.'.'.$2;
1.92      www      5435:                $courseid=~s/^\///;
1.54      www      5436:                my $expiretime=600;
1.620     albertel 5437:                if ($env{'request.role'} eq $roleid) {
1.54      www      5438: 		  $expiretime=120;
                   5439:                }
                   5440: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5441:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5442:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5443: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5444:                }
1.620     albertel 5445:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5446:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5447: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5448:                        &log($env{'user.domain'},$env{'user.name'},
                   5449:                             $env{'user.home'},
1.57      www      5450:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5451:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5452:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5453: 		       return '';
                   5454:                    }
                   5455:                }
1.620     albertel 5456:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5457:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5458: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5459:                        &log($env{'user.domain'},$env{'user.name'},
                   5460:                             $env{'user.home'},
1.57      www      5461:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5462:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5463:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5464: 		       return '';
                   5465:                    }
                   5466:                }
                   5467: 	   }
1.29      www      5468:        }
1.52      www      5469:     }
                   5470:    
                   5471: #
                   5472: # Rest of the restrictions depend on selected course
                   5473: #
                   5474: 
1.620     albertel 5475:     unless ($env{'request.course.id'}) {
1.766     albertel 5476: 	if ($thisallowed eq 'A') {
                   5477: 	    return 'A';
1.814     raeburn  5478:         } elsif ($thisallowed eq 'B') {
                   5479:             return 'B';
1.766     albertel 5480: 	} else {
                   5481: 	    return '1';
                   5482: 	}
1.52      www      5483:     }
1.29      www      5484: 
1.52      www      5485: #
                   5486: # Now user is definitely in a course
                   5487: #
1.53      www      5488: 
                   5489: 
                   5490: # Course preferences
                   5491: 
                   5492:    if ($thisallowed=~/C/) {
1.620     albertel 5493:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5494:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5495:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5496: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5497: 	   if ($priv ne 'pch') { 
                   5498: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5499: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5500: 			$env{'request.course.id'});
                   5501: 	   }
1.237     www      5502:            return '';
                   5503:        }
                   5504: 
1.620     albertel 5505:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5506: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5507: 	   if ($priv ne 'pch') { 
                   5508: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5509: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5510: 			$env{'request.course.id'});
                   5511: 	   }
1.54      www      5512:            return '';
                   5513:        }
1.53      www      5514:    }
                   5515: 
                   5516: # Resource preferences
                   5517: 
                   5518:    if ($thisallowed=~/R/) {
1.620     albertel 5519:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5520:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5521: 	   if ($priv ne 'pch') { 
                   5522: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5523: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5524: 	   }
                   5525: 	   return '';
1.54      www      5526:        }
1.53      www      5527:    }
1.30      www      5528: 
1.246     www      5529: # Restricted by state or randomout?
1.30      www      5530: 
1.52      www      5531:    if ($thisallowed=~/X/) {
1.620     albertel 5532:       if ($env{'acc.randomout'}) {
1.579     albertel 5533: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5534:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5535:             return ''; 
                   5536:          }
1.247     www      5537:       }
                   5538:       if (&condval($statecond)) {
1.52      www      5539: 	 return '2';
                   5540:       } else {
                   5541:          return '';
                   5542:       }
                   5543:    }
1.30      www      5544: 
1.766     albertel 5545:     if ($thisallowed eq 'A') {
                   5546: 	return 'A';
1.814     raeburn  5547:     } elsif ($thisallowed eq 'B') {
                   5548:         return 'B';
1.766     albertel 5549:     }
1.52      www      5550:    return 'F';
1.232     www      5551: }
                   5552: 
1.710     albertel 5553: sub split_uri_for_cond {
                   5554:     my $uri=&deversion(&declutter(shift));
                   5555:     my @uriparts=split(/\//,$uri);
                   5556:     my $filename=pop(@uriparts);
                   5557:     my $pathname=join('/',@uriparts);
                   5558:     return ($pathname,$filename);
                   5559: }
1.232     www      5560: # --------------------------------------------------- Is a resource on the map?
                   5561: 
                   5562: sub is_on_map {
1.710     albertel 5563:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5564:     #Trying to find the conditional for the file
1.620     albertel 5565:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5566: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5567:     if ($match) {
1.289     bowersj2 5568: 	return (1,$1);
                   5569:     } else {
1.434     www      5570: 	return (0,0);
1.289     bowersj2 5571:     }
1.12      www      5572: }
                   5573: 
1.427     www      5574: # --------------------------------------------------------- Get symb from alias
                   5575: 
                   5576: sub get_symb_from_alias {
                   5577:     my $symb=shift;
                   5578:     my ($map,$resid,$url)=&decode_symb($symb);
                   5579: # Already is a symb
                   5580:     if ($url) { return $symb; }
                   5581: # Must be an alias
                   5582:     my $aliassymb='';
                   5583:     my %bighash;
1.620     albertel 5584:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5585:                             &GDBM_READER(),0640)) {
                   5586:         my $rid=$bighash{'mapalias_'.$symb};
                   5587: 	if ($rid) {
                   5588: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5589: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5590: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5591: 	}
                   5592:         untie %bighash;
                   5593:     }
                   5594:     return $aliassymb;
                   5595: }
                   5596: 
1.12      www      5597: # ----------------------------------------------------------------- Define Role
                   5598: 
                   5599: sub definerole {
                   5600:   if (allowed('mcr','/')) {
                   5601:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5602:     foreach my $role (split(':',$sysrole)) {
                   5603: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5604:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5605:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5606: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5607:                return "refused:s:$crole&$cqual"; 
                   5608:             }
                   5609:         }
1.191     harris41 5610:     }
1.800     albertel 5611:     foreach my $role (split(':',$domrole)) {
                   5612: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5613:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5614:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5615: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5616:                return "refused:d:$crole&$cqual"; 
                   5617:             }
                   5618:         }
1.191     harris41 5619:     }
1.800     albertel 5620:     foreach my $role (split(':',$courole)) {
                   5621: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5622:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5623:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5624: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5625:                return "refused:c:$crole&$cqual"; 
                   5626:             }
                   5627:         }
1.191     harris41 5628:     }
1.620     albertel 5629:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5630:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5631: 	        "rolesdef_$rolename=".
                   5632:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5633:     return reply($command,$env{'user.home'});
1.12      www      5634:   } else {
                   5635:     return 'refused';
                   5636:   }
1.105     harris41 5637: }
                   5638: 
                   5639: # ---------------- Make a metadata query against the network of library servers
                   5640: 
                   5641: sub metadata_query {
1.244     matthew  5642:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5643:     my %rhash;
1.845     albertel 5644:     my %libserv = &all_library();
1.244     matthew  5645:     my @server_list = (defined($server_array) ? @$server_array
                   5646:                                               : keys(%libserv) );
                   5647:     for my $server (@server_list) {
1.118     harris41 5648: 	unless ($custom or $customshow) {
                   5649: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5650: 	    $rhash{$server}=$reply;
                   5651: 	}
                   5652: 	else {
                   5653: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5654: 			     &escape($custom).':'.&escape($customshow),
                   5655: 			     $server);
                   5656: 	    $rhash{$server}=$reply;
                   5657: 	}
1.112     harris41 5658:     }
1.118     harris41 5659:     return \%rhash;
1.240     www      5660: }
                   5661: 
                   5662: # ----------------------------------------- Send log queries and wait for reply
                   5663: 
                   5664: sub log_query {
                   5665:     my ($uname,$udom,$query,%filters)=@_;
                   5666:     my $uhome=&homeserver($uname,$udom);
                   5667:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5668:     my $uhost=&hostname($uhome);
1.800     albertel 5669:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5670:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5671:                        $uhome);
1.479     albertel 5672:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5673:     return get_query_reply($queryid);
                   5674: }
                   5675: 
1.818     raeburn  5676: # -------------------------- Update MySQL table for portfolio file
                   5677: 
                   5678: sub update_portfolio_table {
1.821     raeburn  5679:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5680:     if ($group ne '') {
                   5681:         $file_name =~s /^\Q$group\E//;
                   5682:     }
1.818     raeburn  5683:     my $homeserver = &homeserver($uname,$udom);
                   5684:     my $queryid=
1.821     raeburn  5685:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5686:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5687:     my $reply = &get_query_reply($queryid);
                   5688:     return $reply;
                   5689: }
                   5690: 
1.899     raeburn  5691: # -------------------------- Update MySQL allusers table
                   5692: 
                   5693: sub update_allusers_table {
                   5694:     my ($uname,$udom,$names) = @_;
                   5695:     my $homeserver = &homeserver($uname,$udom);
                   5696:     my $queryid=
                   5697:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5698:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5699:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5700:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5701:                'generation='.&escape($names->{'generation'}).'%%'.
                   5702:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5703:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  5704:     return;
1.899     raeburn  5705: }
                   5706: 
1.508     raeburn  5707: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5708: 
                   5709: sub fetch_enrollment_query {
1.511     raeburn  5710:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5711:     my $homeserver;
1.547     raeburn  5712:     my $maxtries = 1;
1.508     raeburn  5713:     if ($context eq 'automated') {
                   5714:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5715:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5716:     } else {
                   5717:         $homeserver = &homeserver($cnum,$dom);
                   5718:     }
1.838     albertel 5719:     my $host=&hostname($homeserver);
1.506     raeburn  5720:     my $cmd = '';
1.1000    raeburn  5721:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5722:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5723:     }
                   5724:     $cmd =~ s/%%$//;
                   5725:     $cmd = &escape($cmd);
                   5726:     my $query = 'fetchenrollment';
1.620     albertel 5727:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5728:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5729:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5730:         return 'error: '.$queryid;
                   5731:     }
1.506     raeburn  5732:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5733:     my $tries = 1;
                   5734:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5735:         $reply = &get_query_reply($queryid);
                   5736:         $tries ++;
                   5737:     }
1.526     raeburn  5738:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5739:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5740:     } else {
1.901     albertel 5741:         my @responses = split(/:/,$reply);
1.515     raeburn  5742:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5743:             foreach my $line (@responses) {
                   5744:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5745:                 $$replyref{$key} = $value;
                   5746:             }
                   5747:         } else {
1.506     raeburn  5748:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5749:             foreach my $line (@responses) {
                   5750:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5751:                 $$replyref{$key} = $value;
                   5752:                 if ($value > 0) {
1.800     albertel 5753:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5754:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5755:                         my $destname = $pathname.'/'.$filename;
                   5756:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5757:                         if ($xml_classlist =~ /^error/) {
                   5758:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5759:                         } else {
1.506     raeburn  5760:                             if ( open(FILE,">$destname") ) {
                   5761:                                 print FILE &unescape($xml_classlist);
                   5762:                                 close(FILE);
1.526     raeburn  5763:                             } else {
                   5764:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5765:                             }
                   5766:                         }
                   5767:                     }
                   5768:                 }
                   5769:             }
                   5770:         }
                   5771:         return 'ok';
                   5772:     }
                   5773:     return 'error';
                   5774: }
                   5775: 
1.242     www      5776: sub get_query_reply {
                   5777:     my $queryid=shift;
1.240     www      5778:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5779:     my $reply='';
                   5780:     for (1..100) {
                   5781: 	sleep 2;
                   5782:         if (-e $replyfile.'.end') {
1.448     albertel 5783: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5784: 		$reply = join('',<$fh>);
                   5785: 		close($fh);
1.240     www      5786: 	   } else { return 'error: reply_file_error'; }
1.242     www      5787:            return &unescape($reply);
                   5788: 	}
1.240     www      5789:     }
1.242     www      5790:     return 'timeout:'.$queryid;
1.240     www      5791: }
                   5792: 
                   5793: sub courselog_query {
1.241     www      5794: #
                   5795: # possible filters:
                   5796: # url: url or symb
                   5797: # username
                   5798: # domain
                   5799: # action: view, submit, grade
                   5800: # start: timestamp
                   5801: # end: timestamp
                   5802: #
1.240     www      5803:     my (%filters)=@_;
1.620     albertel 5804:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5805:     if ($filters{'url'}) {
                   5806: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5807:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5808:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5809:     }
1.620     albertel 5810:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5811:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5812:     return &log_query($cname,$cdom,'courselog',%filters);
                   5813: }
                   5814: 
                   5815: sub userlog_query {
1.858     raeburn  5816: #
                   5817: # possible filters:
                   5818: # action: log check role
                   5819: # start: timestamp
                   5820: # end: timestamp
                   5821: #
1.240     www      5822:     my ($uname,$udom,%filters)=@_;
                   5823:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5824: }
                   5825: 
1.506     raeburn  5826: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5827: 
                   5828: sub auto_run {
1.508     raeburn  5829:     my ($cnum,$cdom) = @_;
1.876     raeburn  5830:     my $response = 0;
                   5831:     my $settings;
                   5832:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5833:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5834:         $settings = $domconfig{'autoenroll'};
                   5835:         if ($settings->{'run'} eq '1') {
                   5836:             $response = 1;
                   5837:         }
                   5838:     } else {
1.934     raeburn  5839:         my $homeserver;
                   5840:         if (&is_course($cdom,$cnum)) {
                   5841:             $homeserver = &homeserver($cnum,$cdom);
                   5842:         } else {
                   5843:             $homeserver = &domain($cdom,'primary');
                   5844:         }
                   5845:         if ($homeserver ne 'no_host') {
                   5846:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5847:         }
1.876     raeburn  5848:     }
1.506     raeburn  5849:     return $response;
                   5850: }
1.776     albertel 5851: 
1.506     raeburn  5852: sub auto_get_sections {
1.508     raeburn  5853:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5854:     my $homeserver;
                   5855:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5856:         $homeserver = &homeserver($cnum,$cdom);
                   5857:     }
                   5858:     if (!defined($homeserver)) { 
                   5859:         if ($cdom =~ /^$match_domain$/) {
                   5860:             $homeserver = &domain($cdom,'primary');
                   5861:         }
                   5862:     }
                   5863:     my @secs;
                   5864:     if (defined($homeserver)) {
                   5865:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5866:         unless ($response eq 'refused') {
                   5867:             @secs = split(/:/,$response);
                   5868:         }
1.506     raeburn  5869:     }
                   5870:     return @secs;
                   5871: }
1.776     albertel 5872: 
1.506     raeburn  5873: sub auto_new_course {
1.508     raeburn  5874:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5875:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5876:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5877:     return $response;
                   5878: }
1.776     albertel 5879: 
1.506     raeburn  5880: sub auto_validate_courseID {
1.508     raeburn  5881:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5882:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5883:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5884:     return $response;
                   5885: }
1.776     albertel 5886: 
1.1007    raeburn  5887: sub auto_validate_instcode {
1.1020    raeburn  5888:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  5889:     my ($homeserver,$response);
                   5890:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5891:         $homeserver = &homeserver($cnum,$cdom);
                   5892:     }
                   5893:     if (!defined($homeserver)) {
                   5894:         if ($cdom =~ /^$match_domain$/) {
                   5895:             $homeserver = &domain($cdom,'primary');
                   5896:         }
                   5897:     }
1.1065    raeburn  5898:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   5899:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  5900:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   5901:     return ($outcome,$description);
1.1007    raeburn  5902: }
                   5903: 
1.506     raeburn  5904: sub auto_create_password {
1.873     raeburn  5905:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5906:     my ($homeserver,$response);
1.506     raeburn  5907:     my $create_passwd = 0;
                   5908:     my $authchk = '';
1.873     raeburn  5909:     if ($udom =~ /^$match_domain$/) {
                   5910:         $homeserver = &domain($udom,'primary');
                   5911:     }
                   5912:     if ($homeserver eq '') {
                   5913:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5914:             $homeserver = &homeserver($cnum,$cdom);
                   5915:         }
                   5916:     }
                   5917:     if ($homeserver eq '') {
                   5918:         $authchk = 'nodomain';
1.506     raeburn  5919:     } else {
1.873     raeburn  5920:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5921:         if ($response eq 'refused') {
                   5922:             $authchk = 'refused';
                   5923:         } else {
1.901     albertel 5924:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5925:         }
1.506     raeburn  5926:     }
                   5927:     return ($authparam,$create_passwd,$authchk);
                   5928: }
                   5929: 
1.706     raeburn  5930: sub auto_photo_permission {
                   5931:     my ($cnum,$cdom,$students) = @_;
                   5932:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5933:     my ($outcome,$perm_reqd,$conditions) = 
                   5934: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5935:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5936: 	return (undef,undef);
                   5937:     }
1.706     raeburn  5938:     return ($outcome,$perm_reqd,$conditions);
                   5939: }
                   5940: 
                   5941: sub auto_checkphotos {
                   5942:     my ($uname,$udom,$pid) = @_;
                   5943:     my $homeserver = &homeserver($uname,$udom);
                   5944:     my ($result,$resulttype);
                   5945:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5946: 				   &escape($uname).':'.&escape($pid),
                   5947: 				   $homeserver));
1.709     albertel 5948:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5949: 	return (undef,undef);
                   5950:     }
1.706     raeburn  5951:     if ($outcome) {
                   5952:         ($result,$resulttype) = split(/:/,$outcome);
                   5953:     } 
                   5954:     return ($result,$resulttype);
                   5955: }
                   5956: 
                   5957: sub auto_photochoice {
                   5958:     my ($cnum,$cdom) = @_;
                   5959:     my $homeserver = &homeserver($cnum,$cdom);
                   5960:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5961: 						       &escape($cdom),
                   5962: 						       $homeserver)));
1.709     albertel 5963:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5964: 	return (undef,undef);
                   5965:     }
1.706     raeburn  5966:     return ($update,$comment);
                   5967: }
                   5968: 
                   5969: sub auto_photoupdate {
                   5970:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5971:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5972:     my $host=&hostname($homeserver);
1.706     raeburn  5973:     my $cmd = '';
                   5974:     my $maxtries = 1;
1.800     albertel 5975:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5976:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5977:     }
                   5978:     $cmd =~ s/%%$//;
                   5979:     $cmd = &escape($cmd);
                   5980:     my $query = 'institutionalphotos';
                   5981:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5982:     unless ($queryid=~/^\Q$host\E\_/) {
                   5983:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5984:         return 'error: '.$queryid;
                   5985:     }
                   5986:     my $reply = &get_query_reply($queryid);
                   5987:     my $tries = 1;
                   5988:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5989:         $reply = &get_query_reply($queryid);
                   5990:         $tries ++;
                   5991:     }
                   5992:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5993:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5994:     } else {
                   5995:         my @responses = split(/:/,$reply);
                   5996:         my $outcome = shift(@responses); 
                   5997:         foreach my $item (@responses) {
                   5998:             my ($key,$value) = split(/=/,$item);
                   5999:             $$photo{$key} = $value;
                   6000:         }
                   6001:         return $outcome;
                   6002:     }
                   6003:     return 'error';
                   6004: }
                   6005: 
1.521     raeburn  6006: sub auto_instcode_format {
1.793     albertel 6007:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6008: 	$cat_order) = @_;
1.521     raeburn  6009:     my $courses = '';
1.772     raeburn  6010:     my @homeservers;
1.521     raeburn  6011:     if ($caller eq 'global') {
1.841     albertel 6012: 	my %servers = &get_servers($codedom,'library');
                   6013: 	foreach my $tryserver (keys(%servers)) {
                   6014: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6015: 		push(@homeservers,$tryserver);
                   6016: 	    }
1.584     raeburn  6017:         }
1.1022    raeburn  6018:     } elsif ($caller eq 'requests') {
                   6019:         if ($codedom =~ /^$match_domain$/) {
                   6020:             my $chome = &domain($codedom,'primary');
                   6021:             unless ($chome eq 'no_host') {
                   6022:                 push(@homeservers,$chome);
                   6023:             }
                   6024:         }
1.521     raeburn  6025:     } else {
1.772     raeburn  6026:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6027:     }
1.793     albertel 6028:     foreach my $code (keys(%{$instcodes})) {
                   6029:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6030:     }
                   6031:     chop($courses);
1.772     raeburn  6032:     my $ok_response = 0;
                   6033:     my $response;
                   6034:     while (@homeservers > 0 && $ok_response == 0) {
                   6035:         my $server = shift(@homeservers); 
                   6036:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6037:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6038:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6039: 		split(/:/,$response);
1.772     raeburn  6040:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6041:             push(@{$codetitles},&str2array($codetitles_str));
                   6042:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6043:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6044:             $ok_response = 1;
                   6045:         }
                   6046:     }
                   6047:     if ($ok_response) {
1.521     raeburn  6048:         return 'ok';
1.772     raeburn  6049:     } else {
                   6050:         return $response;
1.521     raeburn  6051:     }
                   6052: }
                   6053: 
1.792     raeburn  6054: sub auto_instcode_defaults {
                   6055:     my ($domain,$returnhash,$code_order) = @_;
                   6056:     my @homeservers;
1.841     albertel 6057: 
                   6058:     my %servers = &get_servers($domain,'library');
                   6059:     foreach my $tryserver (keys(%servers)) {
                   6060: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6061: 	    push(@homeservers,$tryserver);
                   6062: 	}
1.792     raeburn  6063:     }
1.841     albertel 6064: 
1.792     raeburn  6065:     my $response;
1.841     albertel 6066:     foreach my $server (@homeservers) {
1.792     raeburn  6067:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6068:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6069: 	
                   6070: 	foreach my $pair (split(/\&/,$response)) {
                   6071: 	    my ($name,$value)=split(/\=/,$pair);
                   6072: 	    if ($name eq 'code_order') {
                   6073: 		@{$code_order} = split(/\&/,&unescape($value));
                   6074: 	    } else {
                   6075: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6076: 	    }
                   6077: 	}
                   6078: 	return 'ok';
1.792     raeburn  6079:     }
1.841     albertel 6080: 
                   6081:     return $response;
1.1003    raeburn  6082: }
                   6083: 
                   6084: sub auto_possible_instcodes {
1.1007    raeburn  6085:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6086:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6087:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6088:         return;
                   6089:     }
1.1003    raeburn  6090:     my (@homeservers,$uhome);
                   6091:     if (defined(&domain($domain,'primary'))) {
                   6092:         $uhome=&domain($domain,'primary');
                   6093:         push(@homeservers,&domain($domain,'primary'));
                   6094:     } else {
                   6095:         my %servers = &get_servers($domain,'library');
                   6096:         foreach my $tryserver (keys(%servers)) {
                   6097:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6098:                 push(@homeservers,$tryserver);
                   6099:             }
                   6100:         }
                   6101:     }
                   6102:     my $response;
                   6103:     foreach my $server (@homeservers) {
                   6104:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6105:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6106:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6107:             split(':',$response);
                   6108:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6109:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6110:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6111:             my ($name,$value)=split('=',$item);
                   6112:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6113:         }
                   6114:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6115:             my ($name,$value)=split('=',$item);
                   6116:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6117:         }
                   6118:         return 'ok';
                   6119:     }
                   6120:     return $response;
                   6121: }
1.792     raeburn  6122: 
1.1010    raeburn  6123: sub auto_courserequest_checks {
                   6124:     my ($dom) = @_;
1.1020    raeburn  6125:     my ($homeserver,%validations);
                   6126:     if ($dom =~ /^$match_domain$/) {
                   6127:         $homeserver = &domain($dom,'primary');
                   6128:     }
                   6129:     unless ($homeserver eq 'no_host') {
                   6130:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6131:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6132:             my @items = split(/&/,$response);
                   6133:             foreach my $item (@items) {
                   6134:                 my ($key,$value) = split('=',$item);
                   6135:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6136:             }
                   6137:         }
                   6138:     }
1.1010    raeburn  6139:     return %validations; 
                   6140: }
                   6141: 
1.1020    raeburn  6142: sub auto_courserequest_validation {
                   6143:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6144:     my ($homeserver,$response);
                   6145:     if ($dom =~ /^$match_domain$/) {
                   6146:         $homeserver = &domain($dom,'primary');
                   6147:     }
                   6148:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6149:           
1.1020    raeburn  6150:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6151:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6152:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6153:                                     $homeserver));
                   6154:     }
                   6155:     return $response;
                   6156: }
                   6157: 
1.777     albertel 6158: sub auto_validate_class_sec {
1.918     raeburn  6159:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6160:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6161:     my $ownerlist;
                   6162:     if (ref($owners) eq 'ARRAY') {
                   6163:         $ownerlist = join(',',@{$owners});
                   6164:     } else {
                   6165:         $ownerlist = $owners;
                   6166:     }
1.773     raeburn  6167:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6168:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6169:     return $response;
                   6170: }
                   6171: 
1.679     raeburn  6172: # ------------------------------------------------------- Course Group routines
                   6173: 
                   6174: sub get_coursegroups {
1.809     raeburn  6175:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6176:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6177: }
                   6178: 
1.679     raeburn  6179: sub modify_coursegroup {
                   6180:     my ($cdom,$cnum,$groupsettings) = @_;
                   6181:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6182: }
                   6183: 
1.809     raeburn  6184: sub toggle_coursegroup_status {
                   6185:     my ($cdom,$cnum,$group,$action) = @_;
                   6186:     my ($from_namespace,$to_namespace);
                   6187:     if ($action eq 'delete') {
                   6188:         $from_namespace = 'coursegroups';
                   6189:         $to_namespace = 'deleted_groups';
                   6190:     } else {
                   6191:         $from_namespace = 'deleted_groups';
                   6192:         $to_namespace = 'coursegroups';
                   6193:     }
                   6194:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6195:     if (my $tmp = &error(%curr_group)) {
                   6196:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6197:         return ('read error',$tmp);
                   6198:     } else {
                   6199:         my %savedsettings = %curr_group; 
1.809     raeburn  6200:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6201:         my $deloutcome;
                   6202:         if ($result eq 'ok') {
1.809     raeburn  6203:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6204:         } else {
                   6205:             return ('write error',$result);
                   6206:         }
                   6207:         if ($deloutcome eq 'ok') {
                   6208:             return 'ok';
                   6209:         } else {
                   6210:             return ('delete error',$deloutcome);
                   6211:         }
                   6212:     }
                   6213: }
                   6214: 
1.679     raeburn  6215: sub modify_group_roles {
1.957     raeburn  6216:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6217:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6218:     my $role = 'gr/'.&escape($userprivs);
                   6219:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6220:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6221:     if ($result eq 'ok') {
                   6222:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6223:     }
1.679     raeburn  6224:     return $result;
                   6225: }
                   6226: 
                   6227: sub modify_coursegroup_membership {
                   6228:     my ($cdom,$cnum,$membership) = @_;
                   6229:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6230:     return $result;
                   6231: }
                   6232: 
1.682     raeburn  6233: sub get_active_groups {
                   6234:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6235:     my $now = time;
                   6236:     my %groups = ();
                   6237:     foreach my $key (keys(%env)) {
1.811     albertel 6238:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6239:             my ($start,$end) = split(/\./,$env{$key});
                   6240:             if (($end!=0) && ($end<$now)) { next; }
                   6241:             if (($start!=0) && ($start>$now)) { next; }
                   6242:             if ($1 eq $cdom && $2 eq $cnum) {
                   6243:                 $groups{$3} = $env{$key} ;
                   6244:             }
                   6245:         }
                   6246:     }
                   6247:     return %groups;
                   6248: }
                   6249: 
1.683     raeburn  6250: sub get_group_membership {
                   6251:     my ($cdom,$cnum,$group) = @_;
                   6252:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6253: }
                   6254: 
                   6255: sub get_users_groups {
                   6256:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6257:     my @usersgroups;
1.683     raeburn  6258:     my $cachetime=1800;
                   6259: 
                   6260:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6261:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6262:     if (defined($cached)) {
1.734     albertel 6263:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6264:     } else {  
                   6265:         $grouplist = '';
1.816     raeburn  6266:         my $courseurl = &courseid_to_courseurl($courseid);
                   6267:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  6268:         my $access_end = $env{'course.'.$courseid.
                   6269:                               '.default_enrollment_end_date'};
                   6270:         my $now = time;
                   6271:         foreach my $key (keys(%roleshash)) {
                   6272:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6273:                 my $group = $1;
                   6274:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6275:                     my $start = $2;
                   6276:                     my $end = $1;
                   6277:                     if ($start == -1) { next; } # deleted from group
                   6278:                     if (($start!=0) && ($start>$now)) { next; }
                   6279:                     if (($end!=0) && ($end<$now)) {
                   6280:                         if ($access_end && $access_end < $now) {
                   6281:                             if ($access_end - $end < 86400) {
                   6282:                                 push(@usersgroups,$group);
1.733     raeburn  6283:                             }
                   6284:                         }
1.817     raeburn  6285:                         next;
1.733     raeburn  6286:                     }
1.817     raeburn  6287:                     push(@usersgroups,$group);
1.683     raeburn  6288:                 }
                   6289:             }
                   6290:         }
1.817     raeburn  6291:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6292:         $grouplist = join(':',@usersgroups);
                   6293:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6294:     }
1.733     raeburn  6295:     return @usersgroups;
1.683     raeburn  6296: }
                   6297: 
                   6298: sub devalidate_getgroups_cache {
                   6299:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6300:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6301: 
1.683     raeburn  6302:     my $hashid="$udom:$uname:$courseid";
                   6303:     &devalidate_cache_new('getgroups',$hashid);
                   6304: }
                   6305: 
1.12      www      6306: # ------------------------------------------------------------------ Plain Text
                   6307: 
                   6308: sub plaintext {
1.988     raeburn  6309:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6310:     if ($short =~ m{^cr/}) {
1.758     albertel 6311: 	return (split('/',$short))[-1];
                   6312:     }
1.742     raeburn  6313:     if (!defined($cid)) {
                   6314:         $cid = $env{'request.course.id'};
                   6315:     }
                   6316:     my %rolenames = (
1.1008    raeburn  6317:                       Course    => 'std',
                   6318:                       Community => 'alt1',
1.742     raeburn  6319:                     );
1.1037    raeburn  6320:     if ($cid ne '') {
                   6321:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6322:             unless ($forcedefault) {
                   6323:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6324:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6325:                 return &Apache::lonlocal::mt($roletext);
                   6326:             }
                   6327:         }
                   6328:     }
                   6329:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6330:         (defined($rolenames{$type})) && 
                   6331:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6332:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6333:     } elsif ($cid ne '') {
                   6334:         my $crstype = $env{'course.'.$cid.'.type'};
                   6335:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6336:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6337:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6338:         }
1.742     raeburn  6339:     }
1.1037    raeburn  6340:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6341: }
                   6342: 
                   6343: # ----------------------------------------------------------------- Assign Role
                   6344: 
                   6345: sub assignrole {
1.957     raeburn  6346:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6347:         $context)=@_;
1.21      www      6348:     my $mrole;
                   6349:     if ($role =~ /^cr\//) {
1.393     www      6350:         my $cwosec=$url;
1.811     albertel 6351:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6352: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6353:            my $refused = 1;
                   6354:            if ($context eq 'requestcourses') {
                   6355:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6356:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6357:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6358:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6359:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6360:                            if ($crsenv{'internal.courseowner'} eq
                   6361:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6362:                                $refused = '';
                   6363:                            }
                   6364:                        }
                   6365:                    }
                   6366:                }
                   6367:            }
                   6368:            if ($refused) {
                   6369:                &logthis('Refused custom assignrole: '.
                   6370:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6371:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6372:                return 'refused';
                   6373:            }
1.104     www      6374:         }
1.21      www      6375:         $mrole='cr';
1.678     raeburn  6376:     } elsif ($role =~ /^gr\//) {
                   6377:         my $cwogrp=$url;
1.811     albertel 6378:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6379:         unless (&allowed('mdg',$cwogrp)) {
                   6380:             &logthis('Refused group assignrole: '.
                   6381:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6382:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6383:             return 'refused';
                   6384:         }
                   6385:         $mrole='gr';
1.21      www      6386:     } else {
1.82      www      6387:         my $cwosec=$url;
1.811     albertel 6388:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6389:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6390:             my $refused;
                   6391:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6392:                 if (!(&allowed('c'.$role,$url))) {
                   6393:                     $refused = 1;
                   6394:                 }
                   6395:             } else {
                   6396:                 $refused = 1;
                   6397:             }
1.947     raeburn  6398:             if ($refused) {
1.1045    raeburn  6399:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6400:                 if (!$selfenroll && $context eq 'course') {
                   6401:                     my %crsenv;
                   6402:                     if ($role eq 'cc' || $role eq 'co') {
                   6403:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6404:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6405:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6406:                                 if ($crsenv{'internal.courseowner'} eq 
                   6407:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6408:                                     $refused = '';
                   6409:                                 }
                   6410:                             }
                   6411:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6412:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6413:                                 if ($crsenv{'internal.courseowner'} eq 
                   6414:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6415:                                     $refused = '';
                   6416:                                 }
                   6417:                             }
                   6418:                         }
                   6419:                     }
                   6420:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6421:                     $refused = '';
1.1017    raeburn  6422:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6423:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6424:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6425:                         my $wrongcc;
                   6426:                         if ($cnum =~ /^$match_community$/) {
                   6427:                             $wrongcc = 1 if ($role eq 'cc');
                   6428:                         } else {
                   6429:                             $wrongcc = 1 if ($role eq 'co');
                   6430:                         }
                   6431:                         unless ($wrongcc) {
                   6432:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6433:                             if ($crsenv{'internal.courseowner'} eq 
                   6434:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6435:                                 $refused = '';
                   6436:                             }
1.1017    raeburn  6437:                         }
                   6438:                     }
                   6439:                 }
                   6440:                 if ($refused) {
1.947     raeburn  6441:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6442:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6443: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6444:                     return 'refused';
                   6445:                 }
1.932     raeburn  6446:             }
1.104     www      6447:         }
1.21      www      6448:         $mrole=$role;
                   6449:     }
1.620     albertel 6450:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6451:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6452:     if ($end) { $command.='_'.$end; }
1.21      www      6453:     if ($start) {
                   6454: 	if ($end) { 
1.81      www      6455:            $command.='_'.$start; 
1.21      www      6456:         } else {
1.81      www      6457:            $command.='_0_'.$start;
1.21      www      6458:         }
                   6459:     }
1.739     raeburn  6460:     my $origstart = $start;
                   6461:     my $origend = $end;
1.957     raeburn  6462:     my $delflag;
1.357     www      6463: # actually delete
                   6464:     if ($deleteflag) {
1.373     www      6465: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6466: # modify command to delete the role
1.620     albertel 6467:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6468:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6469: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6470: # set start and finish to negative values for userrolelog
                   6471:            $start=-1;
                   6472:            $end=-1;
1.957     raeburn  6473:            $delflag = 1;
1.357     www      6474:         }
                   6475:     }
                   6476: # send command
1.349     www      6477:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6478: # log new user role if status is ok
1.349     www      6479:     if ($answer eq 'ok') {
1.663     raeburn  6480: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6481: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6482:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6483:         unless ($role =~ /^gr/) {
                   6484:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6485:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6486:         }
1.1053    raeburn  6487:         if ($role eq 'cc') {
                   6488:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6489:         }
1.349     www      6490:     }
                   6491:     return $answer;
1.169     harris41 6492: }
                   6493: 
1.1053    raeburn  6494: sub autoupdate_coowners {
                   6495:     my ($url,$end,$start,$uname,$udom) = @_;
                   6496:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6497:     if (($cdom ne '') && ($cnum ne '')) {
                   6498:         my $now = time;
                   6499:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6500:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6501:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6502:             my $instcode = $coursehash{'internal.coursecode'};
                   6503:             if ($instcode ne '') {
1.1056    raeburn  6504:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6505:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6506:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6507:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6508:                         if ($result eq 'valid') {
                   6509:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6510:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6511:                                     push(@newcoowners,$coowner);
                   6512:                                 }
                   6513:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6514:                                     push(@newcoowners,$uname.':'.$udom);
                   6515:                                 }
                   6516:                                 @newcoowners = sort(@newcoowners);
                   6517:                             } else {
                   6518:                                 push(@newcoowners,$uname.':'.$udom);
                   6519:                             }
                   6520:                         } else {
                   6521:                             if ($coursehash{'internal.co-owners'}) {
                   6522:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6523:                                     unless ($coowner eq $uname.':'.$udom) {
                   6524:                                         push(@newcoowners,$coowner);
                   6525:                                     }
                   6526:                                 }
                   6527:                                 unless (@newcoowners > 0) {
                   6528:                                     $delcoowners = 1;
                   6529:                                     $coowners = '';
                   6530:                                 }
                   6531:                             }
                   6532:                         }
                   6533:                         if (@newcoowners || $delcoowners) {
                   6534:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6535:                                             $delcoowners,@newcoowners);
                   6536:                         }
                   6537:                     }
                   6538:                 }
                   6539:             }
                   6540:         }
                   6541:     }
                   6542: }
                   6543: 
                   6544: sub store_coowners {
                   6545:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6546:     my $cid = $cdom.'_'.$cnum;
                   6547:     my ($coowners,$delresult,$putresult);
                   6548:     if (@newcoowners) {
                   6549:         $coowners = join(',',@newcoowners);
                   6550:         my %coownershash = (
                   6551:                             'internal.co-owners' => $coowners,
                   6552:                            );
                   6553:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6554:         if ($putresult eq 'ok') {
                   6555:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6556:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6557:             }
                   6558:         }
                   6559:     }
                   6560:     if ($delcoowners) {
                   6561:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6562:         if ($delresult eq 'ok') {
                   6563:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6564:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6565:             }
                   6566:         }
                   6567:     }
                   6568:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6569:         my %crsinfo =
                   6570:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6571:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6572:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6573:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6574:         }
                   6575:     }
                   6576: }
                   6577: 
1.169     harris41 6578: # -------------------------------------------------- Modify user authentication
1.197     www      6579: # Overrides without validation
                   6580: 
1.169     harris41 6581: sub modifyuserauth {
                   6582:     my ($udom,$uname,$umode,$upass)=@_;
                   6583:     my $uhome=&homeserver($uname,$udom);
1.197     www      6584:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6585:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6586:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6587:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6588:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6589: 		     &escape($upass),$uhome);
1.620     albertel 6590:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6591:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6592:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6593:     &log($udom,,$uname,$uhome,
1.620     albertel 6594:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6595:                                      $env{'user.name'}.', '.$umode.
1.197     www      6596:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6597:     unless ($reply eq 'ok') {
1.197     www      6598:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6599: 	return 'error: '.$reply;
                   6600:     }   
1.170     harris41 6601:     return 'ok';
1.80      www      6602: }
                   6603: 
1.81      www      6604: # --------------------------------------------------------------- Modify a user
1.80      www      6605: 
1.81      www      6606: sub modifyuser {
1.206     matthew  6607:     my ($udom,    $uname, $uid,
                   6608:         $umode,   $upass, $first,
                   6609:         $middle,  $last,  $gene,
1.1058    raeburn  6610:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6611:     $udom= &LONCAPA::clean_domain($udom);
                   6612:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6613:     my $showcandelete = 'none';
                   6614:     if (ref($candelete) eq 'ARRAY') {
                   6615:         if (@{$candelete} > 0) {
                   6616:             $showcandelete = join(', ',@{$candelete});
                   6617:         }
                   6618:     }
1.81      www      6619:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6620:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6621: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6622:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6623:                                      ' desiredhome not specified'). 
1.620     albertel 6624:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6625:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6626:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6627:     my $newuser;
                   6628:     if ($uhome eq 'no_host') {
                   6629:         $newuser = 1;
                   6630:     }
1.80      www      6631: # ----------------------------------------------------------------- Create User
1.406     albertel 6632:     if (($uhome eq 'no_host') && 
                   6633: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6634:         my $unhome='';
1.844     albertel 6635:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6636:             $unhome = $desiredhome;
1.620     albertel 6637: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6638: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6639:         } else { # load balancing routine for determining $unhome
1.81      www      6640:             my $loadm=10000000;
1.841     albertel 6641: 	    my %servers = &get_servers($udom,'library');
                   6642: 	    foreach my $tryserver (keys(%servers)) {
                   6643: 		my $answer=reply('load',$tryserver);
                   6644: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6645: 		    $loadm=$answer;
                   6646: 		    $unhome=$tryserver;
                   6647: 		}
1.80      www      6648: 	    }
                   6649:         }
                   6650:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6651: 	    return 'error: unable to find a home server for '.$uname.
                   6652:                    ' in domain '.$udom;
1.80      www      6653:         }
                   6654:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6655:                          &escape($upass),$unhome);
                   6656: 	unless ($reply eq 'ok') {
                   6657:             return 'error: '.$reply;
                   6658:         }   
1.230     stredwic 6659:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6660:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6661: 	    return 'error: unable verify users home machine.';
1.80      www      6662:         }
1.209     matthew  6663:     }   # End of creation of new user
1.80      www      6664: # ---------------------------------------------------------------------- Add ID
                   6665:     if ($uid) {
                   6666:        $uid=~tr/A-Z/a-z/;
                   6667:        my %uidhash=&idrget($udom,$uname);
1.196     www      6668:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6669:          && (!$forceid)) {
1.80      www      6670: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6671: 	      return 'error: user id "'.$uid.'" does not match '.
                   6672:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6673:           }
                   6674:        } else {
                   6675: 	  &idput($udom,($uname => $uid));
                   6676:        }
                   6677:     }
                   6678: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6679:     my @tmp=&get('environment',
1.899     raeburn  6680: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6681:                     'permanentemail','inststatus'],
1.134     albertel 6682: 		   $udom,$uname);
1.1075    raeburn  6683:     my (%names,%oldnames);
1.313     matthew  6684:     if ($tmp[0] =~ m/^error:.*/) { 
                   6685:         %names=(); 
                   6686:     } else {
                   6687:         %names = @tmp;
1.1075    raeburn  6688:         %oldnames = %names;
1.313     matthew  6689:     }
1.388     www      6690: #
1.1058    raeburn  6691: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6692: # of users did not contain them), do not overwrite existing values
                   6693: # unless field is in $candelete array ref.  
                   6694: #
                   6695: 
                   6696:     my @fields = ('firstname','middlename','lastname','generation',
                   6697:                   'permanentemail','id');
                   6698:     my %newvalues;
                   6699:     if (ref($candelete) eq 'ARRAY') {
                   6700:         foreach my $field (@fields) {
                   6701:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6702:                 if ($field eq 'firstname') {
                   6703:                     $names{$field} = $first;
                   6704:                 } elsif ($field eq 'middlename') {
                   6705:                     $names{$field} = $middle;
                   6706:                 } elsif ($field eq 'lastname') {
                   6707:                     $names{$field} = $last;
                   6708:                 } elsif ($field eq 'generation') { 
                   6709:                     $names{$field} = $gene;
                   6710:                 } elsif ($field eq 'permanentemail') {
                   6711:                     $names{$field} = $email;
                   6712:                 } elsif ($field eq 'id') {
                   6713:                     $names{$field}  = $uid;
                   6714:                 }
                   6715:             }
                   6716:         }
                   6717:     }
1.388     www      6718:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6719:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6720:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6721:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6722:     if ($email) {
                   6723:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6724:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6725:     }
1.899     raeburn  6726:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6727:     if (defined($inststatus)) {
                   6728:         $names{'inststatus'} = '';
                   6729:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6730:         if (ref($usertypes) eq 'HASH') {
                   6731:             my @okstatuses; 
                   6732:             foreach my $item (split(/:/,$inststatus)) {
                   6733:                 if (defined($usertypes->{$item})) {
                   6734:                     push(@okstatuses,$item);  
                   6735:                 }
                   6736:             }
                   6737:             if (@okstatuses) {
                   6738:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6739:             }
                   6740:         }
                   6741:     }
1.1075    raeburn  6742:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6743:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  6744:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6745:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6746:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6747:     } else {
                   6748:         $logmsg .= ' during self creation';
                   6749:     }
1.1075    raeburn  6750:     my $changed;
                   6751:     if ($newuser) {
                   6752:         $changed = 1;
                   6753:     } else {
                   6754:         foreach my $field (@fields) {
                   6755:             if ($names{$field} ne $oldnames{$field}) {
                   6756:                 $changed = 1;
                   6757:                 last;
                   6758:             }
                   6759:         }
                   6760:     }
                   6761:     unless ($changed) {
                   6762:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6763:         &logthis($logmsg);
                   6764:         return 'ok';
                   6765:     }
                   6766:     my $reply = &put('environment', \%names, $udom,$uname);
                   6767:     if ($reply ne 'ok') { 
                   6768:         return 'error: '.$reply;
                   6769:     }
                   6770:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6771:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6772:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6773:     &logthis($logmsg);
1.134     albertel 6774:     return 'ok';
1.80      www      6775: }
                   6776: 
1.81      www      6777: # -------------------------------------------------------------- Modify student
1.80      www      6778: 
1.81      www      6779: sub modifystudent {
                   6780:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6781:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6782:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6783:     if (!$cid) {
1.620     albertel 6784: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6785: 	    return 'not_in_class';
                   6786: 	}
1.80      www      6787:     }
                   6788: # --------------------------------------------------------------- Make the user
1.81      www      6789:     my $reply=&modifyuser
1.209     matthew  6790: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6791:          $desiredhome,$email,$inststatus);
1.80      www      6792:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6793:     # This will cause &modify_student_enrollment to get the uid from the
                   6794:     # students environment
                   6795:     $uid = undef if (!$forceid);
1.455     albertel 6796:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6797: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6798:     return $reply;
                   6799: }
                   6800: 
                   6801: sub modify_student_enrollment {
1.957     raeburn  6802:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6803:     my ($cdom,$cnum,$chome);
                   6804:     if (!$cid) {
1.620     albertel 6805: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6806: 	    return 'not_in_class';
                   6807: 	}
1.620     albertel 6808: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6809: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6810:     } else {
                   6811: 	($cdom,$cnum)=split(/_/,$cid);
                   6812:     }
1.620     albertel 6813:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6814:     if (!$chome) {
1.457     raeburn  6815: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6816:     }
1.455     albertel 6817:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6818:     # Make sure the user exists
1.81      www      6819:     my $uhome=&homeserver($uname,$udom);
                   6820:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6821: 	return 'error: no such user';
                   6822:     }
1.297     matthew  6823:     # Get student data if we were not given enough information
                   6824:     if (!defined($first)  || $first  eq '' || 
                   6825:         !defined($last)   || $last   eq '' || 
                   6826:         !defined($uid)    || $uid    eq '' || 
                   6827:         !defined($middle) || $middle eq '' || 
                   6828:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6829:         # They did not supply us with enough data to enroll the student, so
                   6830:         # we need to pick up more information.
1.297     matthew  6831:         my %tmp = &get('environment',
1.294     matthew  6832:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6833:                        ,$udom,$uname);
                   6834: 
1.800     albertel 6835:         #foreach my $key (keys(%tmp)) {
                   6836:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6837:         #}
1.294     matthew  6838:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6839:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6840:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6841:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6842:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6843:     }
1.556     albertel 6844:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6845:     my $reply=cput('classlist',
                   6846: 		   {"$uname:$udom" => 
1.515     raeburn  6847: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6848: 		   $cdom,$cnum);
1.81      www      6849:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6850: 	return 'error: '.$reply;
1.652     albertel 6851:     } else {
                   6852: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6853:     }
1.297     matthew  6854:     # Add student role to user
1.83      www      6855:     my $uurl='/'.$cid;
1.81      www      6856:     $uurl=~s/\_/\//g;
                   6857:     if ($usec) {
                   6858: 	$uurl.='/'.$usec;
                   6859:     }
1.957     raeburn  6860:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6861: }
                   6862: 
1.556     albertel 6863: sub format_name {
                   6864:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6865:     my $name;
                   6866:     if ($first ne 'lastname') {
                   6867: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6868:     } else {
                   6869: 	if ($lastname=~/\S/) {
                   6870: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6871: 	    $name=~s/\s+,/,/;
                   6872: 	} else {
                   6873: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6874: 	}
                   6875:     }
                   6876:     $name=~s/^\s+//;
                   6877:     $name=~s/\s+$//;
                   6878:     $name=~s/\s+/ /g;
                   6879:     return $name;
                   6880: }
                   6881: 
1.84      www      6882: # ------------------------------------------------- Write to course preferences
                   6883: 
                   6884: sub writecoursepref {
                   6885:     my ($courseid,%prefs)=@_;
                   6886:     $courseid=~s/^\///;
                   6887:     $courseid=~s/\_/\//g;
                   6888:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6889:     my $chome=homeserver($cnum,$cdomain);
                   6890:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6891: 	return 'error: no such course';
                   6892:     }
                   6893:     my $cstring='';
1.800     albertel 6894:     foreach my $pref (keys(%prefs)) {
                   6895: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6896:     }
1.84      www      6897:     $cstring=~s/\&$//;
                   6898:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6899: }
                   6900: 
                   6901: # ---------------------------------------------------------- Make/modify course
                   6902: 
                   6903: sub createcourse {
1.741     raeburn  6904:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  6905:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      6906:     $url=&declutter($url);
                   6907:     my $cid='';
1.1028    raeburn  6908:     if ($context eq 'requestcourses') {
                   6909:         my $can_create = 0;
                   6910:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   6911:         if ($udom eq $ownerdom) {
                   6912:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   6913:                                   $context)) {
                   6914:                 $can_create = 1;
                   6915:             }
                   6916:         } else {
                   6917:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   6918:                                            $category);
                   6919:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   6920:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   6921:                 if (@curr > 0) {
                   6922:                     my @options = qw(approval validate autolimit);
                   6923:                     my $optregex = join('|',@options);
                   6924:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   6925:                         $can_create = 1;
                   6926:                     }
                   6927:                 }
                   6928:             }
                   6929:         }
                   6930:         if ($can_create) {
                   6931:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   6932:                 unless (&allowed('ccc',$udom)) {
                   6933:                     return 'refused'; 
                   6934:                 }
1.1017    raeburn  6935:             }
                   6936:         } else {
                   6937:             return 'refused';
                   6938:         }
1.1028    raeburn  6939:     } elsif (!&allowed('ccc',$udom)) {
                   6940:         return 'refused';
1.84      www      6941:     }
1.1011    raeburn  6942: # --------------------------------------------------------------- Get Unique ID
                   6943:     my $uname;
                   6944:     if ($cnum =~ /^$match_courseid$/) {
                   6945:         my $chome=&homeserver($cnum,$udom,'true');
                   6946:         if (($chome eq '') || ($chome eq 'no_host')) {
                   6947:             $uname = $cnum;
                   6948:         } else {
1.1038    raeburn  6949:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  6950:         }
                   6951:     } else {
1.1038    raeburn  6952:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  6953:     }
                   6954:     return $uname if ($uname =~ /^error/);
                   6955: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  6956:     if (!defined($course_server)) {
                   6957:         if (defined(&domain($udom,'primary'))) {
                   6958:             $course_server = &domain($udom,'primary');
                   6959:         } else {
                   6960:             $course_server = $env{'user.home'}; 
                   6961:         }
                   6962:     }
                   6963:     my %host_servers =
                   6964:         &Apache::lonnet::get_servers($udom,'library');
                   6965:     unless ($host_servers{$course_server}) {
                   6966:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  6967:     }
1.84      www      6968: # ------------------------------------------------------------- Make the course
                   6969:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6970:                       $course_server);
1.84      www      6971:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  6972:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6973:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6974: 	return 'error: no such course';
                   6975:     }
1.271     www      6976: # ----------------------------------------------------------------- Course made
1.516     raeburn  6977: # log existence
1.1029    raeburn  6978:     my $now = time;
1.918     raeburn  6979:     my $newcourse = {
                   6980:                     $udom.'_'.$uname => {
1.921     raeburn  6981:                                      description => $description,
                   6982:                                      inst_code   => $inst_code,
                   6983:                                      owner       => $course_owner,
                   6984:                                      type        => $crstype,
1.1029    raeburn  6985:                                      creator     => $env{'user.name'}.':'.
                   6986:                                                     $env{'user.domain'},
                   6987:                                      created     => $now,
                   6988:                                      context     => $context,
1.918     raeburn  6989:                                                 },
                   6990:                     };
1.921     raeburn  6991:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6992: # set toplevel url
1.271     www      6993:     my $topurl=$url;
                   6994:     unless ($nonstandard) {
                   6995: # ------------------------------------------ For standard courses, make top url
                   6996:         my $mapurl=&clutter($url);
1.278     www      6997:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6998:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6999: <map>
                   7000: <resource id="1" type="start"></resource>
                   7001: <resource id="2" src="$mapurl"></resource>
                   7002: <resource id="3" type="finish"></resource>
                   7003: <link index="1" from="1" to="2"></link>
                   7004: <link index="2" from="2" to="3"></link>
                   7005: </map>
                   7006: ENDINITMAP
                   7007:         $topurl=&declutter(
1.638     albertel 7008:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7009:                           );
                   7010:     }
                   7011: # ----------------------------------------------------------- Write preferences
1.84      www      7012:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7013:                      ('description'              => $description,
                   7014:                       'url'                      => $topurl,
                   7015:                       'internal.creator'         => $env{'user.name'}.':'.
                   7016:                                                     $env{'user.domain'},
                   7017:                       'internal.created'         => $now,
                   7018:                       'internal.creationcontext' => $context)
                   7019:                     );
1.84      www      7020:     return '/'.$udom.'/'.$uname;
                   7021: }
                   7022: 
1.1011    raeburn  7023: # ------------------------------------------------------------------- Create ID
                   7024: sub generate_coursenum {
1.1038    raeburn  7025:     my ($udom,$crstype) = @_;
1.1011    raeburn  7026:     my $domdesc = &domain($udom);
                   7027:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7028:     my $first;
                   7029:     if ($crstype eq 'Community') {
                   7030:         $first = '0';
                   7031:     } else {
                   7032:         $first = int(1+rand(9)); 
                   7033:     } 
                   7034:     my $uname=$first.
1.1011    raeburn  7035:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7036:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7037:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7038: # ----------------------------------------------- Make sure that does not exist
                   7039:     my $uhome=&homeserver($uname,$udom,'true');
                   7040:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7041:         if ($crstype eq 'Community') {
                   7042:             $first = '0';
                   7043:         } else {
                   7044:             $first = int(1+rand(9));
                   7045:         }
                   7046:         $uname=$first.
1.1011    raeburn  7047:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7048:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7049:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7050:         $uhome=&homeserver($uname,$udom,'true');
                   7051:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7052:             return 'error: unable to generate unique course-ID';
                   7053:         }
                   7054:     }
                   7055:     return $uname;
                   7056: }
                   7057: 
1.813     albertel 7058: sub is_course {
                   7059:     my ($cdom,$cnum) = @_;
                   7060:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7061: 				undef,'.');
1.813     albertel 7062:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7063:         return 1;
                   7064:     }
                   7065:     return 0;
                   7066: }
                   7067: 
1.1015    raeburn  7068: sub store_userdata {
                   7069:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7070:     my $result;
1.1016    raeburn  7071:     if ($datakey ne '') {
1.1013    raeburn  7072:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7073:             if ($udom eq '' || $uname eq '') {
                   7074:                 $udom = $env{'user.domain'};
                   7075:                 $uname = $env{'user.name'};
                   7076:             }
                   7077:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7078:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7079:                 $result = 'error: no_host';
                   7080:             } else {
                   7081:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7082:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7083: 
                   7084:                 my $namevalue='';
                   7085:                 foreach my $key (keys(%{$storehash})) {
                   7086:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7087:                 }
                   7088:                 $namevalue=~s/\&$//;
                   7089:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7090:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7091:             }
                   7092:         } else {
                   7093:             $result = 'error: data to store was not a hash reference'; 
                   7094:         }
                   7095:     } else {
                   7096:         $result= 'error: invalid requestkey'; 
                   7097:     }
                   7098:     return $result;
                   7099: }
                   7100: 
1.21      www      7101: # ---------------------------------------------------------- Assign Custom Role
                   7102: 
                   7103: sub assigncustomrole {
1.957     raeburn  7104:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7105:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7106:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7107: }
                   7108: 
                   7109: # ----------------------------------------------------------------- Revoke Role
                   7110: 
                   7111: sub revokerole {
1.957     raeburn  7112:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7113:     my $now=time;
1.965     raeburn  7114:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7115: }
                   7116: 
                   7117: # ---------------------------------------------------------- Revoke Custom Role
                   7118: 
                   7119: sub revokecustomrole {
1.957     raeburn  7120:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7121:     my $now=time;
1.357     www      7122:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7123:            $deleteflag,$selfenroll,$context);
1.17      www      7124: }
                   7125: 
1.533     banghart 7126: # ------------------------------------------------------------ Disk usage
1.535     albertel 7127: sub diskusage {
1.955     raeburn  7128:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7129:     $directorypath =~ s/\/$//;
                   7130:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7131:                        .&escape($getpropath).':'.&escape($uname).':'
                   7132:                        .&escape($udom),homeserver($uname,$udom));
                   7133:     if ($listing eq 'unknown_cmd') {
                   7134:         if ($getpropath) {
                   7135:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7136:         }
                   7137:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7138:     }
1.514     albertel 7139:     return $listing;
1.512     banghart 7140: }
                   7141: 
1.566     banghart 7142: sub is_locked {
                   7143:     my ($file_name, $domain, $user) = @_;
                   7144:     my @check;
                   7145:     my $is_locked;
                   7146:     push @check, $file_name;
1.613     albertel 7147:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7148: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7149:     my ($tmp)=keys(%locked);
                   7150:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7151:     
1.566     banghart 7152:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7153:         $is_locked = 'false';
                   7154:         foreach my $entry (@{$locked{$file_name}}) {
                   7155:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7156:                $is_locked = 'true';
                   7157:                last;
1.745     raeburn  7158:            }
                   7159:        }
1.566     banghart 7160:     } else {
                   7161:         $is_locked = 'false';
                   7162:     }
                   7163: }
                   7164: 
1.759     albertel 7165: sub declutter_portfile {
                   7166:     my ($file) = @_;
1.833     albertel 7167:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7168:     return $file;
                   7169: }
                   7170: 
1.559     banghart 7171: # ------------------------------------------------------------- Mark as Read Only
                   7172: 
                   7173: sub mark_as_readonly {
                   7174:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7175:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7176:     my ($tmp)=keys(%current_permissions);
                   7177:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7178:     foreach my $file (@{$files}) {
1.759     albertel 7179: 	$file = &declutter_portfile($file);
1.561     banghart 7180:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7181:     }
1.613     albertel 7182:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7183:     return;
                   7184: }
                   7185: 
1.572     banghart 7186: # ------------------------------------------------------------Save Selected Files
                   7187: 
                   7188: sub save_selected_files {
                   7189:     my ($user, $path, @files) = @_;
                   7190:     my $filename = $user."savedfiles";
1.573     banghart 7191:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7192:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7193:     foreach my $file (@files) {
1.620     albertel 7194:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7195:     }
                   7196:     foreach my $file (@other_files) {
1.574     banghart 7197:         print (OUT $file."\n");
1.572     banghart 7198:     }
1.574     banghart 7199:     close (OUT);
1.572     banghart 7200:     return 'ok';
                   7201: }
                   7202: 
1.574     banghart 7203: sub clear_selected_files {
                   7204:     my ($user) = @_;
                   7205:     my $filename = $user."savedfiles";
                   7206:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7207:     print (OUT undef);
                   7208:     close (OUT);
                   7209:     return ("ok");    
                   7210: }
                   7211: 
1.572     banghart 7212: sub files_in_path {
                   7213:     my ($user, $path) = @_;
                   7214:     my $filename = $user."savedfiles";
                   7215:     my %return_files;
1.574     banghart 7216:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7217:     while (my $line_in = <IN>) {
1.574     banghart 7218:         chomp ($line_in);
                   7219:         my @paths_and_file = split (m!/!, $line_in);
                   7220:         my $file_part = pop (@paths_and_file);
                   7221:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7222:         $path_part.='/';
                   7223:         my $path_and_file = $path_part.$file_part;
                   7224:         if ($path_part eq $path) {
                   7225:             $return_files{$file_part}= 'selected';
                   7226:         }
                   7227:     }
1.574     banghart 7228:     close (IN);
                   7229:     return (\%return_files);
1.572     banghart 7230: }
                   7231: 
                   7232: # called in portfolio select mode, to show files selected NOT in current directory
                   7233: sub files_not_in_path {
                   7234:     my ($user, $path) = @_;
                   7235:     my $filename = $user."savedfiles";
                   7236:     my @return_files;
                   7237:     my $path_part;
1.800     albertel 7238:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7239:     while (my $line = <IN>) {
1.572     banghart 7240:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7241:         my @paths_and_file = split(m|/|, $line);
                   7242:         my $file_part = pop(@paths_and_file);
                   7243:         chomp($file_part);
                   7244:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7245:         $path_part .= '/';
                   7246:         my $path_and_file = $path_part.$file_part;
                   7247:         if ($path_part ne $path) {
1.800     albertel 7248:             push(@return_files, ($path_and_file));
1.572     banghart 7249:         }
                   7250:     }
1.800     albertel 7251:     close(OUT);
1.574     banghart 7252:     return (@return_files);
1.572     banghart 7253: }
                   7254: 
1.745     raeburn  7255: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7256: 
1.745     raeburn  7257: sub get_portfile_permissions {
                   7258:     my ($domain,$user) = @_;
1.613     albertel 7259:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7260:     my ($tmp)=keys(%current_permissions);
                   7261:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7262:     return \%current_permissions;
                   7263: }
                   7264: 
                   7265: #---------------------------------------------Get portfolio file access controls
                   7266: 
1.749     raeburn  7267: sub get_access_controls {
1.745     raeburn  7268:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7269:     my %access;
                   7270:     my $real_file = $file;
                   7271:     $file =~ s/\.meta$//;
1.745     raeburn  7272:     if (defined($file)) {
1.749     raeburn  7273:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7274:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7275:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7276:             }
                   7277:         }
1.745     raeburn  7278:     } else {
1.749     raeburn  7279:         foreach my $key (keys(%{$current_permissions})) {
                   7280:             if ($key =~ /\0accesscontrol$/) {
                   7281:                 if (defined($group)) {
                   7282:                     if ($key !~ m-^\Q$group\E/-) {
                   7283:                         next;
                   7284:                     }
                   7285:                 }
                   7286:                 my ($fullpath) = split(/\0/,$key);
                   7287:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7288:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7289:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7290:                     }
                   7291:                 }
                   7292:             }
                   7293:         }
                   7294:     }
                   7295:     return %access;
                   7296: }
                   7297: 
                   7298: sub modify_access_controls {
                   7299:     my ($file_name,$changes,$domain,$user)=@_;
                   7300:     my ($outcome,$deloutcome);
                   7301:     my %store_permissions;
                   7302:     my %new_values;
                   7303:     my %new_control;
                   7304:     my %translation;
                   7305:     my @deletions = ();
                   7306:     my $now = time;
                   7307:     if (exists($$changes{'activate'})) {
                   7308:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7309:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7310:             my $numnew = scalar(@newitems);
                   7311:             for (my $i=0; $i<$numnew; $i++) {
                   7312:                 my $newkey = $newitems[$i];
                   7313:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7314:                 if ($newkey =~ /^\d+:/) { 
                   7315:                     $newkey =~ s/^(\d+)/$newid/;
                   7316:                     $translation{$1} = $newid;
                   7317:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7318:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7319:                     $translation{$1} = $newid;
                   7320:                 }
1.749     raeburn  7321:                 $new_values{$file_name."\0".$newkey} = 
                   7322:                                           $$changes{'activate'}{$newitems[$i]};
                   7323:                 $new_control{$newkey} = $now;
                   7324:             }
                   7325:         }
                   7326:     }
                   7327:     my %todelete;
                   7328:     my %changed_items;
                   7329:     foreach my $action ('delete','update') {
                   7330:         if (exists($$changes{$action})) {
                   7331:             if (ref($$changes{$action}) eq 'HASH') {
                   7332:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7333:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7334:                     if ($action eq 'delete') { 
                   7335:                         $todelete{$itemnum} = 1;
                   7336:                     } else {
                   7337:                         $changed_items{$itemnum} = $key;
                   7338:                     }
                   7339:                 }
1.745     raeburn  7340:             }
                   7341:         }
1.749     raeburn  7342:     }
                   7343:     # get lock on access controls for file.
                   7344:     my $lockhash = {
                   7345:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7346:                                                        ':'.$env{'user.domain'},
                   7347:                    }; 
                   7348:     my $tries = 0;
                   7349:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7350:    
                   7351:     while (($gotlock ne 'ok') && $tries <3) {
                   7352:         $tries ++;
                   7353:         sleep 1;
                   7354:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7355:     }
                   7356:     if ($gotlock eq 'ok') {
                   7357:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7358:         my ($tmp)=keys(%curr_permissions);
                   7359:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7360:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7361:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7362:             if (ref($curr_controls) eq 'HASH') {
                   7363:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7364:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7365:                     if (defined($todelete{$itemnum})) {
                   7366:                         push(@deletions,$file_name."\0".$control_item);
                   7367:                     } else {
                   7368:                         if (defined($changed_items{$itemnum})) {
                   7369:                             $new_control{$changed_items{$itemnum}} = $now;
                   7370:                             push(@deletions,$file_name."\0".$control_item);
                   7371:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7372:                         } else {
                   7373:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7374:                         }
                   7375:                     }
1.745     raeburn  7376:                 }
                   7377:             }
                   7378:         }
1.970     raeburn  7379:         my ($group);
                   7380:         if (&is_course($domain,$user)) {
                   7381:             ($group,my $file) = split(/\//,$file_name,2);
                   7382:         }
1.749     raeburn  7383:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7384:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7385:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7386:         #  remove lock
                   7387:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7388:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7389:         my $sqlresult =
1.970     raeburn  7390:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7391:                                     $group);
1.749     raeburn  7392:     } else {
                   7393:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7394:     }
1.749     raeburn  7395:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7396: }
                   7397: 
1.827     raeburn  7398: sub make_public_indefinitely {
                   7399:     my ($requrl) = @_;
                   7400:     my $now = time;
                   7401:     my $action = 'activate';
                   7402:     my $aclnum = 0;
                   7403:     if (&is_portfolio_url($requrl)) {
                   7404:         my (undef,$udom,$unum,$file_name,$group) =
                   7405:             &parse_portfolio_url($requrl);
                   7406:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7407:         my %access_controls = &get_access_controls($current_perms,
                   7408:                                                    $group,$file_name);
                   7409:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7410:             my ($num,$scope,$end,$start) = 
                   7411:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7412:             if ($scope eq 'public') {
                   7413:                 if ($start <= $now && $end == 0) {
                   7414:                     $action = 'none';
                   7415:                 } else {
                   7416:                     $action = 'update';
                   7417:                     $aclnum = $num;
                   7418:                 }
                   7419:                 last;
                   7420:             }
                   7421:         }
                   7422:         if ($action eq 'none') {
                   7423:              return 'ok';
                   7424:         } else {
                   7425:             my %changes;
                   7426:             my $newend = 0;
                   7427:             my $newstart = $now;
                   7428:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7429:             $changes{$action}{$newkey} = {
                   7430:                 type => 'public',
                   7431:                 time => {
                   7432:                     start => $newstart,
                   7433:                     end   => $newend,
                   7434:                 },
                   7435:             };
                   7436:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7437:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7438:             return $outcome;
                   7439:         }
                   7440:     } else {
                   7441:         return 'invalid';
                   7442:     }
                   7443: }
                   7444: 
1.745     raeburn  7445: #------------------------------------------------------Get Marked as Read Only
                   7446: 
                   7447: sub get_marked_as_readonly {
                   7448:     my ($domain,$user,$what,$group) = @_;
                   7449:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7450:     my @readonly_files;
1.629     banghart 7451:     my $cmp1=$what;
                   7452:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7453:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7454:         if (defined($group)) {
                   7455:             if ($file_name !~ m-^\Q$group\E/-) {
                   7456:                 next;
                   7457:             }
                   7458:         }
1.561     banghart 7459:         if (ref($value) eq "ARRAY"){
                   7460:             foreach my $stored_what (@{$value}) {
1.629     banghart 7461:                 my $cmp2=$stored_what;
1.759     albertel 7462:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7463:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7464:                 }
1.629     banghart 7465:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7466:                     push(@readonly_files, $file_name);
1.745     raeburn  7467:                     last;
1.563     banghart 7468:                 } elsif (!defined($what)) {
                   7469:                     push(@readonly_files, $file_name);
1.745     raeburn  7470:                     last;
1.561     banghart 7471:                 }
                   7472:             }
1.745     raeburn  7473:         }
1.561     banghart 7474:     }
                   7475:     return @readonly_files;
                   7476: }
1.577     banghart 7477: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7478: 
1.577     banghart 7479: sub get_marked_as_readonly_hash {
1.745     raeburn  7480:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7481:     my %readonly_files;
1.745     raeburn  7482:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7483:         if (defined($group)) {
                   7484:             if ($file_name !~ m-^\Q$group\E/-) {
                   7485:                 next;
                   7486:             }
                   7487:         }
1.577     banghart 7488:         if (ref($value) eq "ARRAY"){
                   7489:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7490:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7491:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7492:                         if ($lock_descriptor eq 'graded') {
                   7493:                             $readonly_files{$file_name} = 'graded';
                   7494:                         } elsif ($lock_descriptor eq 'handback') {
                   7495:                             $readonly_files{$file_name} = 'handback';
                   7496:                         } else {
                   7497:                             if (!exists($readonly_files{$file_name})) {
                   7498:                                 $readonly_files{$file_name} = 'locked';
                   7499:                             }
                   7500:                         }
1.745     raeburn  7501:                     }
1.750     banghart 7502:                 } 
1.577     banghart 7503:             }
                   7504:         } 
                   7505:     }
                   7506:     return %readonly_files;
                   7507: }
1.559     banghart 7508: # ------------------------------------------------------------ Unmark as Read Only
                   7509: 
                   7510: sub unmark_as_readonly {
1.629     banghart 7511:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7512:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7513:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7514:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7515:     my $symb_crs = $what;
                   7516:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7517:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7518:     my ($tmp)=keys(%current_permissions);
                   7519:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7520:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7521:     foreach my $file (@readonly_files) {
1.759     albertel 7522: 	my $clean_file = &declutter_portfile($file);
                   7523: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7524: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7525:         my @new_locks;
                   7526:         my @del_keys;
                   7527:         if (ref($current_locks) eq "ARRAY"){
                   7528:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7529:                 my $compare=$locker;
1.749     raeburn  7530:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7531:                     $compare=join('',@{$locker});
1.746     raeburn  7532:                     if ($compare ne $symb_crs) {
                   7533:                         push(@new_locks, $locker);
                   7534:                     }
1.563     banghart 7535:                 }
                   7536:             }
1.650     albertel 7537:             if (scalar(@new_locks) > 0) {
1.563     banghart 7538:                 $current_permissions{$file} = \@new_locks;
                   7539:             } else {
                   7540:                 push(@del_keys, $file);
1.613     albertel 7541:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7542:                 delete($current_permissions{$file});
1.563     banghart 7543:             }
                   7544:         }
1.561     banghart 7545:     }
1.613     albertel 7546:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7547:     return;
                   7548: }
1.512     banghart 7549: 
1.17      www      7550: # ------------------------------------------------------------ Directory lister
                   7551: 
                   7552: sub dirlist {
1.955     raeburn  7553:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7554:     $uri=~s/^\///;
                   7555:     $uri=~s/\/$//;
1.253     stredwic 7556:     my ($udom, $uname);
1.955     raeburn  7557:     if ($getuserdir) {
1.253     stredwic 7558:         $udom = $userdomain;
                   7559:         $uname = $username;
1.955     raeburn  7560:     } else {
                   7561:         (undef,$udom,$uname)=split(/\//,$uri);
                   7562:         if(defined($userdomain)) {
                   7563:             $udom = $userdomain;
                   7564:         }
                   7565:         if(defined($username)) {
                   7566:             $uname = $username;
                   7567:         }
1.253     stredwic 7568:     }
1.955     raeburn  7569:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7570: 
1.955     raeburn  7571:     $dirRoot = $perlvar{'lonDocRoot'};
                   7572:     if (defined($getpropath)) {
                   7573:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7574:         $dirRoot =~ s/\/$//;
1.955     raeburn  7575:     } elsif (defined($getuserdir)) {
                   7576:         my $subdir=$uname.'__';
                   7577:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7578:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7579:                    ."/$udom/$subdir/$uname";
                   7580:     } elsif (defined($alternateRoot)) {
                   7581:         $dirRoot = $alternateRoot;
1.751     banghart 7582:     }
1.253     stredwic 7583: 
                   7584:     if($udom) {
                   7585:         if($uname) {
1.955     raeburn  7586:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7587:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7588:                               .':'.&escape($uname).':'.&escape($udom),
                   7589:                               &homeserver($uname,$udom));
                   7590:             if ($listing eq 'unknown_cmd') {
                   7591:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7592:                                   &homeserver($uname,$udom));
                   7593:             } else {
                   7594:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7595:             }
1.605     matthew  7596:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7597:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7598: 				  &homeserver($uname,$udom));
1.605     matthew  7599:                 @listing_results = split(/:/,$listing);
                   7600:             } else {
                   7601:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7602:             }
                   7603:             return @listing_results;
1.955     raeburn  7604:         } elsif(!$alternateRoot) {
1.800     albertel 7605:             my %allusers;
1.841     albertel 7606: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7607:  	    foreach my $tryserver (keys(%servers)) {
                   7608:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7609:                                   &escape($udom),$tryserver);
                   7610:                 if ($listing eq 'unknown_cmd') {
                   7611: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7612: 				      $udom, $tryserver);
                   7613:                 } else {
                   7614:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7615:                 }
1.841     albertel 7616: 		if ($listing eq 'unknown_cmd') {
                   7617: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7618: 				      $udom, $tryserver);
                   7619: 		    @listing_results = split(/:/,$listing);
                   7620: 		} else {
                   7621: 		    @listing_results =
                   7622: 			map { &unescape($_); } split(/:/,$listing);
                   7623: 		}
                   7624: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7625: 		    $listing_results[0] ne 'empty'       &&
                   7626: 		    $listing_results[0] ne 'con_lost') {
                   7627: 		    foreach my $line (@listing_results) {
                   7628: 			my ($entry) = split(/&/,$line,2);
                   7629: 			$allusers{$entry} = 1;
                   7630: 		    }
                   7631: 		}
1.253     stredwic 7632:             }
                   7633:             my $alluserstr='';
1.800     albertel 7634:             foreach my $user (sort(keys(%allusers))) {
                   7635:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7636:             }
                   7637:             $alluserstr=~s/:$//;
                   7638:             return split(/:/,$alluserstr);
                   7639:         } else {
1.800     albertel 7640:             return ('missing user name');
1.253     stredwic 7641:         }
1.955     raeburn  7642:     } elsif(!defined($getpropath)) {
1.841     albertel 7643:         my @all_domains = sort(&all_domains());
1.955     raeburn  7644:         foreach my $domain (@all_domains) {
                   7645:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7646:         }
                   7647:         return @all_domains;
                   7648:     } else {
1.800     albertel 7649:         return ('missing domain');
1.275     stredwic 7650:     }
                   7651: }
                   7652: 
                   7653: # --------------------------------------------- GetFileTimestamp
                   7654: # This function utilizes dirlist and returns the date stamp for
                   7655: # when it was last modified.  It will also return an error of -1
                   7656: # if an error occurs
                   7657: 
                   7658: sub GetFileTimestamp {
1.955     raeburn  7659:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7660:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7661:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7662:     my ($fileStat) = 
                   7663:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7664:                                  undef,$getuserdir);
1.275     stredwic 7665:     my @stats = split('&', $fileStat);
                   7666:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7667:         # @stats contains first the filename, then the stat output
                   7668:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7669:     } else {
                   7670:         return -1;
1.253     stredwic 7671:     }
1.26      www      7672: }
                   7673: 
1.712     albertel 7674: sub stat_file {
                   7675:     my ($uri) = @_;
1.787     albertel 7676:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7677: 
1.955     raeburn  7678:     my ($udom,$uname,$file);
1.712     albertel 7679:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7680: 	($udom,$uname,$file) =
1.811     albertel 7681: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7682: 	$file = 'userfiles/'.$file;
                   7683:     }
                   7684:     if ($uri =~ m-^/res/-) {
                   7685: 	($udom,$uname) = 
1.807     albertel 7686: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7687: 	$file = $uri;
                   7688:     }
                   7689: 
                   7690:     if (!$udom || !$uname || !$file) {
                   7691: 	# unable to handle the uri
                   7692: 	return ();
                   7693:     }
1.956     raeburn  7694:     my $getpropath;
                   7695:     if ($file =~ /^userfiles\//) {
                   7696:         $getpropath = 1;
                   7697:     }
1.955     raeburn  7698:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7699:     my @stats = split('&', $result);
1.721     banghart 7700:     
1.712     albertel 7701:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7702: 	shift(@stats); #filename is first
                   7703: 	return @stats;
                   7704:     }
                   7705:     return ();
                   7706: }
                   7707: 
1.26      www      7708: # -------------------------------------------------------- Value of a Condition
                   7709: 
1.713     albertel 7710: # gets the value of a specific preevaluated condition
                   7711: #    stored in the string  $env{user.state.<cid>}
                   7712: # or looks up a condition reference in the bighash and if if hasn't
                   7713: # already been evaluated recurses into docondval to get the value of
                   7714: # the condition, then memoizing it to 
                   7715: #   $env{user.state.<cid>.<condition>}
1.40      www      7716: sub directcondval {
                   7717:     my $number=shift;
1.620     albertel 7718:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7719: 	&Apache::lonuserstate::evalstate();
                   7720:     }
1.713     albertel 7721:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7722: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7723:     } elsif ($number =~ /^_/) {
                   7724: 	my $sub_condition;
                   7725: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7726: 		&GDBM_READER(),0640)) {
                   7727: 	    $sub_condition=$bighash{'conditions'.$number};
                   7728: 	    untie(%bighash);
                   7729: 	}
                   7730: 	my $value = &docondval($sub_condition);
1.949     raeburn  7731: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7732: 	return $value;
                   7733:     }
1.620     albertel 7734:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7735:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7736:     } else {
                   7737:        return 2;
                   7738:     }
                   7739: }
                   7740: 
1.713     albertel 7741: # get the collection of conditions for this resource
1.26      www      7742: sub condval {
                   7743:     my $condidx=shift;
1.54      www      7744:     my $allpathcond='';
1.713     albertel 7745:     foreach my $cond (split(/\|/,$condidx)) {
                   7746: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7747: 	    $allpathcond.=
                   7748: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7749: 	}
1.191     harris41 7750:     }
1.54      www      7751:     $allpathcond=~s/\|$//;
1.713     albertel 7752:     return &docondval($allpathcond);
                   7753: }
                   7754: 
                   7755: #evaluates an expression of conditions
                   7756: sub docondval {
                   7757:     my ($allpathcond) = @_;
                   7758:     my $result=0;
                   7759:     if ($env{'request.course.id'}
                   7760: 	&& defined($allpathcond)) {
                   7761: 	my $operand='|';
                   7762: 	my @stack;
                   7763: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7764: 	    if ($chunk eq '(') {
                   7765: 		push @stack,($operand,$result);
                   7766: 	    } elsif ($chunk eq ')') {
                   7767: 		my $before=pop @stack;
                   7768: 		if (pop @stack eq '&') {
                   7769: 		    $result=$result>$before?$before:$result;
                   7770: 		} else {
                   7771: 		    $result=$result>$before?$result:$before;
                   7772: 		}
                   7773: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7774: 		$operand=$chunk;
                   7775: 	    } else {
                   7776: 		my $new=directcondval($chunk);
                   7777: 		if ($operand eq '&') {
                   7778: 		    $result=$result>$new?$new:$result;
                   7779: 		} else {
                   7780: 		    $result=$result>$new?$result:$new;
                   7781: 		}
                   7782: 	    }
                   7783: 	}
1.26      www      7784:     }
                   7785:     return $result;
1.421     albertel 7786: }
                   7787: 
                   7788: # ---------------------------------------------------- Devalidate courseresdata
                   7789: 
                   7790: sub devalidatecourseresdata {
                   7791:     my ($coursenum,$coursedomain)=@_;
                   7792:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7793:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7794: }
                   7795: 
1.763     www      7796: 
1.200     www      7797: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7798: #
                   7799: #  Parameters:
                   7800: #      $coursenum    - Number of the course.
                   7801: #      $coursedomain - Domain at which the course was created.
                   7802: #  Returns:
                   7803: #     A hash of the course parameters along (I think) with timestamps
                   7804: #     and version info.
1.877     foxr     7805: 
1.624     albertel 7806: sub get_courseresdata {
                   7807:     my ($coursenum,$coursedomain)=@_;
1.200     www      7808:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7809:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7810:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7811:     my %dumpreply;
1.417     albertel 7812:     unless (defined($cached)) {
1.624     albertel 7813: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7814: 	$result=\%dumpreply;
1.251     albertel 7815: 	my ($tmp) = keys(%dumpreply);
                   7816: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7817: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7818: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7819: 	    return $tmp;
1.416     albertel 7820: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7821: 	    $result=undef;
1.599     albertel 7822: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7823: 	}
                   7824:     }
1.624     albertel 7825:     return $result;
                   7826: }
                   7827: 
1.633     albertel 7828: sub devalidateuserresdata {
                   7829:     my ($uname,$udom)=@_;
                   7830:     my $hashid="$udom:$uname";
                   7831:     &devalidate_cache_new('userres',$hashid);
                   7832: }
                   7833: 
1.624     albertel 7834: sub get_userresdata {
                   7835:     my ($uname,$udom)=@_;
                   7836:     #most student don\'t have any data set, check if there is some data
                   7837:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7838: 
                   7839:     my $hashid="$udom:$uname";
                   7840:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7841:     if (!defined($cached)) {
                   7842: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7843: 	$result=\%resourcedata;
                   7844: 	&do_cache_new('userres',$hashid,$result,600);
                   7845:     }
                   7846:     my ($tmp)=keys(%$result);
                   7847:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7848: 	return $result;
                   7849:     }
                   7850:     #error 2 occurs when the .db doesn't exist
                   7851:     if ($tmp!~/error: 2 /) {
1.672     albertel 7852: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7853: 		 " Trying to get resource data for ".
                   7854: 		 $uname." at ".$udom.": ".
                   7855: 		 $tmp."</font>");
                   7856:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7857: 	#&EXT_cache_set($udom,$uname);
                   7858: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7859: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7860:     }
                   7861:     return $tmp;
                   7862: }
1.879     foxr     7863: #----------------------------------------------- resdata - return resource data
                   7864: #  Purpose:
                   7865: #    Return resource data for either users or for a course.
                   7866: #  Parameters:
                   7867: #     $name      - Course/user name.
                   7868: #     $domain    - Name of the domain the user/course is registered on.
                   7869: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7870: #     @which     - Array of names of resources desired.
                   7871: #  Returns:
                   7872: #     The value of the first reasource in @which that is found in the
                   7873: #     resource hash.
                   7874: #  Exceptional Conditions:
                   7875: #     If the $type passed in is not valid (not the string 'course' or 
                   7876: #     'user', an undefined  reference is returned.
                   7877: #     If none of the resources are found, an undef is returned
1.624     albertel 7878: sub resdata {
                   7879:     my ($name,$domain,$type,@which)=@_;
                   7880:     my $result;
                   7881:     if ($type eq 'course') {
                   7882: 	$result=&get_courseresdata($name,$domain);
                   7883:     } elsif ($type eq 'user') {
                   7884: 	$result=&get_userresdata($name,$domain);
                   7885:     }
                   7886:     if (!ref($result)) { return $result; }    
1.251     albertel 7887:     foreach my $item (@which) {
1.927     albertel 7888: 	if (defined($result->{$item->[0]})) {
                   7889: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7890: 	}
1.250     albertel 7891:     }
1.291     albertel 7892:     return undef;
1.200     www      7893: }
                   7894: 
1.379     matthew  7895: #
                   7896: # EXT resource caching routines
                   7897: #
                   7898: 
                   7899: sub clear_EXT_cache_status {
1.383     albertel 7900:     &delenv('cache.EXT.');
1.379     matthew  7901: }
                   7902: 
                   7903: sub EXT_cache_status {
                   7904:     my ($target_domain,$target_user) = @_;
1.383     albertel 7905:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7906:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7907:         # We know already the user has no data
                   7908:         return 1;
                   7909:     } else {
                   7910:         return 0;
                   7911:     }
                   7912: }
                   7913: 
                   7914: sub EXT_cache_set {
                   7915:     my ($target_domain,$target_user) = @_;
1.383     albertel 7916:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7917:     #&appenv({$cachename => time});
1.379     matthew  7918: }
                   7919: 
1.28      www      7920: # --------------------------------------------------------- Value of a Variable
1.58      www      7921: sub EXT {
1.715     albertel 7922: 
1.395     albertel 7923:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7924:     unless ($varname) { return ''; }
1.218     albertel 7925:     #get real user name/domain, courseid and symb
                   7926:     my $courseid;
1.359     albertel 7927:     my $publicuser;
1.427     www      7928:     if ($symbparm) {
                   7929: 	$symbparm=&get_symb_from_alias($symbparm);
                   7930:     }
1.218     albertel 7931:     if (!($uname && $udom)) {
1.790     albertel 7932:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7933:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7934:     } else {
1.620     albertel 7935: 	$courseid=$env{'request.course.id'};
1.218     albertel 7936:     }
1.48      www      7937:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7938:     my $rest;
1.320     albertel 7939:     if (defined($therest[0])) {
1.48      www      7940:        $rest=join('.',@therest);
                   7941:     } else {
                   7942:        $rest='';
                   7943:     }
1.320     albertel 7944: 
1.57      www      7945:     my $qualifierrest=$qualifier;
                   7946:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7947:     my $spacequalifierrest=$space;
                   7948:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7949:     if ($realm eq 'user') {
1.48      www      7950: # --------------------------------------------------------------- user.resource
                   7951: 	if ($space eq 'resource') {
1.651     albertel 7952: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7953: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7954: 		 &&
1.744     albertel 7955: 		 ($symbparm eq &symbread()) ) {	
                   7956: 		# if we are in the middle of processing the resource the
                   7957: 		# get the value we are planning on committing
                   7958:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7959:                     return $Apache::lonhomework::results{$qualifierrest};
                   7960:                 } else {
                   7961:                     return $Apache::lonhomework::history{$qualifierrest};
                   7962:                 }
1.335     albertel 7963: 	    } else {
1.359     albertel 7964: 		my %restored;
1.620     albertel 7965: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7966: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7967: 		} else {
                   7968: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7969: 		}
1.335     albertel 7970: 		return $restored{$qualifierrest};
                   7971: 	    }
1.48      www      7972: # ----------------------------------------------------------------- user.access
                   7973:         } elsif ($space eq 'access') {
1.218     albertel 7974: 	    # FIXME - not supporting calls for a specific user
1.48      www      7975:             return &allowed($qualifier,$rest);
                   7976: # ------------------------------------------ user.preferences, user.environment
                   7977:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7978: 	    if (($uname eq $env{'user.name'}) &&
                   7979: 		($udom eq $env{'user.domain'})) {
                   7980: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7981: 	    } else {
1.359     albertel 7982: 		my %returnhash;
                   7983: 		if (!$publicuser) {
                   7984: 		    %returnhash=&userenvironment($udom,$uname,
                   7985: 						 $qualifierrest);
                   7986: 		}
1.218     albertel 7987: 		return $returnhash{$qualifierrest};
                   7988: 	    }
1.48      www      7989: # ----------------------------------------------------------------- user.course
                   7990:         } elsif ($space eq 'course') {
1.218     albertel 7991: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7992:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7993: # ------------------------------------------------------------------- user.role
                   7994:         } elsif ($space eq 'role') {
1.218     albertel 7995: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7996:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7997:             if ($qualifier eq 'value') {
                   7998: 		return $role;
                   7999:             } elsif ($qualifier eq 'extent') {
                   8000:                 return $where;
                   8001:             }
                   8002: # ----------------------------------------------------------------- user.domain
                   8003:         } elsif ($space eq 'domain') {
1.218     albertel 8004:             return $udom;
1.48      www      8005: # ------------------------------------------------------------------- user.name
                   8006:         } elsif ($space eq 'name') {
1.218     albertel 8007:             return $uname;
1.48      www      8008: # ---------------------------------------------------- Any other user namespace
1.29      www      8009:         } else {
1.359     albertel 8010: 	    my %reply;
                   8011: 	    if (!$publicuser) {
                   8012: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8013: 	    }
                   8014: 	    return $reply{$qualifierrest};
1.48      www      8015:         }
1.236     www      8016:     } elsif ($realm eq 'query') {
                   8017: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8018:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8019: 						[$spacequalifierrest]);
1.620     albertel 8020: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8021:    } elsif ($realm eq 'request') {
1.48      www      8022: # ------------------------------------------------------------- request.browser
                   8023:         if ($space eq 'browser') {
1.430     www      8024: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8025: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8026: 		    return 1;
                   8027: 		} else {
                   8028: 		    return 0;
                   8029: 		}
                   8030: 	    } else {
1.620     albertel 8031: 		return $env{'browser.'.$qualifier};
1.430     www      8032: 	    }
1.57      www      8033: # ------------------------------------------------------------ request.filename
                   8034:         } else {
1.620     albertel 8035:             return $env{'request.'.$spacequalifierrest};
1.29      www      8036:         }
1.28      www      8037:     } elsif ($realm eq 'course') {
1.48      www      8038: # ---------------------------------------------------------- course.description
1.620     albertel 8039:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8040:     } elsif ($realm eq 'resource') {
1.165     www      8041: 
1.620     albertel 8042: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8043: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8044: 	}
1.693     albertel 8045: 
                   8046: 	if ($space eq 'title') {
                   8047: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8048: 	    return &gettitle($symbparm);
                   8049: 	}
                   8050: 	
                   8051: 	if ($space eq 'map') {
                   8052: 	    my ($map) = &decode_symb($symbparm);
                   8053: 	    return &symbread($map);
                   8054: 	}
1.905     albertel 8055: 	if ($space eq 'filename') {
                   8056: 	    if ($symbparm) {
                   8057: 		return &clutter((&decode_symb($symbparm))[2]);
                   8058: 	    }
                   8059: 	    return &hreflocation('',$env{'request.filename'});
                   8060: 	}
1.693     albertel 8061: 
                   8062: 	my ($section, $group, @groups);
1.593     albertel 8063: 	my ($courselevelm,$courselevel);
1.539     albertel 8064: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8065: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8066: 
1.218     albertel 8067: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8068: 
1.60      www      8069: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8070: 	    my $symbp=$symbparm;
1.735     albertel 8071: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8072: 
                   8073: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8074: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8075: 
1.620     albertel 8076: 	    if (($env{'user.name'} eq $uname) &&
                   8077: 		($env{'user.domain'} eq $udom)) {
                   8078: 		$section=$env{'request.course.sec'};
1.733     raeburn  8079:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8080:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8081: 	    } else {
1.539     albertel 8082: 		if (! defined($usection)) {
1.551     albertel 8083: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8084: 		} else {
                   8085: 		    $section = $usection;
                   8086: 		}
1.733     raeburn  8087:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8088: 	    }
                   8089: 
                   8090: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8091: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8092: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8093: 
1.593     albertel 8094: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8095: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8096: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8097: 
1.60      www      8098: # ----------------------------------------------------------- first, check user
1.624     albertel 8099: 
                   8100: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8101: 				       ([$courselevelr,'resource'],
                   8102: 					[$courselevelm,'map'     ],
                   8103: 					[$courselevel, 'course'  ]));
1.931     albertel 8104: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8105: 
1.594     albertel 8106: # ------------------------------------------------ second, check some of course
1.684     raeburn  8107:             my $coursereply;
1.691     raeburn  8108:             if (@groups > 0) {
                   8109:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8110:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8111:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8112:             }
1.96      www      8113: 
1.684     raeburn  8114: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8115: 				  $env{'course.'.$courseid.'.domain'},
                   8116: 				  'course',
                   8117: 				  ([$seclevelr,   'resource'],
                   8118: 				   [$seclevelm,   'map'     ],
                   8119: 				   [$seclevel,    'course'  ],
                   8120: 				   [$courselevelr,'resource']));
                   8121: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8122: 
1.60      www      8123: # ------------------------------------------------------ third, check map parms
1.218     albertel 8124: 	    my %parmhash=();
                   8125: 	    my $thisparm='';
                   8126: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8127: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8128: 		    &GDBM_READER(),0640)) {
1.218     albertel 8129: 		$thisparm=$parmhash{$symbparm};
                   8130: 		untie(%parmhash);
                   8131: 	    }
1.927     albertel 8132: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8133: 	}
1.594     albertel 8134: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8135: 
1.218     albertel 8136: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8137: 	my $filename;
                   8138: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8139: 	if ($symbparm) {
1.409     www      8140: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8141: 	} else {
1.620     albertel 8142: 	    $filename=$env{'request.filename'};
1.282     albertel 8143: 	}
                   8144: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8145: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8146: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8147: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8148: 
1.927     albertel 8149: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8150: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8151: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8152: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8153: 				     $env{'course.'.$courseid.'.domain'},
                   8154: 				     'course',
1.927     albertel 8155: 				     ([$courselevelm,'map'   ],
                   8156: 				      [$courselevel, 'course']));
                   8157: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8158: 	}
1.145     www      8159: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8160: 	unless ($space eq '0') {
1.336     albertel 8161: 	    my @parts=split(/_/,$space);
                   8162: 	    my $id=pop(@parts);
                   8163: 	    my $part=join('_',@parts);
                   8164: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8165: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8166: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8167: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8168: 	}
1.395     albertel 8169: 	if ($recurse) { return undef; }
                   8170: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8171: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8172: # ---------------------------------------------------- Any other user namespace
                   8173:     } elsif ($realm eq 'environment') {
                   8174: # ----------------------------------------------------------------- environment
1.620     albertel 8175: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8176: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8177: 	} else {
1.770     albertel 8178: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8179: 		return '';
                   8180: 	    }
1.219     albertel 8181: 	    my %returnhash=&userenvironment($udom,$uname,
                   8182: 					    $spacequalifierrest);
                   8183: 	    return $returnhash{$spacequalifierrest};
                   8184: 	}
1.28      www      8185:     } elsif ($realm eq 'system') {
1.48      www      8186: # ----------------------------------------------------------------- system.time
                   8187: 	if ($space eq 'time') {
                   8188: 	    return time;
                   8189:         }
1.696     albertel 8190:     } elsif ($realm eq 'server') {
                   8191: # ----------------------------------------------------------------- system.time
                   8192: 	if ($space eq 'name') {
                   8193: 	    return $ENV{'SERVER_NAME'};
                   8194:         }
1.28      www      8195:     }
1.48      www      8196:     return '';
1.61      www      8197: }
                   8198: 
1.927     albertel 8199: sub get_reply {
                   8200:     my ($reply_value) = @_;
1.940     raeburn  8201:     if (ref($reply_value) eq 'ARRAY') {
                   8202:         if (wantarray) {
                   8203: 	    return @$reply_value;
                   8204:         }
                   8205:         return $reply_value->[0];
                   8206:     } else {
                   8207:         return $reply_value;
1.927     albertel 8208:     }
                   8209: }
                   8210: 
1.691     raeburn  8211: sub check_group_parms {
                   8212:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8213:     my @groupitems = ();
                   8214:     my $resultitem;
1.927     albertel 8215:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8216:     foreach my $group (@{$groups}) {
                   8217:         foreach my $level (@levels) {
1.927     albertel 8218:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8219:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8220:         }
                   8221:     }
                   8222:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8223:                             $env{'course.'.$courseid.'.domain'},
                   8224:                                      'course',@groupitems);
                   8225:     return $coursereply;
                   8226: }
                   8227: 
                   8228: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8229:     my ($courseid,@groups) = @_;
                   8230:     @groups = sort(@groups);
1.691     raeburn  8231:     return @groups;
                   8232: }
                   8233: 
1.395     albertel 8234: sub packages_tab_default {
                   8235:     my ($uri,$varname)=@_;
                   8236:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8237: 
                   8238:     my (@extension,@specifics,$do_default);
                   8239:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8240: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8241: 	if ($pack_type eq 'default') {
                   8242: 	    $do_default=1;
                   8243: 	} elsif ($pack_type eq 'extension') {
                   8244: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8245: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8246: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8247: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8248: 	}
                   8249:     }
                   8250:     # first look for a package that matches the requested part id
                   8251:     foreach my $package (@specifics) {
                   8252: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8253: 	next if ($pack_part ne $part);
                   8254: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8255: 	    return $packagetab{"$pack_type&$name&default"};
                   8256: 	}
                   8257:     }
                   8258:     # look for any possible matching non extension_ package
                   8259:     foreach my $package (@specifics) {
                   8260: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8261: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8262: 	    return $packagetab{"$pack_type&$name&default"};
                   8263: 	}
1.585     albertel 8264: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8265: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8266: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8267: 	}
                   8268:     }
1.738     albertel 8269:     # look for any posible extension_ match
                   8270:     foreach my $package (@extension) {
                   8271: 	my ($package,$pack_type)=@{$package};
                   8272: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8273: 	    return $packagetab{"$pack_type&$name&default"};
                   8274: 	}
                   8275: 	if (defined($packagetab{$package."&$name&default"})) {
                   8276: 	    return $packagetab{$package."&$name&default"};
                   8277: 	}
                   8278:     }
                   8279:     # look for a global default setting
                   8280:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8281: 	return $packagetab{"default&$name&default"};
                   8282:     }
1.395     albertel 8283:     return undef;
                   8284: }
                   8285: 
1.334     albertel 8286: sub add_prefix_and_part {
                   8287:     my ($prefix,$part)=@_;
                   8288:     my $keyroot;
                   8289:     if (defined($prefix) && $prefix !~ /^__/) {
                   8290: 	# prefix that has a part already
                   8291: 	$keyroot=$prefix;
                   8292:     } elsif (defined($prefix)) {
                   8293: 	# prefix that is missing a part
                   8294: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8295:     } else {
                   8296: 	# no prefix at all
                   8297: 	if (defined($part)) { $keyroot='_'.$part; }
                   8298:     }
                   8299:     return $keyroot;
                   8300: }
                   8301: 
1.71      www      8302: # ---------------------------------------------------------------- Get metadata
                   8303: 
1.599     albertel 8304: my %metaentry;
1.1070    www      8305: my %importedpartids;
1.71      www      8306: sub metadata {
1.176     www      8307:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8308:     $uri=&declutter($uri);
1.288     albertel 8309:     # if it is a non metadata possible uri return quickly
1.529     albertel 8310:     if (($uri eq '') || 
                   8311: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8312: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8313:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8314: 	return undef;
                   8315:     }
                   8316:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8317: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8318: 	return undef;
1.288     albertel 8319:     }
1.73      www      8320:     my $filename=$uri;
                   8321:     $uri=~s/\.meta$//;
1.172     www      8322: #
                   8323: # Is the metadata already cached?
1.177     www      8324: # Look at timestamp of caching
1.172     www      8325: # Everything is cached by the main uri, libraries are never directly cached
                   8326: #
1.428     albertel 8327:     if (!defined($liburi)) {
1.599     albertel 8328: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8329: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8330:     }
                   8331:     {
1.1069    www      8332: # Imported parts would go here
1.1070    www      8333:         my %importedids=();
                   8334:         my @origfileimportpartids=();
1.1069    www      8335:         my $importedparts=0;
1.172     www      8336: #
                   8337: # Is this a recursive call for a library?
                   8338: #
1.599     albertel 8339: #	if (! exists($metacache{$uri})) {
                   8340: #	    $metacache{$uri}={};
                   8341: #	}
1.924     albertel 8342: 	my $cachetime = 60*60;
1.171     www      8343:         if ($liburi) {
                   8344: 	    $liburi=&declutter($liburi);
                   8345:             $filename=$liburi;
1.401     bowersj2 8346:         } else {
1.599     albertel 8347: 	    &devalidate_cache_new('meta',$uri);
                   8348: 	    undef(%metaentry);
1.401     bowersj2 8349: 	}
1.140     www      8350:         my %metathesekeys=();
1.73      www      8351:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8352: 	my $metastring;
1.924     albertel 8353: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8354: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8355: 	    $metastring = 
1.929     albertel 8356: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8357: 					  ('grade_target' => 'meta'));
                   8358: 	    $cachetime = 1; # only want this cached in the child not long term
                   8359: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8360: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8361: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8362: 	    $metastring=&getfile($file);
1.489     albertel 8363: 	}
1.208     albertel 8364:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8365:         my $token;
1.140     www      8366:         undef %metathesekeys;
1.71      www      8367:         while ($token=$parser->get_token) {
1.339     albertel 8368: 	    if ($token->[0] eq 'S') {
                   8369: 		if (defined($token->[2]->{'package'})) {
1.172     www      8370: #
                   8371: # This is a package - get package info
                   8372: #
1.339     albertel 8373: 		    my $package=$token->[2]->{'package'};
                   8374: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8375: 		    if (defined($token->[2]->{'id'})) { 
                   8376: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8377: 		    }
1.599     albertel 8378: 		    if ($metaentry{':packages'}) {
                   8379: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8380: 		    } else {
1.599     albertel 8381: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8382: 		    }
1.736     albertel 8383: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8384: 			my $part=$keyroot;
                   8385: 			$part=~s/^\_//;
1.736     albertel 8386: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8387: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8388: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8389: 			    # ignore package.tab specified default values
                   8390:                             # here &package_tab_default() will fetch those
                   8391: 			    if ($subp eq 'default') { next; }
1.736     albertel 8392: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8393: 			    my $unikey;
                   8394: 			    if ($pack =~ /_0$/) {
                   8395: 				$unikey='parameter_0_'.$name;
                   8396: 				$part=0;
                   8397: 			    } else {
                   8398: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8399: 			    }
1.339     albertel 8400: 			    if ($subp eq 'display') {
                   8401: 				$value.=' [Part: '.$part.']';
                   8402: 			    }
1.599     albertel 8403: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8404: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8405: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8406: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8407: 			    }
1.599     albertel 8408: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8409: 				$metaentry{':'.$unikey}=
                   8410: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8411: 			    }
1.339     albertel 8412: 			}
                   8413: 		    }
                   8414: 		} else {
1.172     www      8415: #
                   8416: # This is not a package - some other kind of start tag
1.339     albertel 8417: #
                   8418: 		    my $entry=$token->[1];
1.1068    www      8419: 		    my $unikey='';
1.175     www      8420: 
1.339     albertel 8421: 		    if ($entry eq 'import') {
1.175     www      8422: #
                   8423: # Importing a library here
1.339     albertel 8424: #
1.1067    www      8425:                         my $location=$parser->get_text('/import');
                   8426:                         my $dir=$filename;
                   8427:                         $dir=~s|[^/]*$||;
                   8428:                         $location=&filelocation($dir,$location);
1.1069    www      8429:                        
1.1068    www      8430:                         my $importmode=$token->[2]->{'importmode'};
                   8431:                         if ($importmode eq 'problem') {
1.1069    www      8432: # Import as problem/response
1.1068    www      8433:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8434:                         } elsif ($importmode eq 'part') {
                   8435: # Import as part(s)
1.1069    www      8436:                            $importedparts=1;
                   8437: # We need to get the original file and the imported file to get the part order correct
                   8438: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8439: # Load and inspect original file
1.1070    www      8440:                            if ($#origfileimportpartids<0) {
                   8441:                               undef(%importedpartids);
                   8442:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8443:                               my $origfile=&getfile($origfilelocation);
                   8444:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8445:                            }
                   8446: 
1.1069    www      8447: # Load and inspect imported file
                   8448:                            my $impfile=&getfile($location);
                   8449:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8450:                            if ($#impfilepartids>=0) {
                   8451: # This problem had parts
1.1070    www      8452:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8453:                            } else {
                   8454: # Importing by turning a single problem into a problem part
                   8455: # It gets the import-tags ID as part-ID
                   8456:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8457:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8458:                            }
1.1068    www      8459:                         } else {
                   8460: # Normal import
                   8461:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8462:                            if (defined($token->[2]->{'id'})) {
                   8463:                               $unikey.='_'.$token->[2]->{'id'};
                   8464:                            }
1.1067    www      8465:                         }
                   8466: 
1.339     albertel 8467: 			if ($depthcount<20) {
1.736     albertel 8468: 			    my $metadata = 
                   8469: 				&metadata($uri,'keys', $location,$unikey,
                   8470: 					  $depthcount+1);
                   8471: 			    foreach my $meta (split(',',$metadata)) {
                   8472: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8473: 				$metathesekeys{$meta}=1;
1.339     albertel 8474: 			    }
1.1068    www      8475: 			
                   8476:                         }
1.1067    www      8477: 		    } else {
                   8478: #
                   8479: # Not importing, some other kind of non-package, non-library start tag
                   8480: # 
                   8481:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8482:                         if (defined($token->[2]->{'id'})) {
                   8483:                             $unikey.='_'.$token->[2]->{'id'};
                   8484:                         }
1.339     albertel 8485: 			if (defined($token->[2]->{'name'})) { 
                   8486: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8487: 			}
                   8488: 			$metathesekeys{$unikey}=1;
1.736     albertel 8489: 			foreach my $param (@{$token->[3]}) {
                   8490: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8491: 				$token->[2]->{$param};
1.339     albertel 8492: 			}
                   8493: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8494: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8495: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8496: 		 # only ws inside the tag, and not in default, so use default
                   8497: 		 # as value
1.599     albertel 8498: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8499: 			} elsif ( $internaltext =~ /\S/ ) {
                   8500: 		  # something interesting inside the tag
                   8501: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8502: 			} else {
1.908     albertel 8503: 		  # no interesting values, don't set a default
1.339     albertel 8504: 			}
1.172     www      8505: # end of not-a-package not-a-library import
1.339     albertel 8506: 		    }
1.172     www      8507: # end of not-a-package start tag
1.339     albertel 8508: 		}
1.172     www      8509: # the next is the end of "start tag"
1.339     albertel 8510: 	    }
                   8511: 	}
1.483     albertel 8512: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8513: 	$extension = lc($extension);
                   8514: 	if ($extension eq 'htm') { $extension='html'; }
                   8515: 
1.737     albertel 8516: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8517: 	    #no specific packages #how's our extension
                   8518: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8519: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8520: 					 \%metathesekeys);
                   8521: 	}
1.883     albertel 8522: 
                   8523: 	if (!exists($metaentry{':packages'})
                   8524: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8525: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8526: 		#no specific packages well let's get default then
                   8527: 		if ($key!~/^default&/) { next; }
1.488     albertel 8528: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8529: 					     \%metathesekeys);
                   8530: 	    }
                   8531: 	}
1.338     www      8532: # are there custom rights to evaluate
1.599     albertel 8533: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8534: 
1.338     www      8535:     #
                   8536:     # Importing a rights file here
1.339     albertel 8537:     #
                   8538: 	    unless ($depthcount) {
1.599     albertel 8539: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8540: 		my $dir=$filename;
                   8541: 		$dir=~s|[^/]*$||;
                   8542: 		$location=&filelocation($dir,$location);
1.736     albertel 8543: 		my $rights_metadata =
                   8544: 		    &metadata($uri,'keys',$location,'_rights',
                   8545: 			      $depthcount+1);
                   8546: 		foreach my $rights (split(',',$rights_metadata)) {
                   8547: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8548: 		    $metathesekeys{$rights}=1;
1.339     albertel 8549: 		}
                   8550: 	    }
                   8551: 	}
1.737     albertel 8552: 	# uniqifiy package listing
                   8553: 	my %seen;
                   8554: 	my @uniq_packages =
                   8555: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8556: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8557: 
1.1070    www      8558:         if ($importedparts) {
                   8559: # We had imported parts and need to rebuild partorder
                   8560:            $metaentry{':partorder'}='';
                   8561:            $metathesekeys{'partorder'}=1;
                   8562:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8563:                if ($origfileimportpartids[$index] eq 'part') {
                   8564: # original part, part of the problem
                   8565:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8566:                } else {
                   8567: # we have imported parts at this position
                   8568:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8569:                }
                   8570:            }
                   8571:            $metaentry{':partorder'}=~s/^\,//;
                   8572:         }
                   8573: 
1.737     albertel 8574: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8575: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8576: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8577: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8578: # this is the end of "was not already recently cached
1.71      www      8579:     }
1.599     albertel 8580:     return $metaentry{':'.$what};
1.261     albertel 8581: }
                   8582: 
1.488     albertel 8583: sub metadata_create_package_def {
1.483     albertel 8584:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8585:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8586:     if ($subp eq 'default') { next; }
                   8587:     
1.599     albertel 8588:     if (defined($metaentry{':packages'})) {
                   8589: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8590:     } else {
1.599     albertel 8591: 	$metaentry{':packages'}=$package;
1.483     albertel 8592:     }
                   8593:     my $value=$packagetab{$key};
                   8594:     my $unikey;
                   8595:     $unikey='parameter_0_'.$name;
1.599     albertel 8596:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8597:     $$metathesekeys{$unikey}=1;
1.599     albertel 8598:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8599: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8600:     }
1.599     albertel 8601:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8602: 	$metaentry{':'.$unikey}=
                   8603: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8604:     }
                   8605: }
                   8606: 
1.261     albertel 8607: sub metadata_generate_part0 {
                   8608:     my ($metadata,$metacache,$uri) = @_;
                   8609:     my %allnames;
1.737     albertel 8610:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8611: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8612: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8613: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8614: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8615: 	    $allnames{$name}=$part;
                   8616: 	  }
                   8617: 	}
                   8618:     }
                   8619:     foreach my $name (keys(%allnames)) {
                   8620:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8621:       my $key=":parameter_0_$name";
1.261     albertel 8622:       $$metacache{"$key.part"}='0';
                   8623:       $$metacache{"$key.name"}=$name;
1.428     albertel 8624:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8625: 					   $allnames{$name}.'_'.$name.
                   8626: 					   '.type'};
1.428     albertel 8627:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8628: 			     '.display'};
1.644     www      8629:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8630:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8631:       $$metacache{"$key.display"}=$olddis;
                   8632:     }
1.71      www      8633: }
                   8634: 
1.764     albertel 8635: # ------------------------------------------------------ Devalidate title cache
                   8636: 
                   8637: sub devalidate_title_cache {
                   8638:     my ($url)=@_;
                   8639:     if (!$env{'request.course.id'}) { return; }
                   8640:     my $symb=&symbread($url);
                   8641:     if (!$symb) { return; }
                   8642:     my $key=$env{'request.course.id'}."\0".$symb;
                   8643:     &devalidate_cache_new('title',$key);
                   8644: }
                   8645: 
1.1014    droeschl 8646: # ------------------------------------------------- Get the title of a course
                   8647: 
                   8648: sub current_course_title {
                   8649:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8650: }
1.301     www      8651: # ------------------------------------------------- Get the title of a resource
                   8652: 
                   8653: sub gettitle {
                   8654:     my $urlsymb=shift;
                   8655:     my $symb=&symbread($urlsymb);
1.534     albertel 8656:     if ($symb) {
1.620     albertel 8657: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8658: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8659: 	if (defined($cached)) { 
                   8660: 	    return $result;
                   8661: 	}
1.534     albertel 8662: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8663: 	my $title='';
1.907     albertel 8664: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8665: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8666: 	} else {
                   8667: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8668: 		    &GDBM_READER(),0640)) {
                   8669: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8670: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8671: 		untie(%bighash);
                   8672: 	    }
1.534     albertel 8673: 	}
                   8674: 	$title=~s/\&colon\;/\:/gs;
                   8675: 	if ($title) {
1.599     albertel 8676: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8677: 	}
                   8678: 	$urlsymb=$url;
                   8679:     }
                   8680:     my $title=&metadata($urlsymb,'title');
                   8681:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8682:     return $title;
1.301     www      8683: }
1.613     albertel 8684: 
1.614     albertel 8685: sub get_slot {
                   8686:     my ($which,$cnum,$cdom)=@_;
                   8687:     if (!$cnum || !$cdom) {
1.790     albertel 8688: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8689: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8690: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8691:     }
1.703     albertel 8692:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8693:     my %slotinfo;
                   8694:     if (exists($remembered{$key})) {
                   8695: 	$slotinfo{$which} = $remembered{$key};
                   8696:     } else {
                   8697: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8698: 	&Apache::lonhomework::showhash(%slotinfo);
                   8699: 	my ($tmp)=keys(%slotinfo);
                   8700: 	if ($tmp=~/^error:/) { return (); }
                   8701: 	$remembered{$key} = $slotinfo{$which};
                   8702:     }
1.616     albertel 8703:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8704: 	return %{$slotinfo{$which}};
                   8705:     }
                   8706:     return $slotinfo{$which};
1.614     albertel 8707: }
1.31      www      8708: # ------------------------------------------------- Update symbolic store links
                   8709: 
                   8710: sub symblist {
                   8711:     my ($mapname,%newhash)=@_;
1.438     www      8712:     $mapname=&deversion(&declutter($mapname));
1.31      www      8713:     my %hash;
1.620     albertel 8714:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8715:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8716:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8717: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8718: 		next if ($url eq 'last_known'
                   8719: 			 && $env{'form.no_update_last_known'});
                   8720: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8721: 						    $newhash{$url}->[1],
                   8722: 						    $newhash{$url}->[0]);
1.191     harris41 8723:             }
1.31      www      8724:             if (untie(%hash)) {
                   8725: 		return 'ok';
                   8726:             }
                   8727:         }
                   8728:     }
                   8729:     return 'error';
1.212     www      8730: }
                   8731: 
                   8732: # --------------------------------------------------------------- Verify a symb
                   8733: 
                   8734: sub symbverify {
1.510     www      8735:     my ($symb,$thisurl)=@_;
                   8736:     my $thisfn=$thisurl;
1.439     www      8737:     $thisfn=&declutter($thisfn);
1.215     www      8738: # direct jump to resource in page or to a sequence - will construct own symbs
                   8739:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8740: # check URL part
1.409     www      8741:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8742: 
1.431     www      8743:     unless ($url eq $thisfn) { return 0; }
1.213     www      8744: 
1.216     www      8745:     $symb=&symbclean($symb);
1.510     www      8746:     $thisurl=&deversion($thisurl);
1.439     www      8747:     $thisfn=&deversion($thisfn);
1.213     www      8748: 
                   8749:     my %bighash;
                   8750:     my $okay=0;
1.431     www      8751: 
1.620     albertel 8752:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8753:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8754:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8755:             $thisurl =~ s/\?.+$//;
                   8756:         }
1.510     www      8757:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8758:         unless ($ids) { 
1.510     www      8759:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8760:         }
                   8761:         if ($ids) {
                   8762: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8763: 	    foreach my $id (split(/\,/,$ids)) {
                   8764: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8765:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8766:                    $symb =~ s/\?.+$//;
                   8767:                }
1.216     www      8768:                if (
                   8769:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8770:    eq $symb) { 
1.620     albertel 8771: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8772: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8773: 		       $okay=1; 
                   8774: 		   }
                   8775: 	       }
1.216     www      8776: 	   }
                   8777:         }
1.213     www      8778: 	untie(%bighash);
                   8779:     }
                   8780:     return $okay;
1.31      www      8781: }
                   8782: 
1.210     www      8783: # --------------------------------------------------------------- Clean-up symb
                   8784: 
                   8785: sub symbclean {
                   8786:     my $symb=shift;
1.568     albertel 8787:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8788: # remove version from map
                   8789:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8790: 
1.210     www      8791: # remove version from URL
                   8792:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8793: 
1.507     www      8794: # remove wrapper
                   8795: 
1.510     www      8796:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8797:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8798:     return $symb;
1.409     www      8799: }
                   8800: 
                   8801: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8802: 
                   8803: sub encode_symb {
                   8804:     my ($map,$resid,$url)=@_;
                   8805:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8806: }
1.409     www      8807: 
                   8808: sub decode_symb {
1.568     albertel 8809:     my $symb=shift;
                   8810:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8811:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8812:     return (&fixversion($map),$resid,&fixversion($url));
                   8813: }
                   8814: 
                   8815: sub fixversion {
                   8816:     my $fn=shift;
1.609     banghart 8817:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8818:     my %bighash;
                   8819:     my $uri=&clutter($fn);
1.620     albertel 8820:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8821: # is this cached?
1.599     albertel 8822:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8823:     if (defined($cached)) { return $result; }
                   8824: # unfortunately not cached, or expired
1.620     albertel 8825:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8826: 	    &GDBM_READER(),0640)) {
                   8827:  	if ($bighash{'version_'.$uri}) {
                   8828:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8829:  	    unless (($version eq 'mostrecent') || 
                   8830: 		    ($version==&getversion($uri))) {
1.440     www      8831:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8832:  	    }
                   8833:  	}
                   8834:  	untie %bighash;
1.413     www      8835:     }
1.599     albertel 8836:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8837: }
                   8838: 
                   8839: sub deversion {
                   8840:     my $url=shift;
                   8841:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8842:     return $url;
1.210     www      8843: }
                   8844: 
1.31      www      8845: # ------------------------------------------------------ Return symb list entry
                   8846: 
                   8847: sub symbread {
1.249     www      8848:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8849:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8850:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8851: # no filename provided? try from environment
1.44      www      8852:     unless ($thisfn) {
1.620     albertel 8853:         if ($env{'request.symb'}) {
                   8854: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8855: 	}
1.620     albertel 8856: 	$thisfn=$env{'request.filename'};
1.44      www      8857:     }
1.569     albertel 8858:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8859: # is that filename actually a symb? Verify, clean, and return
                   8860:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8861: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8862: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8863: 	}
1.242     www      8864:     }
1.44      www      8865:     $thisfn=declutter($thisfn);
1.31      www      8866:     my %hash;
1.37      www      8867:     my %bighash;
                   8868:     my $syval='';
1.620     albertel 8869:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8870:         my $targetfn = $thisfn;
1.609     banghart 8871:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8872:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8873:         }
1.687     albertel 8874: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8875: 	    $targetfn=$1;
                   8876: 	}
1.620     albertel 8877:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8878:                       &GDBM_READER(),0640)) {
1.481     raeburn  8879: 	    $syval=$hash{$targetfn};
1.37      www      8880:             untie(%hash);
                   8881:         }
                   8882: # ---------------------------------------------------------- There was an entry
                   8883:         if ($syval) {
1.601     albertel 8884: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8885: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8886: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8887: 		    #return $env{$cache_str}='';
1.601     albertel 8888: 		#}    
                   8889: 		#$syval.=$1;
                   8890: 	    #}
1.37      www      8891:         } else {
                   8892: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8893:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8894:                             &GDBM_READER(),0640)) {
1.37      www      8895: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8896:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8897:               unless ($ids) { 
                   8898:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8899:               }
                   8900:               unless ($ids) {
                   8901: # alias?
                   8902: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8903:               }
1.37      www      8904:               if ($ids) {
                   8905: # ------------------------------------------------------------------- Has ID(s)
                   8906:                  my @possibilities=split(/\,/,$ids);
1.39      www      8907:                  if ($#possibilities==0) {
                   8908: # ----------------------------------------------- There is only one possibility
1.37      www      8909: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8910: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8911: 						    $resid,$thisfn);
1.249     www      8912:                  } elsif (!$donotrecurse) {
1.39      www      8913: # ------------------------------------------ There is more than one possibility
                   8914:                      my $realpossible=0;
1.800     albertel 8915:                      foreach my $id (@possibilities) {
                   8916: 			 my $file=$bighash{'src_'.$id};
1.39      www      8917:                          if (&allowed('bre',$file)) {
1.800     albertel 8918:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8919:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8920: 				$realpossible++;
1.626     albertel 8921:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8922: 						    $resid,$thisfn);
1.39      www      8923:                             }
                   8924: 			 }
1.191     harris41 8925:                      }
1.39      www      8926: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8927:                  } else {
                   8928:                      $syval='';
1.37      www      8929:                  }
                   8930: 	      }
                   8931:               untie(%bighash)
1.481     raeburn  8932:            }
1.31      www      8933:         }
1.62      www      8934:         if ($syval) {
1.620     albertel 8935: 	    return $env{$cache_str}=$syval;
1.62      www      8936:         }
1.31      www      8937:     }
1.949     raeburn  8938:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8939:     return $env{$cache_str}='';
1.31      www      8940: }
                   8941: 
                   8942: # ---------------------------------------------------------- Return random seed
                   8943: 
1.32      www      8944: sub numval {
                   8945:     my $txt=shift;
                   8946:     $txt=~tr/A-J/0-9/;
                   8947:     $txt=~tr/a-j/0-9/;
                   8948:     $txt=~tr/K-T/0-9/;
                   8949:     $txt=~tr/k-t/0-9/;
                   8950:     $txt=~tr/U-Z/0-5/;
                   8951:     $txt=~tr/u-z/0-5/;
                   8952:     $txt=~s/\D//g;
1.564     albertel 8953:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8954:     return int($txt);
1.368     albertel 8955: }
                   8956: 
1.484     albertel 8957: sub numval2 {
                   8958:     my $txt=shift;
                   8959:     $txt=~tr/A-J/0-9/;
                   8960:     $txt=~tr/a-j/0-9/;
                   8961:     $txt=~tr/K-T/0-9/;
                   8962:     $txt=~tr/k-t/0-9/;
                   8963:     $txt=~tr/U-Z/0-5/;
                   8964:     $txt=~tr/u-z/0-5/;
                   8965:     $txt=~s/\D//g;
                   8966:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8967:     my $total;
                   8968:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8969:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8970:     return int($total);
                   8971: }
                   8972: 
1.575     albertel 8973: sub numval3 {
                   8974:     use integer;
                   8975:     my $txt=shift;
                   8976:     $txt=~tr/A-J/0-9/;
                   8977:     $txt=~tr/a-j/0-9/;
                   8978:     $txt=~tr/K-T/0-9/;
                   8979:     $txt=~tr/k-t/0-9/;
                   8980:     $txt=~tr/U-Z/0-5/;
                   8981:     $txt=~tr/u-z/0-5/;
                   8982:     $txt=~s/\D//g;
                   8983:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8984:     my $total;
                   8985:     foreach my $val (@txts) { $total+=$val; }
                   8986:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8987:     return $total;
                   8988: }
                   8989: 
1.675     albertel 8990: sub digest {
                   8991:     my ($data)=@_;
                   8992:     my $digest=&Digest::MD5::md5($data);
                   8993:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8994:     my ($e,$f);
                   8995:     {
                   8996:         use integer;
                   8997:         $e=($a+$b);
                   8998:         $f=($c+$d);
                   8999:         if ($_64bit) {
                   9000:             $e=(($e<<32)>>32);
                   9001:             $f=(($f<<32)>>32);
                   9002:         }
                   9003:     }
                   9004:     if (wantarray) {
                   9005: 	return ($e,$f);
                   9006:     } else {
                   9007: 	my $g;
                   9008: 	{
                   9009: 	    use integer;
                   9010: 	    $g=($e+$f);
                   9011: 	    if ($_64bit) {
                   9012: 		$g=(($g<<32)>>32);
                   9013: 	    }
                   9014: 	}
                   9015: 	return $g;
                   9016:     }
                   9017: }
                   9018: 
1.368     albertel 9019: sub latest_rnd_algorithm_id {
1.675     albertel 9020:     return '64bit5';
1.366     albertel 9021: }
1.32      www      9022: 
1.503     albertel 9023: sub get_rand_alg {
                   9024:     my ($courseid)=@_;
1.790     albertel 9025:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9026:     if ($courseid) {
1.620     albertel 9027: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9028:     }
                   9029:     return &latest_rnd_algorithm_id();
                   9030: }
                   9031: 
1.562     albertel 9032: sub validCODE {
                   9033:     my ($CODE)=@_;
                   9034:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9035:     return 0;
                   9036: }
                   9037: 
1.491     albertel 9038: sub getCODE {
1.620     albertel 9039:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9040:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9041: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9042: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9043: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9044:     }
                   9045:     return undef;
                   9046: }
                   9047: 
1.31      www      9048: sub rndseed {
1.155     albertel 9049:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9050:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9051:     if (!defined($symb)) {
1.366     albertel 9052: 	unless ($symb=$wsymb) { return time; }
                   9053:     }
                   9054:     if (!$courseid) { $courseid=$wcourseid; }
                   9055:     if (!$domain) { $domain=$wdomain; }
                   9056:     if (!$username) { $username=$wusername }
1.503     albertel 9057:     my $which=&get_rand_alg();
1.803     albertel 9058: 
1.491     albertel 9059:     if (defined(&getCODE())) {
1.675     albertel 9060: 	if ($which eq '64bit5') {
                   9061: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9062: 	} elsif ($which eq '64bit4') {
1.575     albertel 9063: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9064: 	} else {
                   9065: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9066: 	}
1.675     albertel 9067:     } elsif ($which eq '64bit5') {
                   9068: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9069:     } elsif ($which eq '64bit4') {
                   9070: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9071:     } elsif ($which eq '64bit3') {
                   9072: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9073:     } elsif ($which eq '64bit2') {
                   9074: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9075:     } elsif ($which eq '64bit') {
                   9076: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9077:     }
                   9078:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9079: }
                   9080: 
                   9081: sub rndseed_32bit {
                   9082:     my ($symb,$courseid,$domain,$username)=@_;
                   9083:     {
                   9084: 	use integer;
                   9085: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9086: 	my $symbseed=numval($symb) << 22;
                   9087: 	my $namechck=unpack("%32C*",$username) << 17;
                   9088: 	my $nameseed=numval($username) << 12;
                   9089: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9090: 	my $courseseed=unpack("%32C*",$courseid);
                   9091: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9092: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9093: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9094: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9095: 	return $num;
                   9096:     }
                   9097: }
                   9098: 
                   9099: sub rndseed_64bit {
                   9100:     my ($symb,$courseid,$domain,$username)=@_;
                   9101:     {
                   9102: 	use integer;
                   9103: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9104: 	my $symbseed=numval($symb) << 10;
                   9105: 	my $namechck=unpack("%32S*",$username);
                   9106: 	
                   9107: 	my $nameseed=numval($username) << 21;
                   9108: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9109: 	my $courseseed=unpack("%32S*",$courseid);
                   9110: 	
                   9111: 	my $num1=$symbchck+$symbseed+$namechck;
                   9112: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9113: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9114: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9115: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9116: 	return "$num1,$num2";
1.155     albertel 9117:     }
1.366     albertel 9118: }
                   9119: 
1.443     albertel 9120: sub rndseed_64bit2 {
                   9121:     my ($symb,$courseid,$domain,$username)=@_;
                   9122:     {
                   9123: 	use integer;
                   9124: 	# strings need to be an even # of cahracters long, it it is odd the
                   9125:         # last characters gets thrown away
                   9126: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9127: 	my $symbseed=numval($symb) << 10;
                   9128: 	my $namechck=unpack("%32S*",$username.' ');
                   9129: 	
                   9130: 	my $nameseed=numval($username) << 21;
1.501     albertel 9131: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9132: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9133: 	
                   9134: 	my $num1=$symbchck+$symbseed+$namechck;
                   9135: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9136: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9137: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9138: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9139: 	return "$num1,$num2";
                   9140:     }
                   9141: }
                   9142: 
                   9143: sub rndseed_64bit3 {
                   9144:     my ($symb,$courseid,$domain,$username)=@_;
                   9145:     {
                   9146: 	use integer;
                   9147: 	# strings need to be an even # of cahracters long, it it is odd the
                   9148:         # last characters gets thrown away
                   9149: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9150: 	my $symbseed=numval2($symb) << 10;
                   9151: 	my $namechck=unpack("%32S*",$username.' ');
                   9152: 	
                   9153: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9154: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9155: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9156: 	
                   9157: 	my $num1=$symbchck+$symbseed+$namechck;
                   9158: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9159: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9160: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9161: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9162: 	
1.503     albertel 9163: 	return "$num1:$num2";
1.443     albertel 9164:     }
                   9165: }
                   9166: 
1.575     albertel 9167: sub rndseed_64bit4 {
                   9168:     my ($symb,$courseid,$domain,$username)=@_;
                   9169:     {
                   9170: 	use integer;
                   9171: 	# strings need to be an even # of cahracters long, it it is odd the
                   9172:         # last characters gets thrown away
                   9173: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9174: 	my $symbseed=numval3($symb) << 10;
                   9175: 	my $namechck=unpack("%32S*",$username.' ');
                   9176: 	
                   9177: 	my $nameseed=numval3($username) << 21;
                   9178: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9179: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9180: 	
                   9181: 	my $num1=$symbchck+$symbseed+$namechck;
                   9182: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9183: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9184: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9185: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9186: 	
                   9187: 	return "$num1:$num2";
                   9188:     }
                   9189: }
                   9190: 
1.675     albertel 9191: sub rndseed_64bit5 {
                   9192:     my ($symb,$courseid,$domain,$username)=@_;
                   9193:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9194:     return "$num1:$num2";
                   9195: }
                   9196: 
1.366     albertel 9197: sub rndseed_CODE_64bit {
                   9198:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9199:     {
1.366     albertel 9200: 	use integer;
1.443     albertel 9201: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9202: 	my $symbseed=numval2($symb);
1.491     albertel 9203: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9204: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9205: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9206: 	my $num1=$symbseed+$CODEchck;
                   9207: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9208: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9209: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9210: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9211: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9212: 	return "$num1:$num2";
1.366     albertel 9213:     }
                   9214: }
                   9215: 
1.575     albertel 9216: sub rndseed_CODE_64bit4 {
                   9217:     my ($symb,$courseid,$domain,$username)=@_;
                   9218:     {
                   9219: 	use integer;
                   9220: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9221: 	my $symbseed=numval3($symb);
                   9222: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9223: 	my $CODEseed=numval3(&getCODE());
                   9224: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9225: 	my $num1=$symbseed+$CODEchck;
                   9226: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9227: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9228: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9229: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9230: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9231: 	return "$num1:$num2";
                   9232:     }
                   9233: }
                   9234: 
1.675     albertel 9235: sub rndseed_CODE_64bit5 {
                   9236:     my ($symb,$courseid,$domain,$username)=@_;
                   9237:     my $code = &getCODE();
                   9238:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9239:     return "$num1:$num2";
                   9240: }
                   9241: 
1.366     albertel 9242: sub setup_random_from_rndseed {
                   9243:     my ($rndseed)=@_;
1.503     albertel 9244:     if ($rndseed =~/([,:])/) {
                   9245: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9246: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9247:     } else {
                   9248: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9249:     }
1.36      albertel 9250: }
                   9251: 
1.474     albertel 9252: sub latest_receipt_algorithm_id {
1.835     albertel 9253:     return 'receipt3';
1.474     albertel 9254: }
                   9255: 
1.480     www      9256: sub recunique {
                   9257:     my $fucourseid=shift;
                   9258:     my $unique;
1.835     albertel 9259:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9260: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9261: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9262:     } else {
                   9263: 	$unique=$perlvar{'lonReceipt'};
                   9264:     }
                   9265:     return unpack("%32C*",$unique);
                   9266: }
                   9267: 
                   9268: sub recprefix {
                   9269:     my $fucourseid=shift;
                   9270:     my $prefix;
1.835     albertel 9271:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9272: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9273: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9274:     } else {
                   9275: 	$prefix=$perlvar{'lonHostID'};
                   9276:     }
                   9277:     return unpack("%32C*",$prefix);
                   9278: }
                   9279: 
1.76      www      9280: sub ireceipt {
1.474     albertel 9281:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9282: 
                   9283:     my $return =&recprefix($fucourseid).'-';
                   9284: 
                   9285:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9286: 	$env{'request.state'} eq 'construct') {
                   9287: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9288: 	return $return;
                   9289:     }
                   9290: 
1.76      www      9291:     my $cuname=unpack("%32C*",$funame);
                   9292:     my $cudom=unpack("%32C*",$fudom);
                   9293:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9294:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9295:     my $cunique=&recunique($fucourseid);
1.474     albertel 9296:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9297:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9298: 
1.790     albertel 9299: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9300: 			       
                   9301: 	$return.= ($cunique%$cuname+
                   9302: 		   $cunique%$cudom+
                   9303: 		   $cusymb%$cuname+
                   9304: 		   $cusymb%$cudom+
                   9305: 		   $cucourseid%$cuname+
                   9306: 		   $cucourseid%$cudom+
                   9307: 		   $cpart%$cuname+
                   9308: 		   $cpart%$cudom);
                   9309:     } else {
                   9310: 	$return.= ($cunique%$cuname+
                   9311: 		   $cunique%$cudom+
                   9312: 		   $cusymb%$cuname+
                   9313: 		   $cusymb%$cudom+
                   9314: 		   $cucourseid%$cuname+
                   9315: 		   $cucourseid%$cudom);
                   9316:     }
                   9317:     return $return;
1.76      www      9318: }
                   9319: 
                   9320: sub receipt {
1.474     albertel 9321:     my ($part)=@_;
1.790     albertel 9322:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9323:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9324: }
1.260     ng       9325: 
1.790     albertel 9326: sub whichuser {
                   9327:     my ($passedsymb)=@_;
                   9328:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9329:     if (defined($env{'form.grade_symb'})) {
                   9330: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9331: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9332: 	if (!$allowed &&
                   9333: 	    exists($env{'request.course.sec'}) &&
                   9334: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9335: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9336: 			      '/'.$env{'request.course.sec'});
                   9337: 	}
                   9338: 	if ($allowed) {
                   9339: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9340: 	    $courseid=$tmp_courseid;
                   9341: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9342: 	    ($name)=&get_env_multiple('form.grade_username');
                   9343: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9344: 	}
                   9345:     }
                   9346:     if (!$passedsymb) {
                   9347: 	$symb=&symbread();
                   9348:     } else {
                   9349: 	$symb=$passedsymb;
                   9350:     }
                   9351:     $courseid=$env{'request.course.id'};
                   9352:     $domain=$env{'user.domain'};
                   9353:     $name=$env{'user.name'};
                   9354:     if ($name eq 'public' && $domain eq 'public') {
                   9355: 	if (!defined($env{'form.username'})) {
                   9356: 	    $env{'form.username'}.=time.rand(10000000);
                   9357: 	}
                   9358: 	$name.=$env{'form.username'};
                   9359:     }
                   9360:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9361: 
                   9362: }
                   9363: 
1.36      albertel 9364: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9365: # returns either the contents of the file or 
                   9366: # -1 if the file doesn't exist
1.481     raeburn  9367: #
                   9368: # if the target is a file that was uploaded via DOCS, 
                   9369: # a check will be made to see if a current copy exists on the local server,
                   9370: # if it does this will be served, otherwise a copy will be retrieved from
                   9371: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9372: # the local server.   
1.472     albertel 9373: 
1.36      albertel 9374: sub getfile {
1.538     albertel 9375:     my ($file) = @_;
1.609     banghart 9376:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9377:     &repcopy($file);
                   9378:     return &readfile($file);
                   9379: }
                   9380: 
                   9381: sub repcopy_userfile {
                   9382:     my ($file)=@_;
1.609     banghart 9383:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9384:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9385:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9386: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9387:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9388:     if (-e "$file") {
1.828     www      9389: # we already have a local copy, check it out
1.538     albertel 9390: 	my @fileinfo = stat($file);
1.828     www      9391: 	my $rtncode;
                   9392: 	my $info;
1.538     albertel 9393: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9394: 	if ($lwpresp ne 'ok') {
1.828     www      9395: # there is no such file anymore, even though we had a local copy
1.482     albertel 9396: 	    if ($rtncode eq '404') {
1.538     albertel 9397: 		unlink($file);
1.482     albertel 9398: 	    }
                   9399: 	    return -1;
                   9400: 	}
                   9401: 	if ($info < $fileinfo[9]) {
1.828     www      9402: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9403: 	    return 'ok';
1.828     www      9404: 	} else {
                   9405: # the file is outdated, get rid of it
                   9406: 	    unlink($file);
1.482     albertel 9407: 	}
1.828     www      9408:     }
                   9409: # one way or the other, at this point, we don't have the file
                   9410: # construct the correct path for the file
                   9411:     my @parts = ($cdom,$cnum); 
                   9412:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9413: 	push @parts, split(/\//,$1);
                   9414:     }
                   9415:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9416:     foreach my $part (@parts) {
                   9417: 	$path .= '/'.$part;
                   9418: 	if (!-e $path) {
                   9419: 	    mkdir($path,0770);
1.482     albertel 9420: 	}
                   9421:     }
1.828     www      9422: # now the path exists for sure
                   9423: # get a user agent
                   9424:     my $ua=new LWP::UserAgent;
                   9425:     my $transferfile=$file.'.in.transfer';
                   9426: # FIXME: this should flock
                   9427:     if (-e $transferfile) { return 'ok'; }
                   9428:     my $request;
                   9429:     $uri=~s/^\///;
1.980     raeburn  9430:     my $homeserver = &homeserver($cnum,$cdom);
                   9431:     my $protocol = $protocol{$homeserver};
                   9432:     $protocol = 'http' if ($protocol ne 'https');
                   9433:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9434:     my $response=$ua->request($request,$transferfile);
                   9435: # did it work?
                   9436:     if ($response->is_error()) {
                   9437: 	unlink($transferfile);
                   9438: 	&logthis("Userfile repcopy failed for $uri");
                   9439: 	return -1;
                   9440:     }
                   9441: # worked, rename the transfer file
                   9442:     rename($transferfile,$file);
1.607     raeburn  9443:     return 'ok';
1.481     raeburn  9444: }
                   9445: 
1.517     albertel 9446: sub tokenwrapper {
                   9447:     my $uri=shift;
1.980     raeburn  9448:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9449:     $uri=~s|^/||;
1.620     albertel 9450:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9451:     my $token=$1;
1.552     albertel 9452:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9453:     if ($udom && $uname && $file) {
                   9454: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9455:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9456:         my $homeserver = &homeserver($uname,$udom);
                   9457:         my $protocol = $protocol{$homeserver};
                   9458:         $protocol = 'http' if ($protocol ne 'https');
                   9459:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9460:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9461:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9462:     } else {
                   9463:         return '/adm/notfound.html';
                   9464:     }
                   9465: }
                   9466: 
1.828     www      9467: # call with reqtype HEAD: get last modification time
                   9468: # call with reqtype GET: get the file contents
                   9469: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9470: #
1.481     raeburn  9471: sub getuploaded {
                   9472:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9473:     $uri=~s/^\///;
1.980     raeburn  9474:     my $homeserver = &homeserver($cnum,$cdom);
                   9475:     my $protocol = $protocol{$homeserver};
                   9476:     $protocol = 'http' if ($protocol ne 'https');
                   9477:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9478:     my $ua=new LWP::UserAgent;
                   9479:     my $request=new HTTP::Request($reqtype,$uri);
                   9480:     my $response=$ua->request($request);
                   9481:     $$rtncode = $response->code;
1.482     albertel 9482:     if (! $response->is_success()) {
                   9483: 	return 'failed';
                   9484:     }      
                   9485:     if ($reqtype eq 'HEAD') {
1.486     www      9486: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9487:     } elsif ($reqtype eq 'GET') {
                   9488: 	$$info = $response->content;
1.472     albertel 9489:     }
1.482     albertel 9490:     return 'ok';
1.36      albertel 9491: }
                   9492: 
1.481     raeburn  9493: sub readfile {
                   9494:     my $file = shift;
                   9495:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9496:     my $fh;
                   9497:     open($fh,"<$file");
                   9498:     my $a='';
1.800     albertel 9499:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9500:     return $a;
                   9501: }
                   9502: 
1.36      albertel 9503: sub filelocation {
1.590     banghart 9504:     my ($dir,$file) = @_;
                   9505:     my $location;
                   9506:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9507: 
                   9508:     if ($file =~ m-^/adm/-) {
                   9509: 	$file=~s-^/adm/wrapper/-/-;
                   9510: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9511:     }
1.882     albertel 9512: 
1.590     banghart 9513:     if ($file=~m:^/~:) { # is a contruction space reference
                   9514:         $location = $file;
                   9515:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9516:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9517: 	# is a correct contruction space reference
                   9518:         $location = $file;
1.956     raeburn  9519:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9520:         $location = $file;
1.609     banghart 9521:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9522:         my ($udom,$uname,$filename)=
1.811     albertel 9523:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9524:         my $home=&homeserver($uname,$udom);
                   9525:         my $is_me=0;
                   9526:         my @ids=&current_machine_ids();
                   9527:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9528:         if ($is_me) {
1.955     raeburn  9529:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9530:         } else {
                   9531:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9532:   	      $udom.'/'.$uname.'/'.$filename;
                   9533:         }
1.882     albertel 9534:     } elsif ($file =~ m-^/adm/-) {
                   9535: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9536:     } else {
                   9537:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9538:         $file=~s:^/res/:/:;
                   9539:         if ( !( $file =~ m:^/:) ) {
                   9540:             $location = $dir. '/'.$file;
                   9541:         } else {
                   9542:             $location = '/home/httpd/html/res'.$file;
                   9543:         }
1.59      albertel 9544:     }
1.590     banghart 9545:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9546:     while ($location=~m{/\.\./}) {
                   9547: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9548: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9549: 	} else {
                   9550: 	    $location=~ s{/\.\./}{/}g;
                   9551: 	}
                   9552:     } #remove dir/..
1.590     banghart 9553:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9554:     return $location;
1.46      www      9555: }
1.36      albertel 9556: 
1.46      www      9557: sub hreflocation {
                   9558:     my ($dir,$file)=@_;
1.980     raeburn  9559:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9560: 	$file=filelocation($dir,$file);
1.700     albertel 9561:     } elsif ($file=~m-^/adm/-) {
                   9562: 	$file=~s-^/adm/wrapper/-/-;
                   9563: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9564:     }
                   9565:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9566: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9567:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9568: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9569:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9570: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9571: 	    -/uploaded/$1/$2/-x;
1.46      www      9572:     }
1.913     albertel 9573:     if ($file=~ m{^/userfiles/}) {
                   9574: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9575:     }
1.462     albertel 9576:     return $file;
1.465     albertel 9577: }
                   9578: 
                   9579: sub current_machine_domains {
1.853     albertel 9580:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9581: }
                   9582: 
                   9583: sub machine_domains {
                   9584:     my ($hostname) = @_;
1.465     albertel 9585:     my @domains;
1.838     albertel 9586:     my %hostname = &all_hostnames();
1.465     albertel 9587:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9588: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9589: 	if ($hostname eq $name) {
1.844     albertel 9590: 	    push(@domains,&host_domain($id));
1.465     albertel 9591: 	}
                   9592:     }
                   9593:     return @domains;
                   9594: }
                   9595: 
                   9596: sub current_machine_ids {
1.853     albertel 9597:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9598: }
                   9599: 
                   9600: sub machine_ids {
                   9601:     my ($hostname) = @_;
                   9602:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9603:     my @ids;
1.888     albertel 9604:     my %name_to_host = &all_names();
1.889     albertel 9605:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9606: 	return @{ $name_to_host{$hostname} };
                   9607:     }
                   9608:     return;
1.31      www      9609: }
                   9610: 
1.824     raeburn  9611: sub additional_machine_domains {
                   9612:     my @domains;
                   9613:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9614:     while( my $line = <$fh>) {
                   9615:         $line =~ s/\s//g;
                   9616:         push(@domains,$line);
                   9617:     }
                   9618:     return @domains;
                   9619: }
                   9620: 
                   9621: sub default_login_domain {
                   9622:     my $domain = $perlvar{'lonDefDomain'};
                   9623:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9624:     foreach my $posdom (&current_machine_domains(),
                   9625:                         &additional_machine_domains()) {
                   9626:         if (lc($posdom) eq lc($testdomain)) {
                   9627:             $domain=$posdom;
                   9628:             last;
                   9629:         }
                   9630:     }
                   9631:     return $domain;
                   9632: }
                   9633: 
1.31      www      9634: # ------------------------------------------------------------- Declutters URLs
                   9635: 
                   9636: sub declutter {
                   9637:     my $thisfn=shift;
1.569     albertel 9638:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9639:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9640:     $thisfn=~s/^\///;
1.697     albertel 9641:     $thisfn=~s|^adm/wrapper/||;
                   9642:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9643:     $thisfn=~s/^res\///;
1.1032    raeburn  9644:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9645:         $thisfn=~s/\?.+$//;
                   9646:     }
1.268     www      9647:     return $thisfn;
                   9648: }
                   9649: 
                   9650: # ------------------------------------------------------------- Clutter up URLs
                   9651: 
                   9652: sub clutter {
                   9653:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9654:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9655: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9656:        $thisfn='/res'.$thisfn; 
                   9657:     }
1.1031    raeburn  9658:     if ($thisfn !~m|^/adm|) {
                   9659: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9660: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9661: 	} else {
                   9662: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9663: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9664: 	    if ($embstyle eq 'ssi'
                   9665: 		|| ($embstyle eq 'hdn')
                   9666: 		|| ($embstyle eq 'rat')
                   9667: 		|| ($embstyle eq 'prv')
                   9668: 		|| ($embstyle eq 'ign')) {
                   9669: 		#do nothing with these
                   9670: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9671: 		|| ($embstyle eq 'emb')
                   9672: 		|| ($embstyle eq 'wrp')) {
                   9673: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9674: 	    } elsif ($embstyle eq 'unk'
                   9675: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9676: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9677: 	    } else {
1.718     www      9678: #		&logthis("Got a blank emb style");
1.695     albertel 9679: 	    }
1.694     albertel 9680: 	}
                   9681:     }
1.31      www      9682:     return $thisfn;
1.12      www      9683: }
                   9684: 
1.787     albertel 9685: sub clutter_with_no_wrapper {
                   9686:     my $uri = &clutter(shift);
                   9687:     if ($uri =~ m-^/adm/-) {
                   9688: 	$uri =~ s-^/adm/wrapper/-/-;
                   9689: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9690:     }
                   9691:     return $uri;
                   9692: }
                   9693: 
1.557     albertel 9694: sub freeze_escape {
                   9695:     my ($value)=@_;
                   9696:     if (ref($value)) {
                   9697: 	$value=&nfreeze($value);
                   9698: 	return '__FROZEN__'.&escape($value);
                   9699:     }
                   9700:     return &escape($value);
                   9701: }
                   9702: 
1.11      www      9703: 
1.557     albertel 9704: sub thaw_unescape {
                   9705:     my ($value)=@_;
                   9706:     if ($value =~ /^__FROZEN__/) {
                   9707: 	substr($value,0,10,undef);
                   9708: 	$value=&unescape($value);
                   9709: 	return &thaw($value);
                   9710:     }
                   9711:     return &unescape($value);
                   9712: }
                   9713: 
1.436     albertel 9714: sub correct_line_ends {
                   9715:     my ($result)=@_;
                   9716:     $$result =~s/\r\n/\n/mg;
                   9717:     $$result =~s/\r/\n/mg;
1.415     albertel 9718: }
1.1       albertel 9719: # ================================================================ Main Program
                   9720: 
1.184     www      9721: sub goodbye {
1.204     albertel 9722:    &logthis("Starting Shut down");
1.443     albertel 9723: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9724:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9725: #converted
1.599     albertel 9726: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9727:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9728: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9729: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9730: #1.1 only
1.870     albertel 9731: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9732: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9733: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9734: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9735:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9736:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9737:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9738:    &flushcourselogs();
                   9739:    &logthis("Shutting down");
                   9740: }
                   9741: 
1.852     albertel 9742: sub get_dns {
1.869     albertel 9743:     my ($url,$func,$ignore_cache) = @_;
                   9744:     if (!$ignore_cache) {
                   9745: 	my ($content,$cached)=
                   9746: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9747: 	if ($cached) {
                   9748: 	    &$func($content);
                   9749: 	    return;
                   9750: 	}
                   9751:     }
                   9752: 
                   9753:     my %alldns;
1.852     albertel 9754:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9755:     foreach my $dns (<$config>) {
                   9756: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9757:         my $line = $1;
                   9758:         my ($host,$protocol) = split(/:/,$line);
                   9759:         if ($protocol ne 'https') {
                   9760:             $protocol = 'http';
                   9761:         }
                   9762: 	$alldns{$host} = $protocol;
1.869     albertel 9763:     }
                   9764:     while (%alldns) {
                   9765: 	my ($dns) = keys(%alldns);
1.852     albertel 9766: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9767: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9768: 	my $response=$ua->request($request);
1.979     raeburn  9769:         delete($alldns{$dns});
1.852     albertel 9770: 	next if ($response->is_error());
                   9771: 	my @content = split("\n",$response->content);
1.869     albertel 9772: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9773: 	&$func(\@content);
1.869     albertel 9774: 	return;
1.852     albertel 9775:     }
                   9776:     close($config);
1.871     albertel 9777:     my $which = (split('/',$url))[3];
                   9778:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9779:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9780:     my @content = <$config>;
                   9781:     &$func(\@content);
                   9782:     return;
1.852     albertel 9783: }
1.327     albertel 9784: # ------------------------------------------------------------ Read domain file
                   9785: {
1.852     albertel 9786:     my $loaded;
1.846     albertel 9787:     my %domain;
                   9788: 
1.852     albertel 9789:     sub parse_domain_tab {
                   9790: 	my ($lines) = @_;
                   9791: 	foreach my $line (@$lines) {
                   9792: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9793: 
1.846     albertel 9794: 	    chomp($line);
1.852     albertel 9795: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9796: 	    my %this_domain;
                   9797: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9798: 			       'lang_def', 'city', 'longi', 'lati',
                   9799: 			       'primary') {
                   9800: 		$this_domain{$field} = shift(@elements);
                   9801: 	    }
                   9802: 	    $domain{$name} = \%this_domain;
1.852     albertel 9803: 	}
                   9804:     }
1.864     albertel 9805: 
                   9806:     sub reset_domain_info {
                   9807: 	undef($loaded);
                   9808: 	undef(%domain);
                   9809:     }
                   9810: 
1.852     albertel 9811:     sub load_domain_tab {
1.869     albertel 9812: 	my ($ignore_cache) = @_;
                   9813: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9814: 	my $fh;
                   9815: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9816: 	    my @lines = <$fh>;
                   9817: 	    &parse_domain_tab(\@lines);
1.448     albertel 9818: 	}
1.852     albertel 9819: 	close($fh);
                   9820: 	$loaded = 1;
1.327     albertel 9821:     }
1.846     albertel 9822: 
                   9823:     sub domain {
1.852     albertel 9824: 	&load_domain_tab() if (!$loaded);
                   9825: 
1.846     albertel 9826: 	my ($name,$what) = @_;
                   9827: 	return if ( !exists($domain{$name}) );
                   9828: 
                   9829: 	if (!$what) {
                   9830: 	    return $domain{$name}{'description'};
                   9831: 	}
                   9832: 	return $domain{$name}{$what};
                   9833:     }
1.974     raeburn  9834: 
                   9835:     sub domain_info {
                   9836:         &load_domain_tab() if (!$loaded);
                   9837:         return %domain;
                   9838:     }
                   9839: 
1.327     albertel 9840: }
                   9841: 
                   9842: 
1.1       albertel 9843: # ------------------------------------------------------------- Read hosts file
                   9844: {
1.838     albertel 9845:     my %hostname;
1.844     albertel 9846:     my %hostdom;
1.845     albertel 9847:     my %libserv;
1.852     albertel 9848:     my $loaded;
1.888     albertel 9849:     my %name_to_host;
1.1074    raeburn  9850:     my %internetdom;
1.852     albertel 9851: 
                   9852:     sub parse_hosts_tab {
                   9853: 	my ($file) = @_;
                   9854: 	foreach my $configline (@$file) {
                   9855: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9856: 	    next if ($configline =~ /^\^/);
                   9857: 	    chomp($configline);
1.1074    raeburn  9858: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 9859: 	    $name=~s/\s//g;
                   9860: 	    if ($id && $domain && $role && $name) {
                   9861: 		$hostname{$id}=$name;
1.888     albertel 9862: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9863: 		$hostdom{$id}=$domain;
                   9864: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9865:                 if (defined($protocol)) {
                   9866:                     if ($protocol eq 'https') {
                   9867:                         $protocol{$id} = $protocol;
                   9868:                     } else {
                   9869:                         $protocol{$id} = 'http'; 
                   9870:                     }
1.968     raeburn  9871:                 } else {
1.969     raeburn  9872:                     $protocol{$id} = 'http';
1.968     raeburn  9873:                 }
1.1074    raeburn  9874:                 if (defined($intdom)) {
                   9875:                     $internetdom{$id} = $intdom;
                   9876:                 }
1.852     albertel 9877: 	    }
                   9878: 	}
                   9879:     }
1.864     albertel 9880:     
                   9881:     sub reset_hosts_info {
1.897     albertel 9882: 	&purge_remembered();
1.864     albertel 9883: 	&reset_domain_info();
                   9884: 	&reset_hosts_ip_info();
1.892     albertel 9885: 	undef(%name_to_host);
1.864     albertel 9886: 	undef(%hostname);
                   9887: 	undef(%hostdom);
                   9888: 	undef(%libserv);
                   9889: 	undef($loaded);
                   9890:     }
1.1       albertel 9891: 
1.852     albertel 9892:     sub load_hosts_tab {
1.869     albertel 9893: 	my ($ignore_cache) = @_;
                   9894: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9895: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9896: 	my @config = <$config>;
                   9897: 	&parse_hosts_tab(\@config);
                   9898: 	close($config);
                   9899: 	$loaded=1;
1.1       albertel 9900:     }
1.852     albertel 9901: 
1.838     albertel 9902:     sub hostname {
1.852     albertel 9903: 	&load_hosts_tab() if (!$loaded);
                   9904: 
1.838     albertel 9905: 	my ($lonid) = @_;
                   9906: 	return $hostname{$lonid};
                   9907:     }
1.845     albertel 9908: 
1.838     albertel 9909:     sub all_hostnames {
1.852     albertel 9910: 	&load_hosts_tab() if (!$loaded);
                   9911: 
1.838     albertel 9912: 	return %hostname;
                   9913:     }
1.845     albertel 9914: 
1.888     albertel 9915:     sub all_names {
                   9916: 	&load_hosts_tab() if (!$loaded);
                   9917: 
                   9918: 	return %name_to_host;
                   9919:     }
                   9920: 
1.974     raeburn  9921:     sub all_host_domain {
                   9922:         &load_hosts_tab() if (!$loaded);
                   9923:         return %hostdom;
                   9924:     }
                   9925: 
1.845     albertel 9926:     sub is_library {
1.852     albertel 9927: 	&load_hosts_tab() if (!$loaded);
                   9928: 
1.845     albertel 9929: 	return exists($libserv{$_[0]});
                   9930:     }
                   9931: 
                   9932:     sub all_library {
1.852     albertel 9933: 	&load_hosts_tab() if (!$loaded);
                   9934: 
1.845     albertel 9935: 	return %libserv;
                   9936:     }
                   9937: 
1.1062    droeschl 9938:     sub unique_library {
                   9939: 	#2x reverse removes all hostnames that appear more than once
                   9940:         my %unique = reverse &all_library();
                   9941:         return reverse %unique;
                   9942:     }
                   9943: 
1.841     albertel 9944:     sub get_servers {
1.852     albertel 9945: 	&load_hosts_tab() if (!$loaded);
                   9946: 
1.841     albertel 9947: 	my ($domain,$type) = @_;
                   9948: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9949: 	                                          : %hostname;
                   9950: 	my %result;
1.842     albertel 9951: 	if (ref($domain) eq 'ARRAY') {
                   9952: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9953: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9954: 		    $result{$host} = $hostname;
                   9955: 		}
                   9956: 	    }
                   9957: 	} else {
                   9958: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9959: 		if ($hostdom{$host} eq $domain) {
                   9960: 		    $result{$host} = $hostname;
                   9961: 		}
1.841     albertel 9962: 	    }
                   9963: 	}
                   9964: 	return %result;
                   9965:     }
1.845     albertel 9966: 
1.1062    droeschl 9967:     sub get_unique_servers {
                   9968:         my %unique = reverse &get_servers(@_);
                   9969: 	return reverse %unique;
                   9970:     }
                   9971: 
1.844     albertel 9972:     sub host_domain {
1.852     albertel 9973: 	&load_hosts_tab() if (!$loaded);
                   9974: 
1.844     albertel 9975: 	my ($lonid) = @_;
                   9976: 	return $hostdom{$lonid};
                   9977:     }
                   9978: 
1.841     albertel 9979:     sub all_domains {
1.852     albertel 9980: 	&load_hosts_tab() if (!$loaded);
                   9981: 
1.841     albertel 9982: 	my %seen;
                   9983: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9984: 	return @uniq;
                   9985:     }
1.1074    raeburn  9986: 
                   9987:     sub internet_dom {
                   9988:         &load_hosts_tab() if (!$loaded);
                   9989: 
                   9990:         my ($lonid) = @_;
                   9991:         return $internetdom{$lonid};
                   9992:     }
1.1       albertel 9993: }
                   9994: 
1.847     albertel 9995: { 
                   9996:     my %iphost;
1.856     albertel 9997:     my %name_to_ip;
                   9998:     my %lonid_to_ip;
1.869     albertel 9999: 
1.847     albertel 10000:     sub get_hosts_from_ip {
                   10001: 	my ($ip) = @_;
                   10002: 	my %iphosts = &get_iphost();
                   10003: 	if (ref($iphosts{$ip})) {
                   10004: 	    return @{$iphosts{$ip}};
                   10005: 	}
                   10006: 	return;
1.839     albertel 10007:     }
1.864     albertel 10008:     
                   10009:     sub reset_hosts_ip_info {
                   10010: 	undef(%iphost);
                   10011: 	undef(%name_to_ip);
                   10012: 	undef(%lonid_to_ip);
                   10013:     }
1.856     albertel 10014: 
                   10015:     sub get_host_ip {
                   10016: 	my ($lonid) = @_;
                   10017: 	if (exists($lonid_to_ip{$lonid})) {
                   10018: 	    return $lonid_to_ip{$lonid};
                   10019: 	}
                   10020: 	my $name=&hostname($lonid);
                   10021:    	my $ip = gethostbyname($name);
                   10022: 	return if (!$ip || length($ip) ne 4);
                   10023: 	$ip=inet_ntoa($ip);
                   10024: 	$name_to_ip{$name}   = $ip;
                   10025: 	$lonid_to_ip{$lonid} = $ip;
                   10026: 	return $ip;
                   10027:     }
1.847     albertel 10028:     
                   10029:     sub get_iphost {
1.869     albertel 10030: 	my ($ignore_cache) = @_;
1.894     albertel 10031: 
1.869     albertel 10032: 	if (!$ignore_cache) {
                   10033: 	    if (%iphost) {
                   10034: 		return %iphost;
                   10035: 	    }
                   10036: 	    my ($ip_info,$cached)=
                   10037: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10038: 	    if ($cached) {
                   10039: 		%iphost      = %{$ip_info->[0]};
                   10040: 		%name_to_ip  = %{$ip_info->[1]};
                   10041: 		%lonid_to_ip = %{$ip_info->[2]};
                   10042: 		return %iphost;
                   10043: 	    }
                   10044: 	}
1.894     albertel 10045: 
                   10046: 	# get yesterday's info for fallback
                   10047: 	my %old_name_to_ip;
                   10048: 	my ($ip_info,$cached)=
                   10049: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10050: 	if ($cached) {
                   10051: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10052: 	}
                   10053: 
1.888     albertel 10054: 	my %name_to_host = &all_names();
                   10055: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10056: 	    my $ip;
                   10057: 	    if (!exists($name_to_ip{$name})) {
                   10058: 		$ip = gethostbyname($name);
                   10059: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10060: 		    if (defined($old_name_to_ip{$name})) {
                   10061: 			$ip = $old_name_to_ip{$name};
                   10062: 			&logthis("Can't find $name defaulting to old $ip");
                   10063: 		    } else {
                   10064: 			&logthis("Name $name no IP found");
                   10065: 			next;
                   10066: 		    }
                   10067: 		} else {
                   10068: 		    $ip=inet_ntoa($ip);
1.847     albertel 10069: 		}
                   10070: 		$name_to_ip{$name} = $ip;
                   10071: 	    } else {
                   10072: 		$ip = $name_to_ip{$name};
1.653     albertel 10073: 	    }
1.888     albertel 10074: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10075: 		$lonid_to_ip{$id} = $ip;
                   10076: 	    }
                   10077: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10078: 	}
1.869     albertel 10079: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10080: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10081: 				      48*60*60);
1.869     albertel 10082: 
1.847     albertel 10083: 	return %iphost;
1.598     albertel 10084:     }
                   10085: 
1.992     raeburn  10086:     #
                   10087:     #  Given a DNS returns the loncapa host name for that DNS 
                   10088:     # 
                   10089:     sub host_from_dns {
                   10090:         my ($dns) = @_;
                   10091:         my @hosts;
                   10092:         my $ip;
                   10093: 
1.993     raeburn  10094:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10095:             $ip = $name_to_ip{$dns};
                   10096:         }
                   10097:         if (!$ip) {
                   10098:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10099:             if (length($ip) == 4) { 
                   10100: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10101:             }
                   10102:         }
                   10103:         if ($ip) {
                   10104: 	    @hosts = get_hosts_from_ip($ip);
                   10105: 	    return $hosts[0];
                   10106:         }
                   10107:         return undef;
1.986     foxr     10108:     }
1.992     raeburn  10109: 
1.1074    raeburn  10110:     sub get_internet_names {
                   10111:         my ($lonid) = @_;
                   10112:         return if ($lonid eq '');
                   10113:         my ($idnref,$cached)=
                   10114:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10115:         if ($cached) {
                   10116:             return $idnref;
                   10117:         }
                   10118:         my $ip = &get_host_ip($lonid);
                   10119:         my @hosts = &get_hosts_from_ip($ip);
                   10120:         my %iphost = &get_iphost();
                   10121:         my (@idns,%seen);
                   10122:         foreach my $id (@hosts) {
                   10123:             my $dom = &host_domain($id);
                   10124:             my $prim_id = &domain($dom,'primary');
                   10125:             my $prim_ip = &get_host_ip($prim_id);
                   10126:             next if ($seen{$prim_ip});
                   10127:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10128:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10129:                     my $intdom = &internet_dom($id);
                   10130:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10131:                         push(@idns,$intdom);
                   10132:                     }
                   10133:                 }
                   10134:             }
                   10135:             $seen{$prim_ip} = 1;
                   10136:         }
                   10137:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10138:     }
                   10139: 
1.986     foxr     10140: }
                   10141: 
1.862     albertel 10142: BEGIN {
                   10143: 
                   10144: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10145:     unless ($readit) {
                   10146: {
                   10147:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10148:     %perlvar = (%perlvar,%{$configvars});
                   10149: }
                   10150: 
                   10151: 
1.1       albertel 10152: # ------------------------------------------------------ Read spare server file
                   10153: {
1.448     albertel 10154:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10155: 
                   10156:     while (my $configline=<$config>) {
                   10157:        chomp($configline);
1.284     matthew  10158:        if ($configline) {
1.784     albertel 10159: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10160: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10161: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10162:        }
                   10163:     }
1.448     albertel 10164:     close($config);
1.1       albertel 10165: }
1.11      www      10166: # ------------------------------------------------------------ Read permissions
                   10167: {
1.448     albertel 10168:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10169: 
                   10170:     while (my $configline=<$config>) {
1.448     albertel 10171: 	chomp($configline);
                   10172: 	if ($configline) {
                   10173: 	    my ($role,$perm)=split(/ /,$configline);
                   10174: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10175: 	}
1.11      www      10176:     }
1.448     albertel 10177:     close($config);
1.11      www      10178: }
                   10179: 
                   10180: # -------------------------------------------- Read plain texts for permissions
                   10181: {
1.448     albertel 10182:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10183: 
                   10184:     while (my $configline=<$config>) {
1.448     albertel 10185: 	chomp($configline);
                   10186: 	if ($configline) {
1.742     raeburn  10187: 	    my ($short,@plain)=split(/:/,$configline);
                   10188:             %{$prp{$short}} = ();
                   10189: 	    if (@plain > 0) {
                   10190:                 $prp{$short}{'std'} = $plain[0];
                   10191:                 for (my $i=1; $i<@plain; $i++) {
                   10192:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10193:                 }
                   10194:             }
1.448     albertel 10195: 	}
1.135     www      10196:     }
1.448     albertel 10197:     close($config);
1.135     www      10198: }
                   10199: 
                   10200: # ---------------------------------------------------------- Read package table
                   10201: {
1.448     albertel 10202:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10203: 
                   10204:     while (my $configline=<$config>) {
1.483     albertel 10205: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10206: 	chomp($configline);
                   10207: 	my ($short,$plain)=split(/:/,$configline);
                   10208: 	my ($pack,$name)=split(/\&/,$short);
                   10209: 	if ($plain ne '') {
                   10210: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10211: 	    $packagetab{$short}=$plain; 
                   10212: 	}
1.11      www      10213:     }
1.448     albertel 10214:     close($config);
1.329     matthew  10215: }
                   10216: 
1.1073    raeburn  10217: # ---------------------------------------------------------- Read loncaparev table
                   10218: {
                   10219:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10220:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10221:             while (my $configline=<$config>) {
                   10222:                 chomp($configline);
                   10223:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10224:                 $loncaparevs{$hostid}=$loncaparev;
                   10225:             }
                   10226:             close($config);
                   10227:         }
                   10228:     }
                   10229: }
                   10230: 
1.1074    raeburn  10231: # ---------------------------------------------------------- Read serverhostID table
                   10232: {
                   10233:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10234:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10235:             while (my $configline=<$config>) {
                   10236:                 chomp($configline);
                   10237:                 my ($name,$id)=split(/:/,$configline);
                   10238:                 $serverhomeIDs{$name}=$id;
                   10239:             }
                   10240:             close($config);
                   10241:         }
                   10242:     }
                   10243: }
                   10244: 
1.1073    raeburn  10245: sub all_loncaparevs {
                   10246:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
                   10247: }
                   10248: 
1.329     matthew  10249: # ------------- set up temporary directory
                   10250: {
                   10251:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10252: 
1.11      www      10253: }
                   10254: 
1.794     albertel 10255: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10256: 				'compress_threshold'=> 20_000,
                   10257:  			        });
1.185     www      10258: 
1.281     www      10259: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10260: $dumpcount=0;
1.958     www      10261: $locknum=0;
1.22      www      10262: 
1.163     harris41 10263: &logtouch();
1.672     albertel 10264: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10265: $readit=1;
1.564     albertel 10266:     {
                   10267: 	use integer;
                   10268: 	my $test=(2**32)+1;
1.568     albertel 10269: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10270: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10271:     }
1.195     www      10272: }
1.1       albertel 10273: }
1.179     www      10274: 
1.1       albertel 10275: 1;
1.191     harris41 10276: __END__
                   10277: 
1.243     albertel 10278: =pod
                   10279: 
1.191     harris41 10280: =head1 NAME
                   10281: 
1.243     albertel 10282: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10283: 
                   10284: =head1 SYNOPSIS
                   10285: 
1.243     albertel 10286: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10287: 
                   10288:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10289: 
1.243     albertel 10290: Common parameters:
                   10291: 
                   10292: =over 4
                   10293: 
                   10294: =item *
                   10295: 
                   10296: $uname : an internal username (if $cname expecting a course Id specifically)
                   10297: 
                   10298: =item *
                   10299: 
                   10300: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10301: 
                   10302: =item *
                   10303: 
                   10304: $symb : a resource instance identifier
                   10305: 
                   10306: =item *
                   10307: 
                   10308: $namespace : the name of a .db file that contains the data needed or
                   10309: being set.
                   10310: 
                   10311: =back
                   10312: 
1.394     bowersj2 10313: =head1 OVERVIEW
1.191     harris41 10314: 
1.394     bowersj2 10315: lonnet provides subroutines which interact with the
                   10316: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10317: about classes, users, and resources.
1.243     albertel 10318: 
                   10319: For many of these objects you can also use this to store data about
                   10320: them or modify them in various ways.
1.191     harris41 10321: 
1.394     bowersj2 10322: =head2 Symbs
1.191     harris41 10323: 
1.394     bowersj2 10324: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10325: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10326: map, the resource number of the resource in the map, and the URL of
                   10327: the resource itself. The latter is somewhat redundant, but might help
                   10328: if maps change.
                   10329: 
                   10330: An example is
                   10331: 
                   10332:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10333: 
                   10334: The respective map entry is
                   10335: 
                   10336:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10337:   title="Problem 2">
                   10338:  </resource>
                   10339: 
                   10340: Symbs are used by the random number generator, as well as to store and
                   10341: restore data specific to a certain instance of for example a problem.
                   10342: 
                   10343: =head2 Storing And Retrieving Data
                   10344: 
                   10345: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10346: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10347: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10348: is is the non-critical message twin of cstore. These functions are for
                   10349: handlers to store a perl hash to a user's permanent data space in an
                   10350: easy manner, and to retrieve it again on another call. It is expected
                   10351: that a handler would use this once at the beginning to retrieve data,
                   10352: and then again once at the end to send only the new data back.
                   10353: 
                   10354: The data is stored in the user's data directory on the user's
                   10355: homeserver under the ID of the course.
                   10356: 
                   10357: The hash that is returned by restore will have all of the previous
                   10358: value for all of the elements of the hash.
                   10359: 
                   10360: Example:
                   10361: 
                   10362:  #creating a hash
                   10363:  my %hash;
                   10364:  $hash{'foo'}='bar';
                   10365: 
                   10366:  #storing it
                   10367:  &Apache::lonnet::cstore(\%hash);
                   10368: 
                   10369:  #changing a value
                   10370:  $hash{'foo'}='notbar';
                   10371: 
                   10372:  #adding a new value
                   10373:  $hash{'bar'}='foo';
                   10374:  &Apache::lonnet::cstore(\%hash);
                   10375: 
                   10376:  #retrieving the hash
                   10377:  my %history=&Apache::lonnet::restore();
                   10378: 
                   10379:  #print the hash
                   10380:  foreach my $key (sort(keys(%history))) {
                   10381:    print("\%history{$key} = $history{$key}");
                   10382:  }
                   10383: 
                   10384: Will print out:
1.191     harris41 10385: 
1.394     bowersj2 10386:  %history{1:foo} = bar
                   10387:  %history{1:keys} = foo:timestamp
                   10388:  %history{1:timestamp} = 990455579
                   10389:  %history{2:bar} = foo
                   10390:  %history{2:foo} = notbar
                   10391:  %history{2:keys} = foo:bar:timestamp
                   10392:  %history{2:timestamp} = 990455580
                   10393:  %history{bar} = foo
                   10394:  %history{foo} = notbar
                   10395:  %history{timestamp} = 990455580
                   10396:  %history{version} = 2
                   10397: 
                   10398: Note that the special hash entries C<keys>, C<version> and
                   10399: C<timestamp> were added to the hash. C<version> will be equal to the
                   10400: total number of versions of the data that have been stored. The
                   10401: C<timestamp> attribute will be the UNIX time the hash was
                   10402: stored. C<keys> is available in every historical section to list which
                   10403: keys were added or changed at a specific historical revision of a
                   10404: hash.
                   10405: 
                   10406: B<Warning>: do not store the hash that restore returns directly. This
                   10407: will cause a mess since it will restore the historical keys as if the
                   10408: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10409: 
1.394     bowersj2 10410: Calling convention:
1.191     harris41 10411: 
1.394     bowersj2 10412:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10413:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10414: 
1.394     bowersj2 10415: For more detailed information, see lonnet specific documentation.
1.191     harris41 10416: 
1.394     bowersj2 10417: =head1 RETURN MESSAGES
1.191     harris41 10418: 
1.394     bowersj2 10419: =over 4
1.191     harris41 10420: 
1.394     bowersj2 10421: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10422: 
1.394     bowersj2 10423: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10424: when the connection is brought back up
1.191     harris41 10425: 
1.394     bowersj2 10426: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10427: for later delivery
1.191     harris41 10428: 
1.967     bisitz   10429: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10430: 
1.394     bowersj2 10431: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10432: that was requested
1.191     harris41 10433: 
1.243     albertel 10434: =back
1.191     harris41 10435: 
1.243     albertel 10436: =head1 PUBLIC SUBROUTINES
1.191     harris41 10437: 
1.243     albertel 10438: =head2 Session Environment Functions
1.191     harris41 10439: 
1.243     albertel 10440: =over 4
1.191     harris41 10441: 
1.394     bowersj2 10442: =item * 
                   10443: X<appenv()>
1.949     raeburn  10444: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10445: the user envirnoment file, and will be restored for each access this
1.620     albertel 10446: user makes during this session, also modifies the %env for the current
1.949     raeburn  10447: process. Optional rolesarrayref - if defined contains a reference to an array
                   10448: of roles which are exempt from the restriction on modifying user.role entries 
                   10449: in the user's environment.db and in %env.    
1.191     harris41 10450: 
                   10451: =item *
1.394     bowersj2 10452: X<delenv()>
1.987     raeburn  10453: B<delenv($delthis,$regexp)>: removes all items from the session
                   10454: environment file that begin with $delthis. If the 
                   10455: optional second arg - $regexp - is true, $delthis is treated as a 
                   10456: regular expression, otherwise \Q$delthis\E is used. 
                   10457: The values are also deleted from the current processes %env.
1.191     harris41 10458: 
1.795     albertel 10459: =item * get_env_multiple($name) 
                   10460: 
                   10461: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10462: values may be defined and end up as an array ref.
                   10463: 
                   10464: returns an array of values
                   10465: 
1.243     albertel 10466: =back
                   10467: 
                   10468: =head2 User Information
1.191     harris41 10469: 
1.243     albertel 10470: =over 4
1.191     harris41 10471: 
                   10472: =item *
1.394     bowersj2 10473: X<queryauthenticate()>
                   10474: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10475: authentication scheme
                   10476: 
                   10477: =item *
1.394     bowersj2 10478: X<authenticate()>
1.1073    raeburn  10479: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10480: authenticate user from domain's lib servers (first use the current
                   10481: one). C<$upass> should be the users password.
1.1073    raeburn  10482: $checkdefauth is optional (value is 1 if a check should be made to
                   10483:    authenticate user using default authentication method, and allow
                   10484:    account creation if username does not have account in the domain).
                   10485: $clientcancheckhost is optional (value is 1 if checking whether the
                   10486:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10487: 
                   10488: =item *
1.394     bowersj2 10489: X<homeserver()>
                   10490: B<homeserver($uname,$udom)>: find the server which has
                   10491: the user's directory and files (there must be only one), this caches
                   10492: the answer, and also caches if there is a borken connection.
1.191     harris41 10493: 
                   10494: =item *
1.394     bowersj2 10495: X<idget()>
                   10496: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10497: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10498: username, and only 1 username per ID in a specific domain) (returns
                   10499: hash: id=>name,id=>name)
1.191     harris41 10500: 
                   10501: =item *
1.394     bowersj2 10502: X<idrget()>
                   10503: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10504: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10505: 
                   10506: =item *
1.394     bowersj2 10507: X<idput()>
                   10508: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10509: 
                   10510: =item *
1.394     bowersj2 10511: X<rolesinit()>
                   10512: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10513: 
                   10514: =item *
1.551     albertel 10515: X<getsection()>
                   10516: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10517: course $cname, return section name/number or '' for "not in course"
                   10518: and '-1' for "no section"
                   10519: 
                   10520: =item *
1.394     bowersj2 10521: X<userenvironment()>
                   10522: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10523: passed in @what from the requested user's environment, returns a hash
                   10524: 
1.858     raeburn  10525: =item * 
                   10526: X<userlog_query()>
1.859     albertel 10527: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10528: activity.log file. %filters defines filters applied when parsing the
                   10529: log file. These can be start or end timestamps, or the type of action
                   10530: - log to look for Login or Logout events, check for Checkin or
                   10531: Checkout, role for role selection. The response is in the form
                   10532: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10533: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10534: 
1.243     albertel 10535: =back
                   10536: 
                   10537: =head2 User Roles
                   10538: 
                   10539: =over 4
                   10540: 
                   10541: =item *
                   10542: 
1.810     raeburn  10543: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10544:  F: full access
                   10545:  U,I,K: authentication modes (cxx only)
                   10546:  '': forbidden
                   10547:  1: user needs to choose course
                   10548:  2: browse allowed
1.766     albertel 10549:  A: passphrase authentication needed
1.243     albertel 10550: 
                   10551: =item *
                   10552: 
                   10553: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10554: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10555: and course level
                   10556: 
                   10557: =item *
                   10558: 
1.988     raeburn  10559: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10560: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10561: $type is Course (default) or Community.
1.988     raeburn  10562: If $forcedefault evaluates to true, text returned will be default 
                   10563: text for $type. Otherwise, if this is a course, the text returned 
                   10564: will be a custom name for the role (if defined in the course's 
                   10565: environment).  If no custom name is defined the default is returned.
                   10566:    
1.832     raeburn  10567: =item *
                   10568: 
1.935     raeburn  10569: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10570: All arguments are optional. Returns a hash of a roles, either for
                   10571: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10572: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10573: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10574: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10575: For each key, value is set to colon-separated start and end times for
                   10576: the role.  If no username and domain are specified, will default to
1.934     raeburn  10577: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10578: of role statuses (active, future or previous), roles 
                   10579: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10580: to restrict the list of roles reported. If no array ref is 
                   10581: provided for types, will default to return only active roles.
1.834     albertel 10582: 
1.243     albertel 10583: =back
                   10584: 
                   10585: =head2 User Modification
                   10586: 
                   10587: =over 4
                   10588: 
                   10589: =item *
                   10590: 
1.957     raeburn  10591: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10592: user for the level given by URL.  Optional start and end dates (leave empty
                   10593: string or zero for "no date")
1.191     harris41 10594: 
                   10595: =item *
                   10596: 
1.243     albertel 10597: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10598: change a users, password, possible return values are: ok,
                   10599: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10600: refused
1.191     harris41 10601: 
                   10602: =item *
                   10603: 
1.243     albertel 10604: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10605: 
                   10606: =item *
                   10607: 
1.1058    raeburn  10608: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10609:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10610: 
                   10611: will update user information (firstname,middlename,lastname,generation,
                   10612: permanentemail), and if forceid is true, student/employee ID also.
                   10613: A user's institutional affiliation(s) can also be updated.
                   10614: User information fields will not be overwritten with empty entries 
                   10615: unless the field is included in the $candelete array reference.
                   10616: This array is included when a single user is modified via "Manage Users",
                   10617: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10618: 
                   10619: =item *
                   10620: 
1.286     matthew  10621: modifystudent
                   10622: 
1.957     raeburn  10623: modify a student's enrollment and identification information.
1.286     matthew  10624: The course id is resolved based on the current users environment.  
                   10625: This means the envoking user must be a course coordinator or otherwise
                   10626: associated with a course.
                   10627: 
1.297     matthew  10628: This call is essentially a wrapper for lonnet::modifyuser and
                   10629: lonnet::modify_student_enrollment
1.286     matthew  10630: 
                   10631: Inputs: 
                   10632: 
                   10633: =over 4
                   10634: 
1.957     raeburn  10635: =item B<$udom> Student's loncapa domain
1.286     matthew  10636: 
1.957     raeburn  10637: =item B<$uname> Student's loncapa login name
1.286     matthew  10638: 
1.964     bisitz   10639: =item B<$uid> Student/Employee ID
1.286     matthew  10640: 
1.957     raeburn  10641: =item B<$umode> Student's authentication mode
1.286     matthew  10642: 
1.957     raeburn  10643: =item B<$upass> Student's password
1.286     matthew  10644: 
1.957     raeburn  10645: =item B<$first> Student's first name
1.286     matthew  10646: 
1.957     raeburn  10647: =item B<$middle> Student's middle name
1.286     matthew  10648: 
1.957     raeburn  10649: =item B<$last> Student's last name
1.286     matthew  10650: 
1.957     raeburn  10651: =item B<$gene> Student's generation
1.286     matthew  10652: 
1.957     raeburn  10653: =item B<$usec> Student's section in course
1.286     matthew  10654: 
                   10655: =item B<$end> Unix time of the roles expiration
                   10656: 
                   10657: =item B<$start> Unix time of the roles start date
                   10658: 
                   10659: =item B<$forceid> If defined, allow $uid to be changed
                   10660: 
                   10661: =item B<$desiredhome> server to use as home server for student
                   10662: 
1.957     raeburn  10663: =item B<$email> Student's permanent e-mail address
                   10664: 
                   10665: =item B<$type> Type of enrollment (auto or manual)
                   10666: 
1.963     raeburn  10667: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10668: 
                   10669: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10670: 
1.963     raeburn  10671: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10672: 
1.963     raeburn  10673: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10674: 
1.963     raeburn  10675: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10676: 
1.286     matthew  10677: =back
1.297     matthew  10678: 
                   10679: =item *
                   10680: 
                   10681: modify_student_enrollment
                   10682: 
                   10683: Change a students enrollment status in a class.  The environment variable
                   10684: 'role.request.course' must be defined for this function to proceed.
                   10685: 
                   10686: Inputs:
                   10687: 
                   10688: =over 4
                   10689: 
                   10690: =item $udom, students domain
                   10691: 
                   10692: =item $uname, students name
                   10693: 
                   10694: =item $uid, students user id
                   10695: 
                   10696: =item $first, students first name
                   10697: 
                   10698: =item $middle
                   10699: 
                   10700: =item $last
                   10701: 
                   10702: =item $gene
                   10703: 
                   10704: =item $usec
                   10705: 
                   10706: =item $end
                   10707: 
                   10708: =item $start
                   10709: 
1.957     raeburn  10710: =item $type
                   10711: 
                   10712: =item $locktype
                   10713: 
                   10714: =item $cid
                   10715: 
                   10716: =item $selfenroll
                   10717: 
                   10718: =item $context
                   10719: 
1.297     matthew  10720: =back
                   10721: 
1.191     harris41 10722: 
                   10723: =item *
                   10724: 
1.243     albertel 10725: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10726: custom role; give a custom role to a user for the level given by URL.  Specify
                   10727: name and domain of role author, and role name
1.191     harris41 10728: 
                   10729: =item *
                   10730: 
1.243     albertel 10731: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10732: 
                   10733: =item *
                   10734: 
1.243     albertel 10735: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10736: 
                   10737: =back
                   10738: 
                   10739: =head2 Course Infomation
                   10740: 
                   10741: =over 4
1.191     harris41 10742: 
                   10743: =item *
                   10744: 
1.631     albertel 10745: coursedescription($courseid) : returns a hash of information about the
                   10746: specified course id, including all environment settings for the
                   10747: course, the description of the course will be in the hash under the
                   10748: key 'description'
1.191     harris41 10749: 
                   10750: =item *
                   10751: 
1.624     albertel 10752: resdata($name,$domain,$type,@which) : request for current parameter
                   10753: setting for a specific $type, where $type is either 'course' or 'user',
                   10754: @what should be a list of parameters to ask about. This routine caches
                   10755: answers for 5 minutes.
1.243     albertel 10756: 
1.877     foxr     10757: =item *
                   10758: 
                   10759: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10760: data base, returning a hash that is keyed by the resource name and has
                   10761: values that are the resource value.  I believe that the timestamps and
                   10762: versions are also returned.
                   10763: 
                   10764: 
1.243     albertel 10765: =back
                   10766: 
                   10767: =head2 Course Modification
                   10768: 
                   10769: =over 4
1.191     harris41 10770: 
                   10771: =item *
                   10772: 
1.243     albertel 10773: writecoursepref($courseid,%prefs) : write preferences (environment
                   10774: database) for a course
1.191     harris41 10775: 
                   10776: =item *
                   10777: 
1.1011    raeburn  10778: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10779: 
                   10780: =item *
                   10781: 
1.1038    raeburn  10782: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10783: 
                   10784: =back
                   10785: 
                   10786: =head2 Resource Subroutines
                   10787: 
                   10788: =over 4
1.191     harris41 10789: 
                   10790: =item *
                   10791: 
1.243     albertel 10792: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10793: 
                   10794: =item *
                   10795: 
1.243     albertel 10796: repcopy($filename) : subscribes to the requested file, and attempts to
                   10797: replicate from the owning library server, Might return
1.607     raeburn  10798: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10799: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10800: resource. Expects the local filesystem pathname
                   10801: (/home/httpd/html/res/....)
                   10802: 
                   10803: =back
                   10804: 
                   10805: =head2 Resource Information
                   10806: 
                   10807: =over 4
1.191     harris41 10808: 
                   10809: =item *
                   10810: 
1.243     albertel 10811: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10812: a vairety of different possible values, $varname should be a request
                   10813: string, and the other parameters can be used to specify who and what
                   10814: one is asking about.
                   10815: 
                   10816: Possible values for $varname are environment.lastname (or other item
                   10817: from the envirnment hash), user.name (or someother aspect about the
                   10818: user), resource.0.maxtries (or some other part and parameter of a
                   10819: resource)
1.204     albertel 10820: 
                   10821: =item *
                   10822: 
1.243     albertel 10823: directcondval($number) : get current value of a condition; reads from a state
                   10824: string
1.204     albertel 10825: 
                   10826: =item *
                   10827: 
1.243     albertel 10828: condval($condidx) : value of condition index based on state
1.204     albertel 10829: 
                   10830: =item *
                   10831: 
1.243     albertel 10832: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10833: resource's metadata, $what should be either a specific key, or either
                   10834: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10835: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10836: 
                   10837: this function automatically caches all requests
1.191     harris41 10838: 
                   10839: =item *
                   10840: 
1.243     albertel 10841: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10842: network of library servers; returns file handle of where SQL and regex results
                   10843: will be stored for query
1.191     harris41 10844: 
                   10845: =item *
                   10846: 
1.243     albertel 10847: symbread($filename) : return symbolic list entry (filename argument optional);
                   10848: returns the data handle
1.191     harris41 10849: 
                   10850: =item *
                   10851: 
1.243     albertel 10852: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10853: a possible symb for the URL in $thisfn, and if is an encryypted
                   10854: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10855: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10856: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10857: 
1.191     harris41 10858: 
                   10859: =item *
                   10860: 
1.243     albertel 10861: symbclean($symb) : removes versions numbers from a symb, returns the
                   10862: cleaned symb
1.191     harris41 10863: 
                   10864: =item *
                   10865: 
1.243     albertel 10866: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10867: course map, user must be in a course for it to work.
1.191     harris41 10868: 
                   10869: =item *
                   10870: 
1.243     albertel 10871: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10872: 
                   10873: =item *
                   10874: 
1.243     albertel 10875: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10876: a random seed, all arguments are optional, if they aren't sent it uses the
                   10877: environment to derive them. Note: if symb isn't sent and it can't get one
                   10878: from &symbread it will use the current time as its return value
1.191     harris41 10879: 
                   10880: =item *
                   10881: 
1.243     albertel 10882: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10883: unfakeable, receipt
1.191     harris41 10884: 
                   10885: =item *
                   10886: 
1.620     albertel 10887: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10888: 
                   10889: =item *
                   10890: 
1.243     albertel 10891: countacc($url) : count the number of accesses to a given URL
1.191     harris41 10892: 
                   10893: =item *
                   10894: 
1.243     albertel 10895: 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 10896: 
                   10897: =item *
                   10898: 
1.243     albertel 10899: 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 10900: 
                   10901: =item *
                   10902: 
1.243     albertel 10903: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 10904: 
                   10905: =item *
                   10906: 
1.243     albertel 10907: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10908: forcing spreadsheet to reevaluate the resource scores next time.
                   10909: 
                   10910: =back
                   10911: 
                   10912: =head2 Storing/Retreiving Data
                   10913: 
                   10914: =over 4
1.191     harris41 10915: 
                   10916: =item *
                   10917: 
1.243     albertel 10918: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   10919: for this url; hashref needs to be given and should be a \%hashname; the
                   10920: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 10921: be derived from the env
1.191     harris41 10922: 
                   10923: =item *
                   10924: 
1.243     albertel 10925: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   10926: uses critical subroutine
1.191     harris41 10927: 
                   10928: =item *
                   10929: 
1.243     albertel 10930: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   10931: all args are optional
1.191     harris41 10932: 
                   10933: =item *
                   10934: 
1.717     albertel 10935: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   10936: dumps the complete (or key matching regexp) namespace into a hash
                   10937: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   10938: normally &store()ed into
                   10939: 
                   10940: $range should be either an integer '100' (give me the first 100
                   10941:                                            matching records)
                   10942:               or be  two integers sperated by a - with no spaces
                   10943:                  '30-50' (give me the 30th through the 50th matching
                   10944:                           records)
                   10945: 
                   10946: 
                   10947: =item *
                   10948: 
                   10949: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   10950: replaces a &store() version of data with a replacement set of data
                   10951: for a particular resource in a namespace passed in the $storehash hash 
                   10952: reference
                   10953: 
                   10954: =item *
                   10955: 
1.243     albertel 10956: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   10957: works very similar to store/cstore, but all data is stored in a
                   10958: temporary location and can be reset using tmpreset, $storehash should
                   10959: be a hash reference, returns nothing on success
1.191     harris41 10960: 
                   10961: =item *
                   10962: 
1.243     albertel 10963: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   10964: similar to restore, but all data is stored in a temporary location and
                   10965: can be reset using tmpreset. Returns a hash of values on success,
                   10966: error string otherwise.
1.191     harris41 10967: 
                   10968: =item *
                   10969: 
1.243     albertel 10970: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   10971: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 10972: 
                   10973: =item *
                   10974: 
1.243     albertel 10975: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10976: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10977: 
                   10978: =item *
                   10979: 
1.243     albertel 10980: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10981: namesp ($udom and $uname are optional)
1.191     harris41 10982: 
                   10983: =item *
                   10984: 
1.702     albertel 10985: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10986: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10987: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10988: 
1.702     albertel 10989: $range should be either an integer '100' (give me the first 100
                   10990:                                            matching records)
                   10991:               or be  two integers sperated by a - with no spaces
                   10992:                  '30-50' (give me the 30th through the 50th matching
                   10993:                           records)
1.449     matthew  10994: =item *
                   10995: 
                   10996: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10997: $store can be a scalar, an array reference, or if the amount to be 
                   10998: incremented is > 1, a hash reference.
                   10999: 
                   11000: ($udom and $uname are optional)
1.191     harris41 11001: 
                   11002: =item *
                   11003: 
1.243     albertel 11004: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11005: ($udom and $uname are optional)
1.191     harris41 11006: 
                   11007: =item *
                   11008: 
1.243     albertel 11009: cput($namespace,$storehash,$udom,$uname) : critical put
                   11010: ($udom and $uname are optional)
1.191     harris41 11011: 
                   11012: =item *
                   11013: 
1.748     albertel 11014: newput($namespace,$storehash,$udom,$uname) :
                   11015: 
                   11016: Attempts to store the items in the $storehash, but only if they don't
                   11017: currently exist, if this succeeds you can be certain that you have 
                   11018: successfully created a new key value pair in the $namespace db.
                   11019: 
                   11020: 
                   11021: Args:
                   11022:  $namespace: name of database to store values to
                   11023:  $storehash: hashref to store to the db
                   11024:  $udom: (optional) domain of user containing the db
                   11025:  $uname: (optional) name of user caontaining the db
                   11026: 
                   11027: Returns:
                   11028:  'ok' -> succeeded in storing all keys of $storehash
                   11029:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11030:                         least <key> already existed in the db (other
                   11031:                         requested keys may also already exist)
1.967     bisitz   11032:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11033:  'con_lost' -> unable to contact request server
                   11034:  'refused' -> action was not allowed by remote machine
                   11035: 
                   11036: 
                   11037: =item *
                   11038: 
1.243     albertel 11039: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11040: reference filled in from namesp (encrypts the return communication)
                   11041: ($udom and $uname are optional)
1.191     harris41 11042: 
                   11043: =item *
                   11044: 
1.243     albertel 11045: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11046: critical subroutine
                   11047: 
1.806     raeburn  11048: =item *
                   11049: 
1.860     raeburn  11050: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11051: array reference filled in from namespace found in domain level on either
                   11052: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11053: 
                   11054: =item *
                   11055: 
1.860     raeburn  11056: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11057: domain level either on specified domain server ($uhome) or primary domain 
                   11058: server ($udom and $uhome are optional)
1.806     raeburn  11059: 
1.943     raeburn  11060: =item * 
                   11061: 
                   11062: get_domain_defaults($target_domain) : returns hash with defaults for
                   11063: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11064: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11065: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11066: Values are retrieved from cache (if current), or from domain's configuration.db
                   11067: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11068: or lonTabs/domain.tab. 
                   11069: 
                   11070: %domdefaults = &get_auth_defaults($target_domain);
                   11071: 
1.243     albertel 11072: =back
                   11073: 
                   11074: =head2 Network Status Functions
                   11075: 
                   11076: =over 4
1.191     harris41 11077: 
                   11078: =item *
                   11079: 
                   11080: dirlist($uri) : return directory list based on URI
                   11081: 
                   11082: =item *
                   11083: 
1.243     albertel 11084: spareserver() : find server with least workload from spare.tab
                   11085: 
1.986     foxr     11086: 
                   11087: =item *
                   11088: 
                   11089: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11090: if there is no corresponding loncapa host.
                   11091: 
1.243     albertel 11092: =back
                   11093: 
1.986     foxr     11094: 
1.243     albertel 11095: =head2 Apache Request
                   11096: 
                   11097: =over 4
1.191     harris41 11098: 
                   11099: =item *
                   11100: 
1.243     albertel 11101: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11102: localhost, posts hash
                   11103: 
                   11104: =back
                   11105: 
                   11106: =head2 Data to String to Data
                   11107: 
                   11108: =over 4
1.191     harris41 11109: 
                   11110: =item *
                   11111: 
1.243     albertel 11112: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11113: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11114: 
                   11115: =item *
                   11116: 
1.243     albertel 11117: hashref2str($hashref) : convert a hashref into a string complete with
                   11118: escaping and '=' and '&' separators, supports elements that are
                   11119: arrayrefs and hashrefs
1.191     harris41 11120: 
                   11121: =item *
                   11122: 
1.243     albertel 11123: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11124: with escaping and '&' separators, supports elements that are arrayrefs
                   11125: and hashrefs
1.191     harris41 11126: 
                   11127: =item *
                   11128: 
1.243     albertel 11129: str2hash($string) : convert string to hash using unescaping and
                   11130: splitting on '=' and '&', supports elements that are arrayrefs and
                   11131: hashrefs
1.191     harris41 11132: 
                   11133: =item *
                   11134: 
1.243     albertel 11135: str2array($string) : convert string to hash using unescaping and
                   11136: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11137: 
                   11138: =back
                   11139: 
                   11140: =head2 Logging Routines
                   11141: 
                   11142: =over 4
                   11143: 
                   11144: These routines allow one to make log messages in the lonnet.log and
                   11145: lonnet.perm logfiles.
1.191     harris41 11146: 
                   11147: =item *
                   11148: 
1.243     albertel 11149: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11150: 
                   11151: =item *
                   11152: 
1.243     albertel 11153: logthis() : append message to the normal lonnet.log file, it gets
                   11154: preiodically rolled over and deleted.
1.191     harris41 11155: 
                   11156: =item *
                   11157: 
1.243     albertel 11158: logperm() : append a permanent message to lonnet.perm.log, this log
                   11159: file never gets deleted by any automated portion of the system, only
                   11160: messages of critical importance should go in here.
                   11161: 
                   11162: =back
                   11163: 
                   11164: =head2 General File Helper Routines
                   11165: 
                   11166: =over 4
1.191     harris41 11167: 
                   11168: =item *
                   11169: 
1.481     raeburn  11170: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11171: (a) files in /uploaded
                   11172:   (i) If a local copy of the file exists - 
                   11173:       compares modification date of local copy with last-modified date for 
                   11174:       definitive version stored on home server for course. If local copy is 
                   11175:       stale, requests a new version from the home server and stores it. 
                   11176:       If the original has been removed from the home server, then local copy 
                   11177:       is unlinked.
                   11178:   (ii) If local copy does not exist -
                   11179:       requests the file from the home server and stores it. 
                   11180:   
                   11181:   If $caller is 'uploadrep':  
                   11182:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11183:     for request for files originally uploaded via DOCS. 
                   11184:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11185:   
                   11186:   Otherwise:
                   11187:      This indicates a call from the content generation phase of the request.
                   11188:      -  returns the entire contents of the file or -1.
                   11189:      
                   11190: (b) files in /res
                   11191:    - returns the entire contents of a file or -1; 
                   11192:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11193: 
1.712     albertel 11194: 
                   11195: =item *
                   11196: 
                   11197: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11198:                   reference
                   11199: 
                   11200: returns either a stat() list of data about the file or an empty list
                   11201: if the file doesn't exist or couldn't find out about it (connection
                   11202: problems or user unknown)
                   11203: 
1.191     harris41 11204: =item *
                   11205: 
1.243     albertel 11206: filelocation($dir,$file) : returns file system location of a file
                   11207: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11208: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11209: and a file of ../bob will become /a/bob)
1.191     harris41 11210: 
                   11211: =item *
                   11212: 
                   11213: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11214: filelocation except for hrefs
                   11215: 
                   11216: =item *
                   11217: 
                   11218: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11219: 
1.243     albertel 11220: =back
                   11221: 
1.608     albertel 11222: =head2 Usererfile file routines (/uploaded*)
                   11223: 
                   11224: =over 4
                   11225: 
                   11226: =item *
                   11227: 
                   11228: userfileupload(): main rotine for putting a file in a user or course's
                   11229:                   filespace, arguments are,
                   11230: 
1.620     albertel 11231:  formname - required - this is the name of the element in $env where the
1.608     albertel 11232:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11233:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11234:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 11235:  coursedoc - if true, store the file in the course of the active role
                   11236:              of the current user
                   11237:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11238:          if undefined, it will be placed in "unknown"
                   11239: 
                   11240:  (This routine calls clean_filename() to remove any dangerous
                   11241:  characters from the filename, and then calls finuserfileupload() to
                   11242:  complete the transaction)
                   11243: 
                   11244:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11245:  and /adm/notfound.html if unsuccessful
                   11246: 
                   11247: =item *
                   11248: 
                   11249: clean_filename(): routine for cleaing a filename up for storage in
                   11250:                  userfile space, argument is:
                   11251: 
                   11252:  filename - proposed filename
                   11253: 
                   11254: returns: the new clean filename
                   11255: 
                   11256: =item *
                   11257: 
                   11258: finishuserfileupload(): routine that creaes and sends the file to
                   11259: userspace, probably shouldn't be called directly
                   11260: 
                   11261:   docuname: username or courseid of destination for the file
                   11262:   docudom: domain of user/course of destination for the file
                   11263:   formname: same as for userfileupload()
                   11264:   fname: filename (inculding subdirectories) for the file
                   11265: 
                   11266:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11267:  and /adm/notfound.html if unsuccessful
                   11268: 
                   11269: =item *
                   11270: 
                   11271: renameuserfile(): renames an existing userfile to a new name
                   11272: 
                   11273:   Args:
                   11274:    docuname: username or courseid of destination for the file
                   11275:    docudom: domain of user/course of destination for the file
                   11276:    old: current file name (including any subdirs under userfiles)
                   11277:    new: desired file name (including any subdirs under userfiles)
                   11278: 
                   11279: =item *
                   11280: 
                   11281: mkdiruserfile(): creates a directory is a userfiles dir
                   11282: 
                   11283:   Args:
                   11284:    docuname: username or courseid of destination for the file
                   11285:    docudom: domain of user/course of destination for the file
                   11286:    dir: dir to create (including any subdirs under userfiles)
                   11287: 
                   11288: =item *
                   11289: 
                   11290: removeuserfile(): removes a file that exists in userfiles
                   11291: 
                   11292:   Args:
                   11293:    docuname: username or courseid of destination for the file
                   11294:    docudom: domain of user/course of destination for the file
                   11295:    fname: filname to delete (including any subdirs under userfiles)
                   11296: 
                   11297: =item *
                   11298: 
                   11299: removeuploadedurl(): convience function for removeuserfile()
                   11300: 
                   11301:   Args:
                   11302:    url:  a full /uploaded/... url to delete
                   11303: 
1.747     albertel 11304: =item * 
                   11305: 
                   11306: get_portfile_permissions():
                   11307:   Args:
                   11308:     domain: domain of user or course contain the portfolio files
                   11309:     user: name of user or num of course contain the portfolio files
                   11310:   Returns:
                   11311:     hashref of a dump of the proper file_permissions.db
                   11312:    
                   11313: 
                   11314: =item * 
                   11315: 
                   11316: get_access_controls():
                   11317: 
                   11318: Args:
                   11319:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11320:   group: (optional) the group you want the files associated with
                   11321:   file: (optional) the file you want access info on
                   11322: 
                   11323: Returns:
1.749     raeburn  11324:     a hash (keys are file names) of hashes containing
                   11325:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11326:         values are XML containing access control settings (see below) 
1.747     albertel 11327: 
                   11328: Internal notes:
                   11329: 
1.749     raeburn  11330:  access controls are stored in file_permissions.db as key=value pairs.
                   11331:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11332:         where scope -> public,guest,course,group,domains or users.
                   11333:               end -> UNIX time for end of access (0 -> no end date)
                   11334:               start -> UNIX time for start of access
                   11335: 
                   11336:     value -> XML description of access control
                   11337:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11338:             <start></start>
                   11339:             <end></end>
                   11340: 
                   11341:             <password></password>  for scope type = guest
                   11342: 
                   11343:             <domain></domain>     for scope type = course or group
                   11344:             <number></number>
                   11345:             <roles id="">
                   11346:              <role></role>
                   11347:              <access></access>
                   11348:              <section></section>
                   11349:              <group></group>
                   11350:             </roles>
                   11351: 
                   11352:             <dom></dom>         for scope type = domains
                   11353: 
                   11354:             <users>             for scope type = users
                   11355:              <user>
                   11356:               <uname></uname>
                   11357:               <udom></udom>
                   11358:              </user>
                   11359:             </users>
                   11360:            </scope> 
                   11361:               
                   11362:  Access data is also aggregated for each file in an additional key=value pair:
                   11363:  key -> path to file/file_name\0accesscontrol 
                   11364:  value -> reference to hash
                   11365:           hash contains key = value pairs
                   11366:           where key = uniqueID:scope_end_start
                   11367:                 value = UNIX time record was last updated
                   11368: 
                   11369:           Used to improve speed of look-ups of access controls for each file.  
                   11370:  
                   11371:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11372: 
                   11373: modify_access_controls():
                   11374: 
                   11375: Modifies access controls for a portfolio file
                   11376: Args
                   11377: 1. file name
                   11378: 2. reference to hash of required changes,
                   11379: 3. domain
                   11380: 4. username
                   11381:   where domain,username are the domain of the portfolio owner 
                   11382:   (either a user or a course) 
                   11383: 
                   11384: Returns:
                   11385: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11386: 2. result of deletions ('ok' or 'error', with error message).
                   11387: 3. reference to hash of any new or updated access controls.
                   11388: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11389:    key = integer (inbound ID)
                   11390:    value = uniqueID  
1.747     albertel 11391: 
1.608     albertel 11392: =back
                   11393: 
1.243     albertel 11394: =head2 HTTP Helper Routines
                   11395: 
                   11396: =over 4
                   11397: 
1.191     harris41 11398: =item *
                   11399: 
                   11400: escape() : unpack non-word characters into CGI-compatible hex codes
                   11401: 
                   11402: =item *
                   11403: 
                   11404: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11405: 
1.243     albertel 11406: =back
                   11407: 
                   11408: =head1 PRIVATE SUBROUTINES
                   11409: 
                   11410: =head2 Underlying communication routines (Shouldn't call)
                   11411: 
                   11412: =over 4
                   11413: 
                   11414: =item *
                   11415: 
                   11416: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11417: 
                   11418: =item *
                   11419: 
                   11420: reply() : uses subreply to send a message to remote machine, logs all failures
                   11421: 
                   11422: =item *
                   11423: 
                   11424: critical() : passes a critical message to another server; if cannot
                   11425: get through then place message in connection buffer directory and
                   11426: returns con_delayed, if incapable of saving message, returns
                   11427: con_failed
                   11428: 
                   11429: =item *
                   11430: 
                   11431: reconlonc() : tries to reconnect lonc client processes.
                   11432: 
                   11433: =back
                   11434: 
                   11435: =head2 Resource Access Logging
                   11436: 
                   11437: =over 4
                   11438: 
                   11439: =item *
                   11440: 
                   11441: flushcourselogs() : flush (save) buffer logs and access logs
                   11442: 
                   11443: =item *
                   11444: 
                   11445: courselog($what) : save message for course in hash
                   11446: 
                   11447: =item *
                   11448: 
                   11449: courseacclog($what) : save message for course using &courselog().  Perform
                   11450: special processing for specific resource types (problems, exams, quizzes, etc).
                   11451: 
1.191     harris41 11452: =item *
                   11453: 
                   11454: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11455: as a PerlChildExitHandler
1.243     albertel 11456: 
                   11457: =back
                   11458: 
                   11459: =head2 Other
                   11460: 
                   11461: =over 4
                   11462: 
                   11463: =item *
                   11464: 
                   11465: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11466: 
                   11467: =back
                   11468: 
                   11469: =cut
1.877     foxr     11470: 

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