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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1075  ! raeburn     4: # $Id: lonnet.pm,v 1.1074 2010/07/20 02:42:47 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.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.202     matthew   815: # --------------------------------------------- Try to change a user's password
                    816: 
                    817: sub changepass {
1.799     raeburn   818:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   819:     $currentpass = &escape($currentpass);
                    820:     $newpass     = &escape($newpass);
1.1030    raeburn   821:     my $lonhost = $perlvar{'lonHostID'};
                    822:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   823: 		       $server);
                    824:     if (! $answer) {
                    825: 	&logthis("No reply on password change request to $server ".
                    826: 		 "by $uname in domain $udom.");
                    827:     } elsif ($answer =~ "^ok") {
                    828:         &logthis("$uname in $udom successfully changed their password ".
                    829: 		 "on $server.");
                    830:     } elsif ($answer =~ "^pwchange_failure") {
                    831: 	&logthis("$uname in $udom was unable to change their password ".
                    832: 		 "on $server.  The action was blocked by either lcpasswd ".
                    833: 		 "or pwchange");
                    834:     } elsif ($answer =~ "^non_authorized") {
                    835:         &logthis("$uname in $udom did not get their password correct when ".
                    836: 		 "attempting to change it on $server.");
                    837:     } elsif ($answer =~ "^auth_mode_error") {
                    838:         &logthis("$uname in $udom attempted to change their password despite ".
                    839: 		 "not being locally or internally authenticated on $server.");
                    840:     } elsif ($answer =~ "^unknown_user") {
                    841:         &logthis("$uname in $udom attempted to change their password ".
                    842: 		 "on $server but were unable to because $server is not ".
                    843: 		 "their home server.");
                    844:     } elsif ($answer =~ "^refused") {
                    845: 	&logthis("$server refused to change $uname in $udom password because ".
                    846: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   847:     } elsif ($answer =~ "invalid_client") {
                    848:         &logthis("$server refused to change $uname in $udom password because ".
                    849:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   850:     }
                    851:     return $answer;
1.1       albertel  852: }
                    853: 
1.169     harris41  854: # ----------------------- Try to determine user's current authentication scheme
                    855: 
                    856: sub queryauthenticate {
                    857:     my ($uname,$udom)=@_;
1.456     albertel  858:     my $uhome=&homeserver($uname,$udom);
                    859:     if (!$uhome) {
                    860: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    861: 	return 'no_host';
                    862:     }
                    863:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    864:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    865: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  866:     }
1.456     albertel  867:     return $answer;
1.169     harris41  868: }
                    869: 
1.1       albertel  870: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       871: 
1.1       albertel  872: sub authenticate {
1.1073    raeburn   873:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  874:     $upass=&escape($upass);
                    875:     $uname= &LONCAPA::clean_username($uname);
1.836     www       876:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   877:     my $newhome;
1.836     www       878:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    879: # Maybe the machine was offline and only re-appeared again recently?
                    880:         &reconlonc();
                    881: # One more
1.952     raeburn   882: 	$uhome=&homeserver($uname,$udom,1);
                    883:         if (($uhome eq 'no_host') && $checkdefauth) {
                    884:             if (defined(&domain($udom,'primary'))) {
                    885:                 $newhome=&domain($udom,'primary');
                    886:             }
                    887:             if ($newhome ne '') {
                    888:                 $uhome = $newhome;
                    889:             }
                    890:         }
1.836     www       891: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    892: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   893: 	    return 'no_host';
                    894:         }
1.1       albertel  895:     }
1.1073    raeburn   896:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  897:     if ($answer eq 'authorized') {
1.952     raeburn   898:         if ($newhome) {
                    899:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    900:             return 'no_account_on_host'; 
                    901:         } else {
                    902:             &logthis("User $uname at $udom authorized by $uhome");
                    903:             return $uhome;
                    904:         }
1.471     albertel  905:     }
                    906:     if ($answer eq 'non_authorized') {
                    907: 	&logthis("User $uname at $udom rejected by $uhome");
                    908: 	return 'no_host'; 
1.9       www       909:     }
1.471     albertel  910:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  911:     return 'no_host';
                    912: }
                    913: 
1.1073    raeburn   914: sub can_host_session {
1.1074    raeburn   915:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn   916:     my $canhost = 1;
1.1074    raeburn   917:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn   918:     if (ref($remotesessions) eq 'HASH') {
                    919:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn   920:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn   921:                 $canhost = 0;
                    922:             } else {
                    923:                 $canhost = 1;
                    924:             }
                    925:         }
                    926:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn   927:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn   928:                 $canhost = 1;
                    929:             } else {
                    930:                 $canhost = 0;
                    931:             }
                    932:         }
                    933:         if ($canhost) {
                    934:             if ($remotesessions->{'version'} ne '') {
                    935:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                    936:                 if ($reqmajor ne '' && $reqminor ne '') {
                    937:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                    938:                         my $major = $1;
                    939:                         my $minor = $2;
                    940:                         if (($major < $reqmajor ) ||
                    941:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                    942:                             $canhost = 0;
                    943:                         }
                    944:                     } else {
                    945:                         $canhost = 0;
                    946:                     }
                    947:                 }
                    948:             }
                    949:         }
                    950:     }
                    951:     if ($canhost) {
                    952:         if (ref($hostedsessions) eq 'HASH') {
                    953:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                    954:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                    955:                     $canhost = 0;
                    956:                 } else {
                    957:                     $canhost = 1;
                    958:                 }
                    959:             }
                    960:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                    961:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                    962:                     $canhost = 1;
                    963:                 } else {
                    964:                     $canhost = 0;
                    965:                 }
                    966:             }
                    967:         }
                    968:     }
                    969:     return $canhost;
                    970: }
                    971: 
1.1       albertel  972: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       973: 
1.599     albertel  974: my %homecache;
1.1       albertel  975: sub homeserver {
1.230     stredwic  976:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  977:     my $index="$uname:$udom";
1.426     albertel  978: 
1.599     albertel  979:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  980: 
                    981:     my %servers = &get_servers($udom,'library');
                    982:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  983:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  984: 		 exists($badServerCache{$tryserver}));
1.841     albertel  985: 
                    986: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    987: 	if ($answer eq 'found') {
                    988: 	    delete($badServerCache{$tryserver}); 
                    989: 	    return $homecache{$index}=$tryserver;
                    990: 	} elsif ($answer eq 'no_host') {
                    991: 	    $badServerCache{$tryserver}=1;
                    992: 	}
1.1       albertel  993:     }    
                    994:     return 'no_host';
1.70      www       995: }
                    996: 
                    997: # ------------------------------------- Find the usernames behind a list of IDs
                    998: 
                    999: sub idget {
                   1000:     my ($udom,@ids)=@_;
                   1001:     my %returnhash=();
                   1002:     
1.841     albertel 1003:     my %servers = &get_servers($udom,'library');
                   1004:     foreach my $tryserver (keys(%servers)) {
                   1005: 	my $idlist=join('&',@ids);
                   1006: 	$idlist=~tr/A-Z/a-z/; 
                   1007: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1008: 	my @answer=();
                   1009: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1010: 	    @answer=split(/\&/,$reply);
                   1011: 	}                    ;
                   1012: 	my $i;
                   1013: 	for ($i=0;$i<=$#ids;$i++) {
                   1014: 	    if ($answer[$i]) {
                   1015: 		$returnhash{$ids[$i]}=$answer[$i];
                   1016: 	    } 
                   1017: 	}
                   1018:     } 
1.70      www      1019:     return %returnhash;
                   1020: }
                   1021: 
                   1022: # ------------------------------------- Find the IDs behind a list of usernames
                   1023: 
                   1024: sub idrget {
                   1025:     my ($udom,@unames)=@_;
                   1026:     my %returnhash=();
1.800     albertel 1027:     foreach my $uname (@unames) {
                   1028:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1029:     }
1.70      www      1030:     return %returnhash;
                   1031: }
                   1032: 
                   1033: # ------------------------------- Store away a list of names and associated IDs
                   1034: 
                   1035: sub idput {
                   1036:     my ($udom,%ids)=@_;
                   1037:     my %servers=();
1.800     albertel 1038:     foreach my $uname (keys(%ids)) {
                   1039: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1040:         my $uhom=&homeserver($uname,$udom);
1.70      www      1041:         if ($uhom ne 'no_host') {
1.800     albertel 1042:             my $id=&escape($ids{$uname});
1.70      www      1043:             $id=~tr/A-Z/a-z/;
1.800     albertel 1044:             my $esc_unam=&escape($uname);
1.70      www      1045: 	    if ($servers{$uhom}) {
1.800     albertel 1046: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1047:             } else {
1.800     albertel 1048:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1049:             }
                   1050:         }
1.191     harris41 1051:     }
1.800     albertel 1052:     foreach my $server (keys(%servers)) {
                   1053:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1054:     }
1.344     www      1055: }
                   1056: 
1.1023    raeburn  1057: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1058: sub dump_dom {
1.1023    raeburn  1059:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1060:     if (!$udom) {
                   1061:         $udom=$env{'user.domain'};
                   1062:     }
                   1063:     my %returnhash;
1.1023    raeburn  1064:     if ($udom) {
                   1065:         my $uname = &get_domainconfiguser($udom);
                   1066:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1067:     }
                   1068:     return %returnhash;
                   1069: }
                   1070: 
1.1023    raeburn  1071: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1072: 
                   1073: sub get_dom {
1.860     raeburn  1074:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1075:     my $items='';
                   1076:     foreach my $item (@$storearr) {
                   1077:         $items.=&escape($item).'&';
                   1078:     }
                   1079:     $items=~s/\&$//;
1.860     raeburn  1080:     if (!$udom) {
                   1081:         $udom=$env{'user.domain'};
                   1082:         if (defined(&domain($udom,'primary'))) {
                   1083:             $uhome=&domain($udom,'primary');
                   1084:         } else {
1.874     albertel 1085:             undef($uhome);
1.860     raeburn  1086:         }
                   1087:     } else {
                   1088:         if (!$uhome) {
                   1089:             if (defined(&domain($udom,'primary'))) {
                   1090:                 $uhome=&domain($udom,'primary');
                   1091:             }
                   1092:         }
                   1093:     }
                   1094:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1095:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1096:         my %returnhash;
1.875     albertel 1097:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1098:             return %returnhash;
                   1099:         }
1.806     raeburn  1100:         my @pairs=split(/\&/,$rep);
                   1101:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1102:             return @pairs;
                   1103:         }
                   1104:         my $i=0;
                   1105:         foreach my $item (@$storearr) {
                   1106:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1107:             $i++;
                   1108:         }
                   1109:         return %returnhash;
                   1110:     } else {
1.880     banghart 1111:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1112:     }
                   1113: }
                   1114: 
                   1115: # -------------------------------------------- put items in domain db files 
                   1116: 
                   1117: sub put_dom {
1.860     raeburn  1118:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1119:     if (!$udom) {
                   1120:         $udom=$env{'user.domain'};
                   1121:         if (defined(&domain($udom,'primary'))) {
                   1122:             $uhome=&domain($udom,'primary');
                   1123:         } else {
1.874     albertel 1124:             undef($uhome);
1.860     raeburn  1125:         }
                   1126:     } else {
                   1127:         if (!$uhome) {
                   1128:             if (defined(&domain($udom,'primary'))) {
                   1129:                 $uhome=&domain($udom,'primary');
                   1130:             }
                   1131:         }
                   1132:     } 
                   1133:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1134:         my $items='';
                   1135:         foreach my $item (keys(%$storehash)) {
                   1136:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1137:         }
                   1138:         $items=~s/\&$//;
                   1139:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1140:     } else {
1.860     raeburn  1141:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1142:     }
                   1143: }
                   1144: 
1.1023    raeburn  1145: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1146: sub newput_dom {
1.1023    raeburn  1147:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1148:     my $result;
                   1149:     if (!$udom) {
                   1150:         $udom=$env{'user.domain'};
                   1151:     }
1.1023    raeburn  1152:     if ($udom) {
                   1153:         my $uname = &get_domainconfiguser($udom);
                   1154:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1155:     }
                   1156:     return $result;
                   1157: }
                   1158: 
1.1023    raeburn  1159: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1160: sub del_dom {
1.1023    raeburn  1161:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1162:     if (ref($storearr) eq 'ARRAY') {
                   1163:         if (!$udom) {
                   1164:             $udom=$env{'user.domain'};
                   1165:         }
1.1023    raeburn  1166:         if ($udom) {
                   1167:             my $uname = &get_domainconfiguser($udom); 
                   1168:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1169:         }
                   1170:     }
                   1171: }
                   1172: 
1.1023    raeburn  1173: # ----------------------------------construct domainconfig user for a domain 
                   1174: sub get_domainconfiguser {
                   1175:     my ($udom) = @_;
                   1176:     return $udom.'-domainconfig';
                   1177: }
                   1178: 
1.837     raeburn  1179: sub retrieve_inst_usertypes {
                   1180:     my ($udom) = @_;
                   1181:     my (%returnhash,@order);
1.989     raeburn  1182:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1183:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1184:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1185:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1186:         @order = @{$domdefs{'inststatusorder'}};
                   1187:     } else {
                   1188:         if (defined(&domain($udom,'primary'))) {
                   1189:             my $uhome=&domain($udom,'primary');
                   1190:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1191:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1192:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1193:                 return (\%returnhash,\@order);
                   1194:             }
                   1195:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1196:             my @pairs=split(/\&/,$hashitems);
                   1197:             foreach my $item (@pairs) {
                   1198:                 my ($key,$value)=split(/=/,$item,2);
                   1199:                 $key = &unescape($key);
                   1200:                 next if ($key =~ /^error: 2 /);
                   1201:                 $returnhash{$key}=&thaw_unescape($value);
                   1202:             }
                   1203:             my @esc_order = split(/\&/,$orderitems);
                   1204:             foreach my $item (@esc_order) {
                   1205:                 push(@order,&unescape($item));
                   1206:             }
                   1207:         } else {
                   1208:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1209:         }
                   1210:     }
                   1211:     return (\%returnhash,\@order);
                   1212: }
                   1213: 
1.868     raeburn  1214: sub is_domainimage {
                   1215:     my ($url) = @_;
                   1216:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1217:         if (&domain($1) ne '') {
                   1218:             return '1';
                   1219:         }
                   1220:     }
                   1221:     return;
                   1222: }
                   1223: 
1.899     raeburn  1224: sub inst_directory_query {
                   1225:     my ($srch) = @_;
                   1226:     my $udom = $srch->{'srchdomain'};
                   1227:     my %results;
                   1228:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1229:     my $outcome;
1.899     raeburn  1230:     if ($homeserver ne '') {
1.904     albertel 1231: 	my $queryid=&reply("querysend:instdirsearch:".
                   1232: 			   &escape($srch->{'srchby'}).':'.
                   1233: 			   &escape($srch->{'srchterm'}).':'.
                   1234: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1235: 	my $host=&hostname($homeserver);
                   1236: 	if ($queryid !~/^\Q$host\E\_/) {
                   1237: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1238: 	    return;
                   1239: 	}
                   1240: 	my $response = &get_query_reply($queryid);
                   1241: 	my $maxtries = 5;
                   1242: 	my $tries = 1;
                   1243: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1244: 	    $response = &get_query_reply($queryid);
                   1245: 	    $tries ++;
                   1246: 	}
                   1247: 
                   1248:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1249:             if ($response eq 'unavailable') {
                   1250:                 $outcome = $response;
                   1251:             } else {
                   1252:                 $outcome = 'ok';
                   1253:                 my @matches = split(/\n/,$response);
                   1254:                 foreach my $match (@matches) {
                   1255:                     my ($key,$value) = split(/=/,$match);
                   1256:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1257:                 }
1.899     raeburn  1258:             }
                   1259:         }
                   1260:     }
1.909     raeburn  1261:     return ($outcome,%results);
1.899     raeburn  1262: }
                   1263: 
                   1264: sub usersearch {
                   1265:     my ($srch) = @_;
                   1266:     my $dom = $srch->{'srchdomain'};
                   1267:     my %results;
                   1268:     my %libserv = &all_library();
                   1269:     my $query = 'usersearch';
                   1270:     foreach my $tryserver (keys(%libserv)) {
                   1271:         if (&host_domain($tryserver) eq $dom) {
                   1272:             my $host=&hostname($tryserver);
                   1273:             my $queryid=
1.911     raeburn  1274:                 &reply("querysend:".&escape($query).':'.
                   1275:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1276:                        &escape($srch->{'srchtype'}).':'.
                   1277:                        &escape($srch->{'srchterm'}),$tryserver);
                   1278:             if ($queryid !~/^\Q$host\E\_/) {
                   1279:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1280:                 next;
1.899     raeburn  1281:             }
                   1282:             my $reply = &get_query_reply($queryid);
                   1283:             my $maxtries = 1;
                   1284:             my $tries = 1;
                   1285:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1286:                 $reply = &get_query_reply($queryid);
                   1287:                 $tries ++;
                   1288:             }
                   1289:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1290:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1291:             } else {
1.911     raeburn  1292:                 my @matches;
                   1293:                 if ($reply =~ /\n/) {
                   1294:                     @matches = split(/\n/,$reply);
                   1295:                 } else {
                   1296:                     @matches = split(/\&/,$reply);
                   1297:                 }
1.899     raeburn  1298:                 foreach my $match (@matches) {
                   1299:                     my ($uname,$udom,%userhash);
1.911     raeburn  1300:                     foreach my $entry (split(/:/,$match)) {
                   1301:                         my ($key,$value) =
                   1302:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1303:                         $userhash{$key} = $value;
                   1304:                         if ($key eq 'username') {
                   1305:                             $uname = $value;
                   1306:                         } elsif ($key eq 'domain') {
                   1307:                             $udom = $value;
1.911     raeburn  1308:                         }
1.899     raeburn  1309:                     }
                   1310:                     $results{$uname.':'.$udom} = \%userhash;
                   1311:                 }
                   1312:             }
                   1313:         }
                   1314:     }
                   1315:     return %results;
                   1316: }
                   1317: 
1.912     raeburn  1318: sub get_instuser {
                   1319:     my ($udom,$uname,$id) = @_;
                   1320:     my $homeserver = &domain($udom,'primary');
                   1321:     my ($outcome,%results);
                   1322:     if ($homeserver ne '') {
                   1323:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1324:                            &escape($id).':'.&escape($udom),$homeserver);
                   1325:         my $host=&hostname($homeserver);
                   1326:         if ($queryid !~/^\Q$host\E\_/) {
                   1327:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1328:             return;
                   1329:         }
                   1330:         my $response = &get_query_reply($queryid);
                   1331:         my $maxtries = 5;
                   1332:         my $tries = 1;
                   1333:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1334:             $response = &get_query_reply($queryid);
                   1335:             $tries ++;
                   1336:         }
                   1337:         if (!&error($response) && $response ne 'refused') {
                   1338:             if ($response eq 'unavailable') {
                   1339:                 $outcome = $response;
                   1340:             } else {
                   1341:                 $outcome = 'ok';
                   1342:                 my @matches = split(/\n/,$response);
                   1343:                 foreach my $match (@matches) {
                   1344:                     my ($key,$value) = split(/=/,$match);
                   1345:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1346:                 }
                   1347:             }
                   1348:         }
                   1349:     }
                   1350:     my %userinfo;
                   1351:     if (ref($results{$uname}) eq 'HASH') {
                   1352:         %userinfo = %{$results{$uname}};
                   1353:     } 
                   1354:     return ($outcome,%userinfo);
                   1355: }
                   1356: 
                   1357: sub inst_rulecheck {
1.923     raeburn  1358:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1359:     my %returnhash;
                   1360:     if ($udom ne '') {
                   1361:         if (ref($rules) eq 'ARRAY') {
                   1362:             @{$rules} = map {&escape($_);} (@{$rules});
                   1363:             my $rulestr = join(':',@{$rules});
                   1364:             my $homeserver=&domain($udom,'primary');
                   1365:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1366:                 my $response;
                   1367:                 if ($item eq 'username') {                
                   1368:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1369:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1370:                                               $homeserver));
1.923     raeburn  1371:                 } elsif ($item eq 'id') {
                   1372:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1373:                                               ':'.&escape($id).':'.$rulestr,
                   1374:                                               $homeserver));
1.945     raeburn  1375:                 } elsif ($item eq 'selfcreate') {
                   1376:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1377:                                                &escape($udom).':'.&escape($uname).
                   1378:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1379:                 }
1.912     raeburn  1380:                 if ($response ne 'refused') {
                   1381:                     my @pairs=split(/\&/,$response);
                   1382:                     foreach my $item (@pairs) {
                   1383:                         my ($key,$value)=split(/=/,$item,2);
                   1384:                         $key = &unescape($key);
                   1385:                         next if ($key =~ /^error: 2 /);
                   1386:                         $returnhash{$key}=&thaw_unescape($value);
                   1387:                     }
                   1388:                 }
                   1389:             }
                   1390:         }
                   1391:     }
                   1392:     return %returnhash;
                   1393: }
                   1394: 
                   1395: sub inst_userrules {
1.923     raeburn  1396:     my ($udom,$check) = @_;
1.912     raeburn  1397:     my (%ruleshash,@ruleorder);
                   1398:     if ($udom ne '') {
                   1399:         my $homeserver=&domain($udom,'primary');
                   1400:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1401:             my $response;
                   1402:             if ($check eq 'id') {
                   1403:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1404:                                  $homeserver);
1.943     raeburn  1405:             } elsif ($check eq 'email') {
                   1406:                 $response=&reply('instemailrules:'.&escape($udom),
                   1407:                                  $homeserver);
1.923     raeburn  1408:             } else {
                   1409:                 $response=&reply('instuserrules:'.&escape($udom),
                   1410:                                  $homeserver);
                   1411:             }
1.912     raeburn  1412:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1413:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1414:                 ($response ne 'no_such_host')) {
                   1415:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1416:                 my @pairs=split(/\&/,$hashitems);
                   1417:                 foreach my $item (@pairs) {
                   1418:                     my ($key,$value)=split(/=/,$item,2);
                   1419:                     $key = &unescape($key);
                   1420:                     next if ($key =~ /^error: 2 /);
                   1421:                     $ruleshash{$key}=&thaw_unescape($value);
                   1422:                 }
                   1423:                 my @esc_order = split(/\&/,$orderitems);
                   1424:                 foreach my $item (@esc_order) {
                   1425:                     push(@ruleorder,&unescape($item));
                   1426:                 }
                   1427:             }
                   1428:         }
                   1429:     }
                   1430:     return (\%ruleshash,\@ruleorder);
                   1431: }
                   1432: 
1.976     raeburn  1433: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1434: 
                   1435: sub get_domain_defaults {
                   1436:     my ($domain) = @_;
                   1437:     my $cachetime = 60*60*24;
                   1438:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1439:     if (defined($cached)) {
                   1440:         if (ref($result) eq 'HASH') {
                   1441:             return %{$result};
                   1442:         }
                   1443:     }
                   1444:     my %domdefaults;
                   1445:     my %domconfig =
1.989     raeburn  1446:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1447:                                   'requestcourses','inststatus',
1.1073    raeburn  1448:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1449:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1450:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1451:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1452:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1453:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1454:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1455:     } else {
                   1456:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1457:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1458:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1459:     }
1.976     raeburn  1460:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1461:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1462:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1463:         } else {
                   1464:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1465:         } 
                   1466:         my @usertools = ('aboutme','blog','portfolio');
                   1467:         foreach my $item (@usertools) {
                   1468:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1469:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1470:             }
                   1471:         }
                   1472:     }
1.985     raeburn  1473:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1474:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1475:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1476:         }
                   1477:     }
1.989     raeburn  1478:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1479:         foreach my $item ('inststatustypes','inststatusorder') {
                   1480:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1481:         }
                   1482:     }
1.1047    raeburn  1483:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1484:         foreach my $item ('canuse_pdfforms') {
                   1485:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1486:         }
                   1487:     }
1.1073    raeburn  1488:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1489:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1490:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1491:         }
                   1492:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1493:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1494:         }
                   1495:     }
1.943     raeburn  1496:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1497:                                   $cachetime);
                   1498:     return %domdefaults;
                   1499: }
                   1500: 
1.344     www      1501: # --------------------------------------------------- Assign a key to a student
                   1502: 
                   1503: sub assign_access_key {
1.364     www      1504: #
                   1505: # a valid key looks like uname:udom#comments
                   1506: # comments are being appended
                   1507: #
1.498     www      1508:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1509:     $kdom=
1.620     albertel 1510:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1511:     $knum=
1.620     albertel 1512:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1513:     $cdom=
1.620     albertel 1514:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1515:     $cnum=
1.620     albertel 1516:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1517:     $udom=$env{'user.name'} unless (defined($udom));
                   1518:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1519:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1520:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1521:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1522:                                                   # assigned to this person
                   1523:                                                   # - this should not happen,
1.345     www      1524:                                                   # unless something went wrong
                   1525:                                                   # the first time around
                   1526: # ready to assign
1.364     www      1527:         $logentry=$1.'; '.$logentry;
1.496     www      1528:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1529:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1530: # key now belongs to user
1.346     www      1531: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1532:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1533:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1534:                 return 'ok';
                   1535:             } else {
                   1536:                 return 
                   1537:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1538: 	    }
                   1539:         } else {
                   1540:             return 'error: Could not assign key, try again later.';
                   1541:         }
1.364     www      1542:     } elsif (!$existing{$ckey}) {
1.345     www      1543: # the key does not exist
                   1544: 	return 'error: The key does not exist';
                   1545:     } else {
                   1546: # the key is somebody else's
                   1547: 	return 'error: The key is already in use';
                   1548:     }
1.344     www      1549: }
                   1550: 
1.364     www      1551: # ------------------------------------------ put an additional comment on a key
                   1552: 
                   1553: sub comment_access_key {
                   1554: #
                   1555: # a valid key looks like uname:udom#comments
                   1556: # comments are being appended
                   1557: #
                   1558:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1559:     $cdom=
1.620     albertel 1560:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1561:     $cnum=
1.620     albertel 1562:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1563:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1564:     if ($existing{$ckey}) {
                   1565:         $existing{$ckey}.='; '.$logentry;
                   1566: # ready to assign
1.367     www      1567:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1568:                                                  $cdom,$cnum) eq 'ok') {
                   1569: 	    return 'ok';
                   1570:         } else {
                   1571: 	    return 'error: Count not store comment.';
                   1572:         }
                   1573:     } else {
                   1574: # the key does not exist
                   1575: 	return 'error: The key does not exist';
                   1576:     }
                   1577: }
                   1578: 
1.344     www      1579: # ------------------------------------------------------ Generate a set of keys
                   1580: 
                   1581: sub generate_access_keys {
1.364     www      1582:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1583:     $cdom=
1.620     albertel 1584:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1585:     $cnum=
1.620     albertel 1586:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1587:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1588:     unless (($cdom) && ($cnum)) { return 0; }
                   1589:     if ($number>10000) { return 0; }
                   1590:     sleep(2); # make sure don't get same seed twice
                   1591:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1592:     my $total=0;
                   1593:     for (my $i=1;$i<=$number;$i++) {
                   1594:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1595:                   sprintf("%lx",int(100000*rand)).'-'.
                   1596:                   sprintf("%lx",int(100000*rand));
                   1597:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1598:        $newkey=~s/0/h/g; # and also 0 and O
                   1599:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1600:        if ($existing{$newkey}) {
                   1601:            $i--;
                   1602:        } else {
1.364     www      1603: 	  if (&put('accesskeys',
                   1604:               { $newkey => '# generated '.localtime().
1.620     albertel 1605:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1606:                            '; '.$logentry },
                   1607: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1608:               $total++;
                   1609: 	  }
                   1610:        }
                   1611:     }
1.620     albertel 1612:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1613:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1614:     return $total;
                   1615: }
                   1616: 
                   1617: # ------------------------------------------------------- Validate an accesskey
                   1618: 
                   1619: sub validate_access_key {
                   1620:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1621:     $cdom=
1.620     albertel 1622:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1623:     $cnum=
1.620     albertel 1624:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1625:     $udom=$env{'user.domain'} unless (defined($udom));
                   1626:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1627:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1628:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1629: }
                   1630: 
                   1631: # ------------------------------------- Find the section of student in a course
1.652     albertel 1632: sub devalidate_getsection_cache {
                   1633:     my ($udom,$unam,$courseid)=@_;
                   1634:     my $hashid="$udom:$unam:$courseid";
                   1635:     &devalidate_cache_new('getsection',$hashid);
                   1636: }
1.298     matthew  1637: 
1.815     albertel 1638: sub courseid_to_courseurl {
                   1639:     my ($courseid) = @_;
                   1640:     #already url style courseid
                   1641:     return $courseid if ($courseid =~ m{^/});
                   1642: 
                   1643:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1644: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1645: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1646: 	return "/$cdom/$cnum";
                   1647:     }
                   1648: 
                   1649:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1650:     if (exists($courseinfo{'num'})) {
                   1651: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1652:     }
                   1653: 
                   1654:     return undef;
                   1655: }
                   1656: 
1.298     matthew  1657: sub getsection {
                   1658:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1659:     my $cachetime=1800;
1.551     albertel 1660: 
                   1661:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1662:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1663:     if (defined($cached)) { return $result; }
                   1664: 
1.298     matthew  1665:     my %Pending; 
                   1666:     my %Expired;
                   1667:     #
                   1668:     # Each role can either have not started yet (pending), be active, 
                   1669:     #    or have expired.
                   1670:     #
                   1671:     # If there is an active role, we are done.
                   1672:     #
                   1673:     # If there is more than one role which has not started yet, 
                   1674:     #     choose the one which will start sooner
                   1675:     # If there is one role which has not started yet, return it.
                   1676:     #
                   1677:     # If there is more than one expired role, choose the one which ended last.
                   1678:     # If there is a role which has expired, return it.
                   1679:     #
1.815     albertel 1680:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1681:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1682:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1683:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1684:         my $section=$1;
                   1685:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1686:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1687:         my $now=time;
1.548     albertel 1688:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1689:             $Expired{$end}=$section;
                   1690:             next;
                   1691:         }
1.548     albertel 1692:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1693:             $Pending{$start}=$section;
                   1694:             next;
                   1695:         }
1.599     albertel 1696:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1697:     }
                   1698:     #
                   1699:     # Presumedly there will be few matching roles from the above
                   1700:     # loop and the sorting time will be negligible.
                   1701:     if (scalar(keys(%Pending))) {
                   1702:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1703:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1704:     } 
                   1705:     if (scalar(keys(%Expired))) {
                   1706:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1707:         my $time = pop(@sorted);
1.599     albertel 1708:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1709:     }
1.599     albertel 1710:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1711: }
1.70      www      1712: 
1.599     albertel 1713: sub save_cache {
                   1714:     &purge_remembered();
1.722     albertel 1715:     #&Apache::loncommon::validate_page();
1.620     albertel 1716:     undef(%env);
1.780     albertel 1717:     undef($env_loaded);
1.599     albertel 1718: }
1.452     albertel 1719: 
1.599     albertel 1720: my $to_remember=-1;
                   1721: my %remembered;
                   1722: my %accessed;
                   1723: my $kicks=0;
                   1724: my $hits=0;
1.849     albertel 1725: sub make_key {
                   1726:     my ($name,$id) = @_;
1.872     albertel 1727:     if (length($id) > 65 
                   1728: 	&& length(&escape($id)) > 200) {
                   1729: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1730:     }
1.849     albertel 1731:     return &escape($name.':'.$id);
                   1732: }
                   1733: 
1.599     albertel 1734: sub devalidate_cache_new {
                   1735:     my ($name,$id,$debug) = @_;
                   1736:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1737:     $id=&make_key($name,$id);
1.599     albertel 1738:     $memcache->delete($id);
                   1739:     delete($remembered{$id});
                   1740:     delete($accessed{$id});
                   1741: }
                   1742: 
                   1743: sub is_cached_new {
                   1744:     my ($name,$id,$debug) = @_;
1.849     albertel 1745:     $id=&make_key($name,$id);
1.599     albertel 1746:     if (exists($remembered{$id})) {
                   1747: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1748: 	$accessed{$id}=[&gettimeofday()];
                   1749: 	$hits++;
                   1750: 	return ($remembered{$id},1);
                   1751:     }
                   1752:     my $value = $memcache->get($id);
                   1753:     if (!(defined($value))) {
                   1754: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1755: 	return (undef,undef);
1.416     albertel 1756:     }
1.599     albertel 1757:     if ($value eq '__undef__') {
                   1758: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1759: 	$value=undef;
                   1760:     }
                   1761:     &make_room($id,$value,$debug);
                   1762:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1763:     return ($value,1);
                   1764: }
                   1765: 
                   1766: sub do_cache_new {
                   1767:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1768:     $id=&make_key($name,$id);
1.599     albertel 1769:     my $setvalue=$value;
                   1770:     if (!defined($setvalue)) {
                   1771: 	$setvalue='__undef__';
                   1772:     }
1.623     albertel 1773:     if (!defined($time) ) {
                   1774: 	$time=600;
                   1775:     }
1.599     albertel 1776:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1777:     my $result = $memcache->set($id,$setvalue,$time);
                   1778:     if (! $result) {
1.872     albertel 1779: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1780: 	$memcache->disconnect_all();
1.872     albertel 1781:     }
1.600     albertel 1782:     # need to make a copy of $value
1.919     albertel 1783:     &make_room($id,$value,$debug);
1.599     albertel 1784:     return $value;
                   1785: }
                   1786: 
                   1787: sub make_room {
                   1788:     my ($id,$value,$debug)=@_;
1.919     albertel 1789: 
                   1790:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1791:                                     : $value;
1.599     albertel 1792:     if ($to_remember<0) { return; }
                   1793:     $accessed{$id}=[&gettimeofday()];
                   1794:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1795:     my $to_kick;
                   1796:     my $max_time=0;
                   1797:     foreach my $other (keys(%accessed)) {
                   1798: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1799: 	    $to_kick=$other;
                   1800: 	    $max_time=&tv_interval($accessed{$other});
                   1801: 	}
                   1802:     }
                   1803:     delete($remembered{$to_kick});
                   1804:     delete($accessed{$to_kick});
                   1805:     $kicks++;
                   1806:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1807:     return;
                   1808: }
                   1809: 
1.599     albertel 1810: sub purge_remembered {
1.604     albertel 1811:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1812:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1813:     undef(%remembered);
                   1814:     undef(%accessed);
1.428     albertel 1815: }
1.70      www      1816: # ------------------------------------- Read an entry from a user's environment
                   1817: 
                   1818: sub userenvironment {
                   1819:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1820:     my $items;
                   1821:     foreach my $item (@what) {
                   1822:         $items.=&escape($item).'&';
                   1823:     }
                   1824:     $items=~s/\&$//;
1.70      www      1825:     my %returnhash=();
1.1009    raeburn  1826:     my $uhome = &homeserver($unam,$udom);
                   1827:     unless ($uhome eq 'no_host') {
                   1828:         my @answer=split(/\&/, 
                   1829:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1830:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1831:             return %returnhash;
                   1832:         }
1.1009    raeburn  1833:         my $i;
                   1834:         for ($i=0;$i<=$#what;$i++) {
                   1835: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1836:         }
1.70      www      1837:     }
                   1838:     return %returnhash;
1.1       albertel 1839: }
                   1840: 
1.617     albertel 1841: # ---------------------------------------------------------- Get a studentphoto
                   1842: sub studentphoto {
                   1843:     my ($udom,$unam,$ext) = @_;
                   1844:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1845:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1846:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1847:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1848:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1849:             } else {
                   1850:                 my ($result,$perm_reqd)=
1.707     albertel 1851: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1852:                 if ($result eq 'ok') {
                   1853:                     if (!($perm_reqd eq 'yes')) {
                   1854:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1855:                     }
                   1856:                 }
                   1857:             }
                   1858:         }
                   1859:     } else {
                   1860:         my ($result,$perm_reqd) = 
1.707     albertel 1861: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1862:         if ($result eq 'ok') {
                   1863:             if (!($perm_reqd eq 'yes')) {
                   1864:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1865:             }
                   1866:         }
                   1867:     }
                   1868:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1869: }
                   1870: 
                   1871: sub retrievestudentphoto {
                   1872:     my ($udom,$unam,$ext,$type) = @_;
                   1873:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1874:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1875:     if ($ret eq 'ok') {
                   1876:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1877:         if ($type eq 'thumbnail') {
                   1878:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1879:         }
                   1880:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1881:         return $tokenurl;
                   1882:     } else {
                   1883:         if ($type eq 'thumbnail') {
                   1884:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1885:         } else { 
                   1886:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1887:         }
1.617     albertel 1888:     }
                   1889: }
                   1890: 
1.263     www      1891: # -------------------------------------------------------------------- New chat
                   1892: 
                   1893: sub chatsend {
1.724     raeburn  1894:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1895:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1896:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1897:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1898:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1899: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1900: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1901: }
                   1902: 
                   1903: # ------------------------------------------ Find current version of a resource
                   1904: 
                   1905: sub getversion {
                   1906:     my $fname=&clutter(shift);
                   1907:     unless ($fname=~/^\/res\//) { return -1; }
                   1908:     return &currentversion(&filelocation('',$fname));
                   1909: }
                   1910: 
                   1911: sub currentversion {
                   1912:     my $fname=shift;
1.599     albertel 1913:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1914:     if (defined($cached)) { return $result; }
1.292     www      1915:     my $author=$fname;
                   1916:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1917:     my ($udom,$uname)=split(/\//,$author);
                   1918:     my $home=homeserver($uname,$udom);
                   1919:     if ($home eq 'no_host') { 
                   1920:         return -1; 
                   1921:     }
                   1922:     my $answer=reply("currentversion:$fname",$home);
                   1923:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1924: 	return -1;
                   1925:     }
1.599     albertel 1926:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1927: }
                   1928: 
1.1       albertel 1929: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1930: 
1.1       albertel 1931: sub subscribe {
                   1932:     my $fname=shift;
1.761     raeburn  1933:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1934:     $fname=~s/[\n\r]//g;
1.1       albertel 1935:     my $author=$fname;
                   1936:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1937:     my ($udom,$uname)=split(/\//,$author);
                   1938:     my $home=homeserver($uname,$udom);
1.335     albertel 1939:     if ($home eq 'no_host') {
                   1940:         return 'not_found';
1.1       albertel 1941:     }
                   1942:     my $answer=reply("sub:$fname",$home);
1.64      www      1943:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1944: 	$answer.=' by '.$home;
                   1945:     }
1.1       albertel 1946:     return $answer;
                   1947: }
                   1948:     
1.8       www      1949: # -------------------------------------------------------------- Replicate file
                   1950: 
                   1951: sub repcopy {
                   1952:     my $filename=shift;
1.23      www      1953:     $filename=~s/\/+/\//g;
1.607     raeburn  1954:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1955:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1956:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1957: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1958: 	return &repcopy_userfile($filename);
                   1959:     }
1.532     albertel 1960:     $filename=~s/[\n\r]//g;
1.8       www      1961:     my $transname="$filename.in.transfer";
1.828     www      1962: # FIXME: this should flock
1.607     raeburn  1963:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1964:     my $remoteurl=subscribe($filename);
1.64      www      1965:     if ($remoteurl =~ /^con_lost by/) {
                   1966: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1967:            return 'unavailable';
1.8       www      1968:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1969: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1970: 	   return 'not_found';
1.64      www      1971:     } elsif ($remoteurl =~ /^rejected by/) {
                   1972: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1973:            return 'forbidden';
1.20      www      1974:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1975:            return 'ok';
1.8       www      1976:     } else {
1.290     www      1977:         my $author=$filename;
                   1978:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1979:         my ($udom,$uname)=split(/\//,$author);
                   1980:         my $home=homeserver($uname,$udom);
                   1981:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1982:            my @parts=split(/\//,$filename);
                   1983:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1984:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1985:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1986: 	       return 'bad_request';
1.8       www      1987:            }
                   1988:            my $count;
                   1989:            for ($count=5;$count<$#parts;$count++) {
                   1990:                $path.="/$parts[$count]";
                   1991:                if ((-e $path)!=1) {
                   1992: 		   mkdir($path,0777);
                   1993:                }
                   1994:            }
                   1995:            my $ua=new LWP::UserAgent;
                   1996:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1997:            my $response=$ua->request($request,$transname);
                   1998:            if ($response->is_error()) {
                   1999: 	       unlink($transname);
                   2000:                my $message=$response->status_line;
1.672     albertel 2001:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2002:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2003:                return 'unavailable';
1.8       www      2004:            } else {
1.16      www      2005: 	       if ($remoteurl!~/\.meta$/) {
                   2006:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2007:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2008:                   if ($mresponse->is_error()) {
                   2009: 		      unlink($filename.'.meta');
                   2010:                       &logthis(
1.672     albertel 2011:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2012:                   }
                   2013: 	       }
1.8       www      2014:                rename($transname,$filename);
1.607     raeburn  2015:                return 'ok';
1.8       www      2016:            }
1.290     www      2017:        }
1.8       www      2018:     }
1.330     www      2019: }
                   2020: 
                   2021: # ------------------------------------------------ Get server side include body
                   2022: sub ssi_body {
1.381     albertel 2023:     my ($filelink,%form)=@_;
1.606     matthew  2024:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2025:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2026:     }
1.953     www      2027:     my $output='';
                   2028:     my $response;
1.980     raeburn  2029:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2030:        ($output,$response)=&externalssi($filelink);
1.953     www      2031:     } else {
1.1004    droeschl 2032:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2033:        $filelink .= 'inhibitmenu=yes';
1.953     www      2034:        ($output,$response)=&ssi($filelink,%form);
                   2035:     }
1.778     albertel 2036:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2037:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2038:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2039:     if (wantarray) {
                   2040:         return ($output, $response);
                   2041:     } else {
                   2042:         return $output;
                   2043:     }
1.8       www      2044: }
                   2045: 
1.15      www      2046: # --------------------------------------------------------- Server Side Include
                   2047: 
1.782     albertel 2048: sub absolute_url {
                   2049:     my ($host_name) = @_;
                   2050:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2051:     if ($host_name eq '') {
                   2052: 	$host_name = $ENV{'SERVER_NAME'};
                   2053:     }
                   2054:     return $protocol.$host_name;
                   2055: }
                   2056: 
1.942     foxr     2057: #
                   2058: #   Server side include.
                   2059: # Parameters:
                   2060: #  fn     Possibly encrypted resource name/id.
                   2061: #  form   Hash that describes how the rendering should be done
                   2062: #         and other things.
1.944     foxr     2063: # Returns:
1.950     raeburn  2064: #   Scalar context: The content of the response.
                   2065: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2066: #     
1.15      www      2067: sub ssi {
                   2068: 
1.944     foxr     2069:     my ($fn,%form)=@_;
1.15      www      2070:     my $ua=new LWP::UserAgent;
1.23      www      2071:     my $request;
1.711     albertel 2072: 
                   2073:     $form{'no_update_last_known'}=1;
1.895     albertel 2074:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2075:     if (%form) {
1.782     albertel 2076:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2077:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2078:     } else {
1.782     albertel 2079:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2080:     }
                   2081: 
1.15      www      2082:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2083:     my $response=$ua->request($request);
                   2084: 
1.944     foxr     2085:     if (wantarray) {
                   2086: 	return ($response->content, $response);
                   2087:     } else {
                   2088: 	return $response->content;
1.942     foxr     2089:     }
1.324     www      2090: }
                   2091: 
                   2092: sub externalssi {
                   2093:     my ($url)=@_;
                   2094:     my $ua=new LWP::UserAgent;
                   2095:     my $request=new HTTP::Request('GET',$url);
                   2096:     my $response=$ua->request($request);
1.954     raeburn  2097:     if (wantarray) {
                   2098:         return ($response->content, $response);
                   2099:     } else {
                   2100:         return $response->content;
                   2101:     }
1.15      www      2102: }
1.254     www      2103: 
1.492     albertel 2104: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2105: 
                   2106: sub allowuploaded {
                   2107:     my ($srcurl,$url)=@_;
                   2108:     $url=&clutter(&declutter($url));
                   2109:     my $dir=$url;
                   2110:     $dir=~s/\/[^\/]+$//;
                   2111:     my %httpref=();
                   2112:     my $httpurl=&hreflocation('',$url);
                   2113:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2114:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2115: }
1.477     raeburn  2116: 
1.478     albertel 2117: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2118: # input: action, courseID, current domain, intended
1.637     raeburn  2119: #        path to file, source of file, instruction to parse file for objects,
                   2120: #        ref to hash for embedded objects,
                   2121: #        ref to hash for codebase of java objects.
                   2122: #
1.485     raeburn  2123: # output: url to file (if action was uploaddoc), 
                   2124: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2125: #
1.478     albertel 2126: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2127: # course.
1.477     raeburn  2128: #
1.478     albertel 2129: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2130: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2131: #          course's home server.
1.477     raeburn  2132: #
1.478     albertel 2133: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2134: #          be copied from $source (current location) to 
                   2135: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2136: #         and will then be copied to
                   2137: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2138: #         course's home server.
1.485     raeburn  2139: #
1.481     raeburn  2140: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2141: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2142: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2143: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2144: #         in course's home server.
1.637     raeburn  2145: #
1.477     raeburn  2146: 
                   2147: sub process_coursefile {
1.638     albertel 2148:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2149:     my $fetchresult;
1.638     albertel 2150:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2151:     if ($action eq 'propagate') {
1.638     albertel 2152:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2153: 			     $home);
1.481     raeburn  2154:     } else {
1.477     raeburn  2155:         my $fpath = '';
                   2156:         my $fname = $file;
1.478     albertel 2157:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2158:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2159:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2160:         if ($action eq 'copy') {
                   2161:             if ($source eq '') {
                   2162:                 $fetchresult = 'no source file';
                   2163:                 return $fetchresult;
                   2164:             } else {
                   2165:                 my $destination = $filepath.'/'.$fname;
                   2166:                 rename($source,$destination);
                   2167:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2168:                                  $home);
1.481     raeburn  2169:             }
                   2170:         } elsif ($action eq 'uploaddoc') {
                   2171:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2172:             print $fh $env{'form.'.$source};
1.481     raeburn  2173:             close($fh);
1.637     raeburn  2174:             if ($parser eq 'parse') {
1.1024    raeburn  2175:                 my $mm = new File::MMagic;
                   2176:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2177:                 if ($mime_type eq 'text/html') {
                   2178:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2179:                     unless ($parse_result eq 'ok') {
                   2180:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2181:                     }
1.637     raeburn  2182:                 }
                   2183:             }
1.477     raeburn  2184:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2185:                                  $home);
1.481     raeburn  2186:             if ($fetchresult eq 'ok') {
                   2187:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2188:             } else {
                   2189:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2190:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2191:                 return '/adm/notfound.html';
                   2192:             }
1.477     raeburn  2193:         }
                   2194:     }
1.485     raeburn  2195:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2196:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2197:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2198:     }
                   2199:     return $fetchresult;
                   2200: }
                   2201: 
1.637     raeburn  2202: sub build_filepath {
                   2203:     my ($fpath) = @_;
                   2204:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2205:     unless ($fpath eq '') {
                   2206:         my @parts=split('/',$fpath);
                   2207:         foreach my $part (@parts) {
                   2208:             $filepath.= '/'.$part;
                   2209:             if ((-e $filepath)!=1) {
                   2210:                 mkdir($filepath,0777);
                   2211:             }
                   2212:         }
                   2213:     }
                   2214:     return $filepath;
                   2215: }
                   2216: 
                   2217: sub store_edited_file {
1.638     albertel 2218:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2219:     my $file = $primary_url;
                   2220:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2221:     my $fpath = '';
                   2222:     my $fname = $file;
                   2223:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2224:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2225:     my $filepath = &build_filepath($fpath);
                   2226:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2227:     print $fh $content;
                   2228:     close($fh);
1.638     albertel 2229:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2230:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2231: 			  $home);
1.637     raeburn  2232:     if ($$fetchresult eq 'ok') {
                   2233:         return '/uploaded/'.$fpath.'/'.$fname;
                   2234:     } else {
1.638     albertel 2235:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2236: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2237:         return '/adm/notfound.html';
                   2238:     }
                   2239: }
                   2240: 
1.531     albertel 2241: sub clean_filename {
1.831     albertel 2242:     my ($fname,$args)=@_;
1.315     www      2243: # Replace Windows backslashes by forward slashes
1.257     www      2244:     $fname=~s/\\/\//g;
1.831     albertel 2245:     if (!$args->{'keep_path'}) {
                   2246:         # Get rid of everything but the actual filename
                   2247: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2248:     }
1.315     www      2249: # Replace spaces by underscores
                   2250:     $fname=~s/\s+/\_/g;
                   2251: # Replace all other weird characters by nothing
1.831     albertel 2252:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2253: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2254: # numbers
                   2255:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2256:     return $fname;
                   2257: }
1.1051    raeburn  2258: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2259: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2260: # image with the same aspect ratio as the original, but with dimensions which do 
                   2261: # not exceed $resizewidth and $resizeheight.
                   2262:  
1.984     neumanie 2263: sub resizeImage {
1.1051    raeburn  2264:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2265:     my $ima = Image::Magick->new;
                   2266:     my $resized;
                   2267:     if (-e $img_path) {
                   2268:         $ima->Read($img_path);
                   2269:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2270:             my $width = $ima->Get('width');
                   2271:             my $height = $ima->Get('height');
                   2272:             if ($width > $resizewidth) {
                   2273: 	        my $factor = $width/$resizewidth;
                   2274:                 my $newheight = $height/$factor;
                   2275:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2276:                 $resized = 1;
                   2277:             }
                   2278:         }
                   2279:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2280:             my $width = $ima->Get('width');
                   2281:             my $height = $ima->Get('height');
                   2282:             if ($height > $resizeheight) {
                   2283:                 my $factor = $height/$resizeheight;
                   2284:                 my $newwidth = $width/$factor;
                   2285:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2286:                 $resized = 1;
                   2287:             }
                   2288:         }
                   2289:         if ($resized) {
                   2290:             $ima->Write($img_path);
                   2291:         }
                   2292:     }
                   2293:     return;
1.977     amueller 2294: }
                   2295: 
1.608     albertel 2296: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2297: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2298: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2299: #        $coursedoc - if true up to the current course
                   2300: #                     if false
                   2301: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2302: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2303: #        $allfiles - reference to hash for embedded objects
                   2304: #        $codebase - reference to hash for codebase of java objects
                   2305: #        $desuname - username for permanent storage of uploaded file
                   2306: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2307: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2308: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2309: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2310: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2311: # 
1.686     albertel 2312: # output: url of file in userspace, or error: <message> 
                   2313: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2314: 
1.531     albertel 2315: sub userfileupload {
1.860     raeburn  2316:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2317:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2318:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2319:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2320:     $fname=&clean_filename($fname);
1.315     www      2321: # See if there is anything left
1.257     www      2322:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2323:     chop($env{'form.'.$formname});
1.523     raeburn  2324:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2325:         my $now = time;
                   2326:         my $filepath = 'tmp/helprequests/'.$now;
                   2327:         my @parts=split(/\//,$filepath);
                   2328:         my $fullpath = $perlvar{'lonDaemons'};
                   2329:         for (my $i=0;$i<@parts;$i++) {
                   2330:             $fullpath .= '/'.$parts[$i];
                   2331:             if ((-e $fullpath)!=1) {
                   2332:                 mkdir($fullpath,0777);
                   2333:             }
                   2334:         }
                   2335:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2336:         print $fh $env{'form.'.$formname};
1.523     raeburn  2337:         close($fh);
1.741     raeburn  2338:         return $fullpath.'/'.$fname;
                   2339:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2340:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2341:                        '_'.$env{'user.domain'}.'/pending';
                   2342:         my @parts=split(/\//,$filepath);
                   2343:         my $fullpath = $perlvar{'lonDaemons'};
                   2344:         for (my $i=0;$i<@parts;$i++) {
                   2345:             $fullpath .= '/'.$parts[$i];
                   2346:             if ((-e $fullpath)!=1) {
                   2347:                 mkdir($fullpath,0777);
                   2348:             }
                   2349:         }
                   2350:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2351:         print $fh $env{'form.'.$formname};
                   2352:         close($fh);
                   2353:         return $fullpath.'/'.$fname;
1.523     raeburn  2354:     }
1.995     raeburn  2355:     if ($subdir eq 'scantron') {
                   2356:         $fname = 'scantron_orig_'.$fname;
                   2357:     } else {   
1.258     www      2358: # Create the directory if not present
1.995     raeburn  2359:         $fname="$subdir/$fname";
                   2360:     }
1.259     www      2361:     if ($coursedoc) {
1.638     albertel 2362: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2363: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2364:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2365:             return &finishuserfileupload($docuname,$docudom,
                   2366: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2367: 					 $codebase,$thumbwidth,$thumbheight,
                   2368:                                          $resizewidth,$resizeheight);
1.481     raeburn  2369:         } else {
1.620     albertel 2370:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2371:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2372: 				       $fname,$formname,$parser,
                   2373: 				       $allfiles,$codebase);
1.481     raeburn  2374:         }
1.719     banghart 2375:     } elsif (defined($destuname)) {
                   2376:         my $docuname=$destuname;
                   2377:         my $docudom=$destudom;
1.860     raeburn  2378: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2379: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2380:                                      $thumbwidth,$thumbheight,
                   2381:                                      $resizewidth,$resizeheight);
1.719     banghart 2382:         
1.259     www      2383:     } else {
1.638     albertel 2384:         my $docuname=$env{'user.name'};
                   2385:         my $docudom=$env{'user.domain'};
1.714     raeburn  2386:         if (exists($env{'form.group'})) {
                   2387:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2388:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2389:         }
1.860     raeburn  2390: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2391: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2392:                                      $thumbwidth,$thumbheight,
                   2393:                                      $resizewidth,$resizeheight);
1.259     www      2394:     }
1.271     www      2395: }
                   2396: 
                   2397: sub finishuserfileupload {
1.860     raeburn  2398:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051    raeburn  2399:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477     raeburn  2400:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2401:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2402:   
1.860     raeburn  2403:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2404:     $file=$fname;
                   2405:     if ($fname=~m|/|) {
                   2406:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2407: 	$path.=$fnamepath.'/';
                   2408:     }
1.259     www      2409:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2410:     my $count;
                   2411:     for ($count=4;$count<=$#parts;$count++) {
                   2412:         $filepath.="/$parts[$count]";
                   2413:         if ((-e $filepath)!=1) {
                   2414: 	    mkdir($filepath,0777);
                   2415:         }
                   2416:     }
1.984     neumanie 2417: 
1.258     www      2418: # Save the file
                   2419:     {
1.701     albertel 2420: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2421: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2422: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2423: 	    return '/adm/notfound.html';
                   2424: 	}
                   2425: 	if (!print FH ($env{'form.'.$formname})) {
                   2426: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2427: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2428: 	    return '/adm/notfound.html';
                   2429: 	}
1.570     albertel 2430: 	close(FH);
1.1051    raeburn  2431:         if ($resizewidth && $resizeheight) {
                   2432:             my $mm = new File::MMagic;
                   2433:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2434:             if ($mime_type =~ m{^image/}) {
                   2435: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2436:             }  
1.977     amueller 2437: 	}
1.258     www      2438:     }
1.637     raeburn  2439:     if ($parser eq 'parse') {
1.1024    raeburn  2440:         my $mm = new File::MMagic;
                   2441:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2442:         if ($mime_type eq 'text/html') {
                   2443:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2444:                                                        $allfiles,$codebase);
                   2445:             unless ($parse_result eq 'ok') {
                   2446:                 &logthis('Failed to parse '.$filepath.$file.
                   2447: 	   	         ' for embedded media: '.$parse_result); 
                   2448:             }
1.637     raeburn  2449:         }
                   2450:     }
1.860     raeburn  2451:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2452:         my $input = $filepath.'/'.$file;
                   2453:         my $output = $filepath.'/'.'tn-'.$file;
                   2454:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2455:         system("convert -sample $thumbsize $input $output");
                   2456:         if (-e $filepath.'/'.'tn-'.$file) {
                   2457:             $fetchthumb  = 1; 
                   2458:         }
                   2459:     }
1.858     raeburn  2460:  
1.259     www      2461: # Notify homeserver to grep it
                   2462: #
1.984     neumanie 2463:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2464:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2465:     if ($fetchresult eq 'ok') {
1.860     raeburn  2466:         if ($fetchthumb) {
                   2467:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2468:             if ($thumbresult ne 'ok') {
                   2469:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2470:                          $docuhome.': '.$thumbresult);
                   2471:             }
                   2472:         }
1.259     www      2473: #
1.258     www      2474: # Return the URL to it
1.494     albertel 2475:         return '/uploaded/'.$path.$file;
1.263     www      2476:     } else {
1.494     albertel 2477:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2478: 		 ': '.$fetchresult);
1.263     www      2479:         return '/adm/notfound.html';
1.858     raeburn  2480:     }
1.493     albertel 2481: }
                   2482: 
1.637     raeburn  2483: sub extract_embedded_items {
1.961     raeburn  2484:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2485:     my @state = ();
                   2486:     my %javafiles = (
                   2487:                       codebase => '',
                   2488:                       code => '',
                   2489:                       archive => ''
                   2490:                     );
                   2491:     my %mediafiles = (
                   2492:                       src => '',
                   2493:                       movie => '',
                   2494:                      );
1.648     raeburn  2495:     my $p;
                   2496:     if ($content) {
                   2497:         $p = HTML::LCParser->new($content);
                   2498:     } else {
1.961     raeburn  2499:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2500:     }
1.641     albertel 2501:     while (my $t=$p->get_token()) {
1.640     albertel 2502: 	if ($t->[0] eq 'S') {
                   2503: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2504: 	    push(@state, $tagname);
1.648     raeburn  2505:             if (lc($tagname) eq 'allow') {
                   2506:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2507:             }
1.640     albertel 2508: 	    if (lc($tagname) eq 'img') {
                   2509: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2510: 	    }
1.886     albertel 2511: 	    if (lc($tagname) eq 'a') {
                   2512: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2513: 	    }
1.645     raeburn  2514:             if (lc($tagname) eq 'script') {
                   2515:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2516:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2517:                 } else {
                   2518:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2519:                 }
                   2520:             }
                   2521:             if (lc($tagname) eq 'link') {
                   2522:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2523:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2524:                 }
                   2525:             }
1.640     albertel 2526: 	    if (lc($tagname) eq 'object' ||
                   2527: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2528: 		foreach my $item (keys(%javafiles)) {
                   2529: 		    $javafiles{$item} = '';
                   2530: 		}
                   2531: 	    }
                   2532: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2533: 		my $name = lc($attr->{'name'});
                   2534: 		foreach my $item (keys(%javafiles)) {
                   2535: 		    if ($name eq $item) {
                   2536: 			$javafiles{$item} = $attr->{'value'};
                   2537: 			last;
                   2538: 		    }
                   2539: 		}
                   2540: 		foreach my $item (keys(%mediafiles)) {
                   2541: 		    if ($name eq $item) {
                   2542: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2543: 			last;
                   2544: 		    }
                   2545: 		}
                   2546: 	    }
                   2547: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2548: 		foreach my $item (keys(%javafiles)) {
                   2549: 		    if ($attr->{$item}) {
                   2550: 			$javafiles{$item} = $attr->{$item};
                   2551: 			last;
                   2552: 		    }
                   2553: 		}
                   2554: 		foreach my $item (keys(%mediafiles)) {
                   2555: 		    if ($attr->{$item}) {
                   2556: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2557: 			last;
                   2558: 		    }
                   2559: 		}
                   2560: 	    }
                   2561: 	} elsif ($t->[0] eq 'E') {
                   2562: 	    my ($tagname) = ($t->[1]);
                   2563: 	    if ($javafiles{'codebase'} ne '') {
                   2564: 		$javafiles{'codebase'} .= '/';
                   2565: 	    }  
                   2566: 	    if (lc($tagname) eq 'applet' ||
                   2567: 		lc($tagname) eq 'object' ||
                   2568: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2569: 		) {
                   2570: 		foreach my $item (keys(%javafiles)) {
                   2571: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2572: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2573: 			&add_filetype($allfiles,$file,$item);
                   2574: 		    }
                   2575: 		}
                   2576: 	    } 
                   2577: 	    pop @state;
                   2578: 	}
                   2579:     }
1.637     raeburn  2580:     return 'ok';
                   2581: }
                   2582: 
1.639     albertel 2583: sub add_filetype {
                   2584:     my ($allfiles,$file,$type)=@_;
                   2585:     if (exists($allfiles->{$file})) {
                   2586: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2587: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2588: 	}
                   2589:     } else {
                   2590: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2591:     }
                   2592: }
                   2593: 
1.493     albertel 2594: sub removeuploadedurl {
1.984     neumanie 2595:     my ($url)=@_;	
                   2596:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2597:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2598: }
                   2599: 
                   2600: sub removeuserfile {
                   2601:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2602:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2603:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2604:     if ($result eq 'ok') {	
1.798     raeburn  2605:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2606:             my $metafile = $fname.'.meta';
                   2607:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2608: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2609:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2610:             my $sqlresult = 
1.823     albertel 2611:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2612:                                         'portfolio_metadata',$group,
                   2613:                                         'delete');
1.798     raeburn  2614:         }
                   2615:     }
                   2616:     return $result;
1.257     www      2617: }
1.15      www      2618: 
1.530     albertel 2619: sub mkdiruserfile {
                   2620:     my ($docuname,$docudom,$dir)=@_;
                   2621:     my $home=&homeserver($docuname,$docudom);
                   2622:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2623: }
                   2624: 
1.531     albertel 2625: sub renameuserfile {
                   2626:     my ($docuname,$docudom,$old,$new)=@_;
                   2627:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2628:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2629:                         &escape("$old").':'.&escape("$new"),$home);
                   2630:     if ($result eq 'ok') {
                   2631:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2632:             my $oldmeta = $old.'.meta';
                   2633:             my $newmeta = $new.'.meta';
                   2634:             my $metaresult = 
                   2635:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2636: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2637:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2638:             my $sqlresult = 
1.823     albertel 2639:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2640:                                         'portfolio_metadata',$group,
                   2641:                                         'delete');
1.798     raeburn  2642:         }
                   2643:     }
                   2644:     return $result;
1.531     albertel 2645: }
                   2646: 
1.14      www      2647: # ------------------------------------------------------------------------- Log
                   2648: 
                   2649: sub log {
                   2650:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2651:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2652: }
                   2653: 
                   2654: # ------------------------------------------------------------------ Course Log
1.352     www      2655: #
                   2656: # This routine flushes several buffers of non-mission-critical nature
                   2657: #
1.157     www      2658: 
                   2659: sub flushcourselogs {
1.352     www      2660:     &logthis('Flushing log buffers');
                   2661: #
                   2662: # course logs
                   2663: # This is a log of all transactions in a course, which can be used
                   2664: # for data mining purposes
                   2665: #
                   2666: # It also collects the courseid database, which lists last transaction
                   2667: # times and course titles for all courseids
                   2668: #
                   2669:     my %courseidbuffer=();
1.921     raeburn  2670:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2671:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2672: 		          &escape($courselogs{$crsid}),
                   2673: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2674: 	    delete $courselogs{$crsid};
                   2675:         } else {
                   2676:             &logthis('Failed to flush log buffer for '.$crsid);
                   2677:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2678:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2679:                         " exceeded maximum size, deleting.</font>");
                   2680:                delete $courselogs{$crsid};
                   2681:             }
1.352     www      2682:         }
1.920     raeburn  2683:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2684:             'description' => $coursedescrbuf{$crsid},
                   2685:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2686:             'type'        => $coursetypebuf{$crsid},
                   2687:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2688:         };
1.191     harris41 2689:     }
1.352     www      2690: #
                   2691: # Write course id database (reverse lookup) to homeserver of courses 
                   2692: # Is used in pickcourse
                   2693: #
1.840     albertel 2694:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2695:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2696:                                     $courseidbuffer{$crs_home},
                   2697:                                     $crs_home,'timeonly');
1.352     www      2698:     }
                   2699: #
                   2700: # File accesses
                   2701: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2702: #
1.449     matthew  2703:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2704:         if ($entry =~ /___count$/) {
                   2705:             my ($dom,$name);
1.807     albertel 2706:             ($dom,$name,undef)=
1.811     albertel 2707: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2708:             if (! defined($dom) || $dom eq '' || 
                   2709:                 ! defined($name) || $name eq '') {
1.620     albertel 2710:                 my $cid = $env{'request.course.id'};
                   2711:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2712:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2713:             }
1.450     matthew  2714:             my $value = $accesshash{$entry};
                   2715:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2716:             my %temphash=($url => $value);
1.449     matthew  2717:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2718:             if ($result eq 'ok') {
                   2719:                 delete $accesshash{$entry};
                   2720:             } elsif ($result eq 'unknown_cmd') {
                   2721:                 # Target server has old code running on it.
1.450     matthew  2722:                 my %temphash=($entry => $value);
1.449     matthew  2723:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2724:                     delete $accesshash{$entry};
                   2725:                 }
                   2726:             }
                   2727:         } else {
1.811     albertel 2728:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2729:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2730:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2731:                 delete $accesshash{$entry};
                   2732:             }
1.185     www      2733:         }
1.191     harris41 2734:     }
1.352     www      2735: #
                   2736: # Roles
                   2737: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2738: #
1.800     albertel 2739:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2740:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2741: 	    split(/\:/,$entry);
                   2742:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2743:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2744:                 $rudom,$runame) eq 'ok') {
                   2745: 	    delete $userrolehash{$entry};
                   2746:         }
                   2747:     }
1.662     raeburn  2748: #
                   2749: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2750: #
                   2751:     my %domrolebuffer = ();
1.1000    raeburn  2752:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2753:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2754:         if ($domrolebuffer{$rudom}) {
                   2755:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2756:                       '='.&escape($domainrolehash{$entry});
                   2757:         } else {
                   2758:             $domrolebuffer{$rudom}.=&escape($entry).
                   2759:                       '='.&escape($domainrolehash{$entry});
                   2760:         }
                   2761:         delete $domainrolehash{$entry};
                   2762:     }
                   2763:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2764: 	my %servers = &get_servers($dom,'library');
                   2765: 	foreach my $tryserver (keys(%servers)) {
                   2766: 	    unless (&reply('domroleput:'.$dom.':'.
                   2767: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2768: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2769: 	    }
1.662     raeburn  2770:         }
                   2771:     }
1.186     www      2772:     $dumpcount++;
1.157     www      2773: }
                   2774: 
                   2775: sub courselog {
                   2776:     my $what=shift;
1.158     www      2777:     $what=time.':'.$what;
1.620     albertel 2778:     unless ($env{'request.course.id'}) { return ''; }
                   2779:     $coursedombuf{$env{'request.course.id'}}=
                   2780:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2781:     $coursenumbuf{$env{'request.course.id'}}=
                   2782:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2783:     $coursehombuf{$env{'request.course.id'}}=
                   2784:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2785:     $coursedescrbuf{$env{'request.course.id'}}=
                   2786:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2787:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2788:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2789:     $courseownerbuf{$env{'request.course.id'}}=
                   2790:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2791:     $coursetypebuf{$env{'request.course.id'}}=
                   2792:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2793:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2794: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2795:     } else {
1.620     albertel 2796: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2797:     }
1.620     albertel 2798:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2799: 	&flushcourselogs();
                   2800:     }
1.158     www      2801: }
                   2802: 
                   2803: sub courseacclog {
                   2804:     my $fnsymb=shift;
1.620     albertel 2805:     unless ($env{'request.course.id'}) { return ''; }
                   2806:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2807:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2808:         $what.=':POST';
1.583     matthew  2809:         # FIXME: Probably ought to escape things....
1.800     albertel 2810: 	foreach my $key (keys(%env)) {
                   2811:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2812:                 my $formitem = $1;
                   2813:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2814:                     $what.=':'.$formitem.'='.$env{$key};
                   2815:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2816:                     $what.=':'.$formitem.'='.$env{$key};
                   2817:                 }
1.158     www      2818:             }
1.191     harris41 2819:         }
1.583     matthew  2820:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2821:         # FIXME: We should not be depending on a form parameter that someone
                   2822:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2823:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2824:             $what.= ':POST';
                   2825:             # FIXME: Probably ought to escape things....
                   2826:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2827:                                  'crsdiscuss') {
1.620     albertel 2828:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2829:             }
                   2830:         }
1.158     www      2831:     }
                   2832:     &courselog($what);
1.149     www      2833: }
                   2834: 
1.185     www      2835: sub countacc {
                   2836:     my $url=&declutter(shift);
1.458     matthew  2837:     return if (! defined($url) || $url eq '');
1.620     albertel 2838:     unless ($env{'request.course.id'}) { return ''; }
                   2839:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2840:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2841:     $accesshash{$key}++;
1.185     www      2842: }
1.349     www      2843: 
1.361     www      2844: sub linklog {
                   2845:     my ($from,$to)=@_;
                   2846:     $from=&declutter($from);
                   2847:     $to=&declutter($to);
                   2848:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2849:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2850: }
                   2851:   
1.349     www      2852: sub userrolelog {
                   2853:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2854:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2855:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2856:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2857:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2858:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2859:        $userrolehash
                   2860:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2861:                     =$tend.':'.$tstart;
1.662     raeburn  2862:     }
1.898     albertel 2863:     if (($env{'request.role'} =~ /dc\./) &&
                   2864: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2865: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2866: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2867:          ($trole=~/^co/))) {
1.898     albertel 2868:        $userrolehash
                   2869:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2870:                     =$tend.':'.$tstart;
                   2871:     }
1.662     raeburn  2872:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2873:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2874:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2875:         ($trole=~/^sc/)) {
                   2876:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2877:        $domainrolehash
                   2878:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2879:                     = $tend.':'.$tstart;
                   2880:     }
1.351     www      2881: }
                   2882: 
1.957     raeburn  2883: sub courserolelog {
                   2884:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2885:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2886:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2887:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2888:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2889:         ($trole eq 'co')) {
1.957     raeburn  2890:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2891:             my $cdom = $1;
                   2892:             my $cnum = $2;
                   2893:             my $sec = $3;
                   2894:             my $namespace = 'rolelog';
                   2895:             my %storehash = (
                   2896:                                role    => $trole,
                   2897:                                start   => $tstart,
                   2898:                                end     => $tend,
                   2899:                                selfenroll => $selfenroll,
                   2900:                                context    => $context,
                   2901:                             );
                   2902:             if ($trole eq 'gr') {
                   2903:                 $namespace = 'groupslog';
                   2904:                 $storehash{'group'} = $sec;
                   2905:             } else {
                   2906:                 $storehash{'section'} = $sec;
                   2907:             }
                   2908:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2909:             if (($trole ne 'st') || ($sec ne '')) {
                   2910:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2911:             }
1.957     raeburn  2912:         }
                   2913:     }
                   2914:     return;
                   2915: }
                   2916: 
1.351     www      2917: sub get_course_adv_roles {
1.948     raeburn  2918:     my ($cid,$codes) = @_;
1.620     albertel 2919:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2920:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2921:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2922:     my %nothide=();
1.800     albertel 2923:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2924:         if ($user !~ /:/) {
                   2925: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2926:         } else {
                   2927:             $nothide{$user}=1;
                   2928:         }
1.470     www      2929:     }
1.351     www      2930:     my %returnhash=();
                   2931:     my %dumphash=
                   2932:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2933:     my $now=time;
1.997     raeburn  2934:     my %privileged;
1.1000    raeburn  2935:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2936: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2937:         if (($tstart) && ($tstart<0)) { next; }
                   2938:         if (($tend) && ($tend<$now)) { next; }
                   2939:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2940:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2941: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2942:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2943:             my %dompersonnel =
1.998     raeburn  2944:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2945:             $privileged{$domain} = {};
                   2946:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2947:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2948:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2949:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2950:                         $privileged{$udom}{$uname} = 1;
                   2951:                     }
                   2952:                 }
                   2953:             }
                   2954:         }
                   2955:         if ((exists($privileged{$domain}{$username})) && 
                   2956:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2957: 	if ($role eq 'cr') { next; }
1.948     raeburn  2958:         if ($codes) {
                   2959:             if ($section) { $role .= ':'.$section; }
                   2960:             if ($returnhash{$role}) {
                   2961:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2962:             } else {
                   2963:                 $returnhash{$role}=$username.':'.$domain;
                   2964:             }
1.351     www      2965:         } else {
1.988     raeburn  2966:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2967:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2968:             if ($returnhash{$key}) {
                   2969: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2970:             } else {
                   2971:                 $returnhash{$key}=$username.':'.$domain;
                   2972:             }
1.351     www      2973:         }
1.948     raeburn  2974:     }
1.400     www      2975:     return %returnhash;
                   2976: }
                   2977: 
                   2978: sub get_my_roles {
1.937     raeburn  2979:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2980:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2981:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2982:     my (%dumphash,%nothide);
1.858     raeburn  2983:     if ($context eq 'userroles') { 
                   2984:         %dumphash = &dump('roles',$udom,$uname);
                   2985:     } else {
                   2986:         %dumphash=
1.400     www      2987:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2988:         if ($hidepriv) {
                   2989:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2990:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2991:                 if ($user !~ /:/) {
                   2992:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2993:                 } else {
                   2994:                     $nothide{$user} = 1;
                   2995:                 }
                   2996:             }
                   2997:         }
1.858     raeburn  2998:     }
1.400     www      2999:     my %returnhash=();
                   3000:     my $now=time;
1.999     raeburn  3001:     my %privileged;
1.800     albertel 3002:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3003:         my ($role,$tend,$tstart);
                   3004:         if ($context eq 'userroles') {
                   3005: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3006:         } else {
                   3007:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3008:         }
1.400     www      3009:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3010:         my $status = 'active';
1.939     raeburn  3011:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3012:             $status = 'previous';
                   3013:         } 
                   3014:         if (($tstart) && ($now<$tstart)) {
                   3015:             $status = 'future';
                   3016:         }
                   3017:         if (ref($types) eq 'ARRAY') {
                   3018:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3019:                 next;
                   3020:             } 
                   3021:         } else {
                   3022:             if ($status ne 'active') {
                   3023:                 next;
                   3024:             }
                   3025:         }
1.867     raeburn  3026:         my ($rolecode,$username,$domain,$section,$area);
                   3027:         if ($context eq 'userroles') {
                   3028:             ($area,$rolecode) = split(/_/,$entry);
                   3029:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3030:         } else {
                   3031:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3032:         }
1.832     raeburn  3033:         if (ref($roledoms) eq 'ARRAY') {
                   3034:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3035:                 next;
                   3036:             }
                   3037:         }
                   3038:         if (ref($roles) eq 'ARRAY') {
                   3039:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3040:                 if ($role =~ /^cr\//) {
                   3041:                     if (!grep(/^cr$/,@{$roles})) {
                   3042:                         next;
                   3043:                     }
                   3044:                 } else {
                   3045:                     next;
                   3046:                 }
1.832     raeburn  3047:             }
1.867     raeburn  3048:         }
1.937     raeburn  3049:         if ($hidepriv) {
1.999     raeburn  3050:             if ($context eq 'userroles') {
                   3051:                 if ((&privileged($username,$domain)) &&
                   3052:                     (!$nothide{$username.':'.$domain})) {
                   3053:                     next;
                   3054:                 }
                   3055:             } else {
                   3056:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3057:                     my %dompersonnel =
                   3058:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3059:                     $privileged{$domain} = {};
                   3060:                     if (keys(%dompersonnel)) {
                   3061:                         foreach my $server (keys(%dompersonnel)) {
                   3062:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3063:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3064:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3065:                                     $privileged{$udom}{$uname} = $trole;
                   3066:                                 }
                   3067:                             }
                   3068:                         }
                   3069:                     }
                   3070:                 }
                   3071:                 if (exists($privileged{$domain}{$username})) {
                   3072:                     if (!$nothide{$username.':'.$domain}) {
                   3073:                         next;
                   3074:                     }
                   3075:                 }
1.937     raeburn  3076:             }
                   3077:         }
1.933     raeburn  3078:         if ($withsec) {
                   3079:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3080:                 $tstart.':'.$tend;
                   3081:         } else {
                   3082:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3083:         }
1.832     raeburn  3084:     }
1.373     www      3085:     return %returnhash;
1.399     www      3086: }
                   3087: 
                   3088: # ----------------------------------------------------- Frontpage Announcements
                   3089: #
                   3090: #
                   3091: 
                   3092: sub postannounce {
                   3093:     my ($server,$text)=@_;
1.844     albertel 3094:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3095:     unless ($text=~/\w/) { $text=''; }
                   3096:     return &reply('setannounce:'.&escape($text),$server);
                   3097: }
                   3098: 
                   3099: sub getannounce {
1.448     albertel 3100: 
                   3101:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3102: 	my $announcement='';
1.800     albertel 3103: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3104: 	close($fh);
1.399     www      3105: 	if ($announcement=~/\w/) { 
                   3106: 	    return 
                   3107:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3108:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3109: 	} else {
                   3110: 	    return '';
                   3111: 	}
                   3112:     } else {
                   3113: 	return '';
                   3114:     }
1.351     www      3115: }
1.353     www      3116: 
                   3117: # ---------------------------------------------------------- Course ID routines
                   3118: # Deal with domain's nohist_courseid.db files
                   3119: #
                   3120: 
                   3121: sub courseidput {
1.921     raeburn  3122:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3123:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3124:     my $outcome;
                   3125:     if ($caller eq 'timeonly') {
                   3126:         my $cids = '';
                   3127:         foreach my $item (keys(%$storehash)) {
                   3128:             $cids.=&escape($item).'&';
                   3129:         }
                   3130:         $cids=~s/\&$//;
                   3131:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3132:                           $coursehome);       
                   3133:     } else {
                   3134:         my $items = '';
                   3135:         foreach my $item (keys(%$storehash)) {
                   3136:             $items.= &escape($item).'='.
                   3137:                      &freeze_escape($$storehash{$item}).'&';
                   3138:         }
                   3139:         $items=~s/\&$//;
                   3140:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3141:                           $coursehome);
1.918     raeburn  3142:     }
                   3143:     if ($outcome eq 'unknown_cmd') {
                   3144:         my $what;
                   3145:         foreach my $cid (keys(%$storehash)) {
                   3146:             $what .= &escape($cid).'=';
1.921     raeburn  3147:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3148:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3149:             }
                   3150:             $what =~ s/\:$/&/;
                   3151:         }
                   3152:         $what =~ s/\&$//;  
                   3153:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3154:     } else {
                   3155:         return $outcome;
                   3156:     }
1.353     www      3157: }
                   3158: 
                   3159: sub courseiddump {
1.921     raeburn  3160:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3161:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3162:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3163:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3164:     my $as_hash = 1;
                   3165:     my %returnhash;
                   3166:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3167:     my %libserv = &all_library();
                   3168:     foreach my $tryserver (keys(%libserv)) {
                   3169:         if ( (  $hostidflag == 1 
                   3170: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3171: 	     || (!defined($hostidflag)) ) {
                   3172: 
1.918     raeburn  3173: 	    if (($domfilter eq '') ||
                   3174: 		(&host_domain($tryserver) eq $domfilter)) {
                   3175:                 my $rep = 
                   3176:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3177:                          $sincefilter.':'.&escape($descfilter).':'.
                   3178:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3179:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3180:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3181:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3182:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3183:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3184:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3185:                          &escape($creationcontext).':'.$domcloner,
                   3186:                          $tryserver);
1.918     raeburn  3187:                 my @pairs=split(/\&/,$rep);
                   3188:                 foreach my $item (@pairs) {
                   3189:                     my ($key,$value)=split(/\=/,$item,2);
                   3190:                     $key = &unescape($key);
                   3191:                     next if ($key =~ /^error: 2 /);
                   3192:                     my $result = &thaw_unescape($value);
                   3193:                     if (ref($result) eq 'HASH') {
                   3194:                         $returnhash{$key}=$result;
                   3195:                     } else {
1.921     raeburn  3196:                         my @responses = split(/:/,$value);
                   3197:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3198:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3199:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3200:                         }
1.1008    raeburn  3201:                     }
1.353     www      3202:                 }
                   3203:             }
                   3204:         }
                   3205:     }
                   3206:     return %returnhash;
                   3207: }
                   3208: 
1.1055    raeburn  3209: sub courselastaccess {
                   3210:     my ($cdom,$cnum,$hostidref) = @_;
                   3211:     my %returnhash;
                   3212:     if ($cdom && $cnum) {
                   3213:         my $chome = &homeserver($cnum,$cdom);
                   3214:         if ($chome ne 'no_host') {
                   3215:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3216:             &extract_lastaccess(\%returnhash,$rep);
                   3217:         }
                   3218:     } else {
                   3219:         if (!$cdom) { $cdom=''; }
                   3220:         my %libserv = &all_library();
                   3221:         foreach my $tryserver (keys(%libserv)) {
                   3222:             if (ref($hostidref) eq 'ARRAY') {
                   3223:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3224:             } 
                   3225:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3226:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3227:                 &extract_lastaccess(\%returnhash,$rep);
                   3228:             }
                   3229:         }
                   3230:     }
                   3231:     return %returnhash;
                   3232: }
                   3233: 
                   3234: sub extract_lastaccess {
                   3235:     my ($returnhash,$rep) = @_;
                   3236:     if (ref($returnhash) eq 'HASH') {
                   3237:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3238:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3239:                  $rep eq '') {
                   3240:             my @pairs=split(/\&/,$rep);
                   3241:             foreach my $item (@pairs) {
                   3242:                 my ($key,$value)=split(/\=/,$item,2);
                   3243:                 $key = &unescape($key);
                   3244:                 next if ($key =~ /^error: 2 /);
                   3245:                 $returnhash->{$key} = &thaw_unescape($value);
                   3246:             }
                   3247:         }
                   3248:     }
                   3249:     return;
                   3250: }
                   3251: 
1.658     raeburn  3252: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3253: 
                   3254: sub dcmailput {
1.685     raeburn  3255:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3256:     my $status = &Apache::lonnet::critical(
1.740     www      3257:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3258:        &escape($message),$server);
1.662     raeburn  3259:     return $status;
                   3260: }
                   3261: 
1.658     raeburn  3262: sub dcmaildump {
                   3263:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3264:     my %returnhash=();
1.846     albertel 3265: 
                   3266:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3267:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3268:                                                          &escape($enddate).':';
                   3269: 	my @esc_senders=map { &escape($_)} @$senders;
                   3270: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3271: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3272:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3273:             if (($key) && ($value)) {
                   3274:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3275:             }
                   3276:         }
                   3277:     }
                   3278:     return %returnhash;
                   3279: }
1.662     raeburn  3280: # ---------------------------------------------------------- Domain roles
                   3281: 
                   3282: sub get_domain_roles {
                   3283:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3284:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3285:         $startdate = '.';
                   3286:     }
1.1018    raeburn  3287:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3288:         $enddate = '.';
                   3289:     }
1.922     raeburn  3290:     my $rolelist;
                   3291:     if (ref($roles) eq 'ARRAY') {
                   3292:         $rolelist = join(':',@{$roles});
                   3293:     }
1.662     raeburn  3294:     my %personnel = ();
1.841     albertel 3295: 
                   3296:     my %servers = &get_servers($dom,'library');
                   3297:     foreach my $tryserver (keys(%servers)) {
                   3298: 	%{$personnel{$tryserver}}=();
                   3299: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3300: 					    &escape($startdate).':'.
                   3301: 					    &escape($enddate).':'.
                   3302: 					    &escape($rolelist), $tryserver))) {
                   3303: 	    my ($key,$value) = split(/\=/,$line,2);
                   3304: 	    if (($key) && ($value)) {
                   3305: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3306: 	    }
                   3307: 	}
1.662     raeburn  3308:     }
                   3309:     return %personnel;
                   3310: }
1.658     raeburn  3311: 
1.1057    www      3312: # ----------------------------------------------------------- Interval timing 
1.149     www      3313: 
1.504     albertel 3314: sub get_first_access {
                   3315:     my ($type,$argsymb)=@_;
1.790     albertel 3316:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3317:     if ($argsymb) { $symb=$argsymb; }
                   3318:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3319:     if ($type eq 'course') {
                   3320: 	$res='course';
                   3321:     } elsif ($type eq 'map') {
1.588     albertel 3322: 	$res=&symbread($map);
                   3323:     } else {
                   3324: 	$res=$symb;
                   3325:     }
                   3326:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3327:     return $times{"$courseid\0$res"};
1.504     albertel 3328: }
                   3329: 
                   3330: sub set_first_access {
                   3331:     my ($type)=@_;
1.790     albertel 3332:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3333:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3334:     if ($type eq 'course') {
                   3335: 	$res='course';
                   3336:     } elsif ($type eq 'map') {
1.588     albertel 3337: 	$res=&symbread($map);
                   3338:     } else {
                   3339: 	$res=$symb;
                   3340:     }
                   3341:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3342:     if (!$firstaccess) {
1.588     albertel 3343: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3344:     }
                   3345:     return 'already_set';
1.504     albertel 3346: }
                   3347: 
1.110     www      3348: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3349: 
                   3350: sub expirespread {
                   3351:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3352:     my $cid=$env{'request.course.id'}; 
1.110     www      3353:     if ($cid) {
                   3354:        my $now=time;
                   3355:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3356:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3357:                             $env{'course.'.$cid.'.num'}.
1.110     www      3358: 	        	    ':nohist_expirationdates:'.
                   3359:                             &escape($key).'='.$now,
1.620     albertel 3360:                             $env{'course.'.$cid.'.home'})
1.110     www      3361:     }
                   3362:     return 'ok';
1.14      www      3363: }
                   3364: 
1.109     www      3365: # ----------------------------------------------------- Devalidate Spreadsheets
                   3366: 
                   3367: sub devalidate {
1.325     www      3368:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3369:     my $cid=$env{'request.course.id'}; 
1.109     www      3370:     if ($cid) {
1.391     matthew  3371:         # delete the stored spreadsheets for
                   3372:         # - the student level sheet of this user in course's homespace
                   3373:         # - the assessment level sheet for this resource 
                   3374:         #   for this user in user's homespace
1.553     albertel 3375: 	# - current conditional state info
1.325     www      3376: 	my $key=$uname.':'.$udom.':';
1.109     www      3377:         my $status=
1.299     matthew  3378: 	    &del('nohist_calculatedsheets',
1.391     matthew  3379: 		 [$key.'studentcalc:'],
1.620     albertel 3380: 		 $env{'course.'.$cid.'.domain'},
                   3381: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3382: 		.' '.
                   3383: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3384: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3385:         unless ($status eq 'ok ok') {
                   3386:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3387:                     $uname.' at '.$udom.' for '.
1.109     www      3388: 		    $symb.': '.$status);
1.133     albertel 3389:         }
1.553     albertel 3390: 	&delenv('user.state.'.$cid);
1.109     www      3391:     }
                   3392: }
                   3393: 
1.265     albertel 3394: sub get_scalar {
                   3395:     my ($string,$end) = @_;
                   3396:     my $value;
                   3397:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3398: 	$value = $1;
                   3399:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3400: 	$value = $1;
                   3401:     }
                   3402:     return &unescape($value);
                   3403: }
                   3404: 
                   3405: sub array2str {
                   3406:   my (@array) = @_;
                   3407:   my $result=&arrayref2str(\@array);
                   3408:   $result=~s/^__ARRAY_REF__//;
                   3409:   $result=~s/__END_ARRAY_REF__$//;
                   3410:   return $result;
                   3411: }
                   3412: 
1.204     albertel 3413: sub arrayref2str {
                   3414:   my ($arrayref) = @_;
1.265     albertel 3415:   my $result='__ARRAY_REF__';
1.204     albertel 3416:   foreach my $elem (@$arrayref) {
1.265     albertel 3417:     if(ref($elem) eq 'ARRAY') {
                   3418:       $result.=&arrayref2str($elem).'&';
                   3419:     } elsif(ref($elem) eq 'HASH') {
                   3420:       $result.=&hashref2str($elem).'&';
                   3421:     } elsif(ref($elem)) {
                   3422:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3423:     } else {
                   3424:       $result.=&escape($elem).'&';
                   3425:     }
                   3426:   }
                   3427:   $result=~s/\&$//;
1.265     albertel 3428:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3429:   return $result;
                   3430: }
                   3431: 
1.168     albertel 3432: sub hash2str {
1.204     albertel 3433:   my (%hash) = @_;
                   3434:   my $result=&hashref2str(\%hash);
1.265     albertel 3435:   $result=~s/^__HASH_REF__//;
                   3436:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3437:   return $result;
                   3438: }
                   3439: 
                   3440: sub hashref2str {
                   3441:   my ($hashref)=@_;
1.265     albertel 3442:   my $result='__HASH_REF__';
1.800     albertel 3443:   foreach my $key (sort(keys(%$hashref))) {
                   3444:     if (ref($key) eq 'ARRAY') {
                   3445:       $result.=&arrayref2str($key).'=';
                   3446:     } elsif (ref($key) eq 'HASH') {
                   3447:       $result.=&hashref2str($key).'=';
                   3448:     } elsif (ref($key)) {
1.265     albertel 3449:       $result.='=';
1.800     albertel 3450:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3451:     } else {
1.800     albertel 3452: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3453:     }
                   3454: 
1.800     albertel 3455:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3456:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3457:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3458:       $result.=&hashref2str($hashref->{$key}).'&';
                   3459:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3460:        $result.='&';
1.800     albertel 3461:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3462:     } else {
1.800     albertel 3463:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3464:     }
                   3465:   }
1.168     albertel 3466:   $result=~s/\&$//;
1.265     albertel 3467:   $result .= '__END_HASH_REF__';
1.168     albertel 3468:   return $result;
                   3469: }
                   3470: 
                   3471: sub str2hash {
1.265     albertel 3472:     my ($string)=@_;
                   3473:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3474:     return %$hash;
                   3475: }
                   3476: 
                   3477: sub str2hashref {
1.168     albertel 3478:   my ($string) = @_;
1.265     albertel 3479: 
                   3480:   my %hash;
                   3481: 
                   3482:   if($string !~ /^__HASH_REF__/) {
                   3483:       if (! ($string eq '' || !defined($string))) {
                   3484: 	  $hash{'error'}='Not hash reference';
                   3485:       }
                   3486:       return (\%hash, $string);
                   3487:   }
                   3488: 
                   3489:   $string =~ s/^__HASH_REF__//;
                   3490: 
                   3491:   while($string !~ /^__END_HASH_REF__/) {
                   3492:       #key
                   3493:       my $key='';
                   3494:       if($string =~ /^__HASH_REF__/) {
                   3495:           ($key, $string)=&str2hashref($string);
                   3496:           if(defined($key->{'error'})) {
                   3497:               $hash{'error'}='Bad data';
                   3498:               return (\%hash, $string);
                   3499:           }
                   3500:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3501:           ($key, $string)=&str2arrayref($string);
                   3502:           if($key->[0] eq 'Array reference error') {
                   3503:               $hash{'error'}='Bad data';
                   3504:               return (\%hash, $string);
                   3505:           }
                   3506:       } else {
                   3507:           $string =~ s/^(.*?)=//;
1.267     albertel 3508: 	  $key=&unescape($1);
1.265     albertel 3509:       }
                   3510:       $string =~ s/^=//;
                   3511: 
                   3512:       #value
                   3513:       my $value='';
                   3514:       if($string =~ /^__HASH_REF__/) {
                   3515:           ($value, $string)=&str2hashref($string);
                   3516:           if(defined($value->{'error'})) {
                   3517:               $hash{'error'}='Bad data';
                   3518:               return (\%hash, $string);
                   3519:           }
                   3520:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3521:           ($value, $string)=&str2arrayref($string);
                   3522:           if($value->[0] eq 'Array reference error') {
                   3523:               $hash{'error'}='Bad data';
                   3524:               return (\%hash, $string);
                   3525:           }
                   3526:       } else {
                   3527: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3528:       }
                   3529:       $string =~ s/^&//;
                   3530: 
                   3531:       $hash{$key}=$value;
1.204     albertel 3532:   }
1.265     albertel 3533: 
                   3534:   $string =~ s/^__END_HASH_REF__//;
                   3535: 
                   3536:   return (\%hash, $string);
1.204     albertel 3537: }
                   3538: 
                   3539: sub str2array {
1.265     albertel 3540:     my ($string)=@_;
                   3541:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3542:     return @$array;
                   3543: }
                   3544: 
                   3545: sub str2arrayref {
1.204     albertel 3546:   my ($string) = @_;
1.265     albertel 3547:   my @array;
                   3548: 
                   3549:   if($string !~ /^__ARRAY_REF__/) {
                   3550:       if (! ($string eq '' || !defined($string))) {
                   3551: 	  $array[0]='Array reference error';
                   3552:       }
                   3553:       return (\@array, $string);
                   3554:   }
                   3555: 
                   3556:   $string =~ s/^__ARRAY_REF__//;
                   3557: 
                   3558:   while($string !~ /^__END_ARRAY_REF__/) {
                   3559:       my $value='';
                   3560:       if($string =~ /^__HASH_REF__/) {
                   3561:           ($value, $string)=&str2hashref($string);
                   3562:           if(defined($value->{'error'})) {
                   3563:               $array[0] ='Array reference error';
                   3564:               return (\@array, $string);
                   3565:           }
                   3566:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3567:           ($value, $string)=&str2arrayref($string);
                   3568:           if($value->[0] eq 'Array reference error') {
                   3569:               $array[0] ='Array reference error';
                   3570:               return (\@array, $string);
                   3571:           }
                   3572:       } else {
                   3573: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3574:       }
                   3575:       $string =~ s/^&//;
                   3576: 
                   3577:       push(@array, $value);
1.191     harris41 3578:   }
1.265     albertel 3579: 
                   3580:   $string =~ s/^__END_ARRAY_REF__//;
                   3581: 
                   3582:   return (\@array, $string);
1.168     albertel 3583: }
                   3584: 
1.167     albertel 3585: # -------------------------------------------------------------------Temp Store
                   3586: 
1.168     albertel 3587: sub tmpreset {
                   3588:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3589:   if (!$symb) {
                   3590:     $symb=&symbread();
1.620     albertel 3591:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3592:   }
                   3593:   $symb=escape($symb);
                   3594: 
1.620     albertel 3595:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3596:   $namespace=~s/\//\_/g;
                   3597:   $namespace=~s/\W//g;
                   3598: 
1.620     albertel 3599:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3600:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3601:   if ($domain eq 'public' && $stuname eq 'public') {
                   3602:       $stuname=$ENV{'REMOTE_ADDR'};
                   3603:   }
1.168     albertel 3604:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3605:   my %hash;
                   3606:   if (tie(%hash,'GDBM_File',
                   3607: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3608: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3609:     foreach my $key (keys(%hash)) {
1.180     albertel 3610:       if ($key=~ /:$symb/) {
1.168     albertel 3611: 	delete($hash{$key});
                   3612:       }
                   3613:     }
                   3614:   }
                   3615: }
                   3616: 
1.167     albertel 3617: sub tmpstore {
1.168     albertel 3618:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3619: 
                   3620:   if (!$symb) {
                   3621:     $symb=&symbread();
1.620     albertel 3622:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3623:   }
                   3624:   $symb=escape($symb);
                   3625: 
                   3626:   if (!$namespace) {
                   3627:     # I don't think we would ever want to store this for a course.
                   3628:     # it seems this will only be used if we don't have a course.
1.620     albertel 3629:     #$namespace=$env{'request.course.id'};
1.168     albertel 3630:     #if (!$namespace) {
1.620     albertel 3631:       $namespace=$env{'request.state'};
1.168     albertel 3632:     #}
                   3633:   }
                   3634:   $namespace=~s/\//\_/g;
                   3635:   $namespace=~s/\W//g;
1.620     albertel 3636:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3637:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3638:   if ($domain eq 'public' && $stuname eq 'public') {
                   3639:       $stuname=$ENV{'REMOTE_ADDR'};
                   3640:   }
1.168     albertel 3641:   my $now=time;
                   3642:   my %hash;
                   3643:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3644:   if (tie(%hash,'GDBM_File',
                   3645: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3646: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3647:     $hash{"version:$symb"}++;
                   3648:     my $version=$hash{"version:$symb"};
                   3649:     my $allkeys=''; 
                   3650:     foreach my $key (keys(%$storehash)) {
                   3651:       $allkeys.=$key.':';
1.591     albertel 3652:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3653:     }
                   3654:     $hash{"$version:$symb:timestamp"}=$now;
                   3655:     $allkeys.='timestamp';
                   3656:     $hash{"$version:keys:$symb"}=$allkeys;
                   3657:     if (untie(%hash)) {
                   3658:       return 'ok';
                   3659:     } else {
                   3660:       return "error:$!";
                   3661:     }
                   3662:   } else {
                   3663:     return "error:$!";
                   3664:   }
                   3665: }
1.167     albertel 3666: 
1.168     albertel 3667: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3668: 
1.168     albertel 3669: sub tmprestore {
                   3670:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3671: 
1.168     albertel 3672:   if (!$symb) {
                   3673:     $symb=&symbread();
1.620     albertel 3674:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3675:   }
                   3676:   $symb=escape($symb);
                   3677: 
1.620     albertel 3678:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3679: 
1.620     albertel 3680:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3681:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3682:   if ($domain eq 'public' && $stuname eq 'public') {
                   3683:       $stuname=$ENV{'REMOTE_ADDR'};
                   3684:   }
1.168     albertel 3685:   my %returnhash;
                   3686:   $namespace=~s/\//\_/g;
                   3687:   $namespace=~s/\W//g;
                   3688:   my %hash;
                   3689:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3690:   if (tie(%hash,'GDBM_File',
                   3691: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3692: 	  &GDBM_READER(),0640)) {
1.168     albertel 3693:     my $version=$hash{"version:$symb"};
                   3694:     $returnhash{'version'}=$version;
                   3695:     my $scope;
                   3696:     for ($scope=1;$scope<=$version;$scope++) {
                   3697:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3698:       my @keys=split(/:/,$vkeys);
                   3699:       my $key;
                   3700:       $returnhash{"$scope:keys"}=$vkeys;
                   3701:       foreach $key (@keys) {
1.591     albertel 3702: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3703: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3704:       }
                   3705:     }
1.168     albertel 3706:     if (!(untie(%hash))) {
                   3707:       return "error:$!";
                   3708:     }
                   3709:   } else {
                   3710:     return "error:$!";
                   3711:   }
                   3712:   return %returnhash;
1.167     albertel 3713: }
                   3714: 
1.9       www      3715: # ----------------------------------------------------------------------- Store
                   3716: 
                   3717: sub store {
1.124     www      3718:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3719:     my $home='';
                   3720: 
1.168     albertel 3721:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3722: 
1.213     www      3723:     $symb=&symbclean($symb);
1.122     albertel 3724:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3725: 
1.620     albertel 3726:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3727:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3728: 
                   3729:     &devalidate($symb,$stuname,$domain);
1.109     www      3730: 
                   3731:     $symb=escape($symb);
1.187     www      3732:     if (!$namespace) { 
1.620     albertel 3733:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3734:           return ''; 
                   3735:        } 
                   3736:     }
1.620     albertel 3737:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3738: 
                   3739:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3740:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3741: 
1.12      www      3742:     my $namevalue='';
1.800     albertel 3743:     foreach my $key (keys(%$storehash)) {
                   3744:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3745:     }
1.12      www      3746:     $namevalue=~s/\&$//;
1.187     www      3747:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3748:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3749: }
                   3750: 
1.47      www      3751: # -------------------------------------------------------------- Critical Store
                   3752: 
                   3753: sub cstore {
1.124     www      3754:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3755:     my $home='';
                   3756: 
1.168     albertel 3757:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3758: 
1.213     www      3759:     $symb=&symbclean($symb);
1.122     albertel 3760:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3761: 
1.620     albertel 3762:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3763:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3764: 
                   3765:     &devalidate($symb,$stuname,$domain);
1.109     www      3766: 
                   3767:     $symb=escape($symb);
1.187     www      3768:     if (!$namespace) { 
1.620     albertel 3769:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3770:           return ''; 
                   3771:        } 
                   3772:     }
1.620     albertel 3773:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3774: 
                   3775:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3776:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3777: 
1.47      www      3778:     my $namevalue='';
1.800     albertel 3779:     foreach my $key (keys(%$storehash)) {
                   3780:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3781:     }
1.47      www      3782:     $namevalue=~s/\&$//;
1.187     www      3783:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3784:     return critical
                   3785:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3786: }
                   3787: 
1.9       www      3788: # --------------------------------------------------------------------- Restore
                   3789: 
                   3790: sub restore {
1.124     www      3791:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3792:     my $home='';
                   3793: 
1.168     albertel 3794:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3795: 
1.122     albertel 3796:     if (!$symb) {
                   3797:       unless ($symb=escape(&symbread())) { return ''; }
                   3798:     } else {
1.213     www      3799:       $symb=&escape(&symbclean($symb));
1.122     albertel 3800:     }
1.188     www      3801:     if (!$namespace) { 
1.620     albertel 3802:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3803:           return ''; 
                   3804:        } 
                   3805:     }
1.620     albertel 3806:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3807:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3808:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3809:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3810: 
1.12      www      3811:     my %returnhash=();
1.800     albertel 3812:     foreach my $line (split(/\&/,$answer)) {
                   3813: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3814:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3815:     }
1.75      www      3816:     my $version;
                   3817:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3818:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3819:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3820:        }
1.75      www      3821:     }
1.13      www      3822:     return %returnhash;
1.34      www      3823: }
                   3824: 
                   3825: # ---------------------------------------------------------- Course Description
                   3826: 
                   3827: sub coursedescription {
1.731     albertel 3828:     my ($courseid,$args)=@_;
1.34      www      3829:     $courseid=~s/^\///;
1.49      www      3830:     $courseid=~s/\_/\//g;
1.34      www      3831:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3832:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3833:     my $normalid=$cdomain.'_'.$cnum;
                   3834:     # need to always cache even if we get errors otherwise we keep 
                   3835:     # trying and trying and trying to get the course description.
                   3836:     my %envhash=();
                   3837:     my %returnhash=();
1.731     albertel 3838:     
                   3839:     my $expiretime=600;
                   3840:     if ($env{'request.course.id'} eq $normalid) {
                   3841: 	$expiretime=120;
                   3842:     }
                   3843: 
                   3844:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3845:     if (!$args->{'freshen_cache'}
                   3846: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3847: 	foreach my $key (keys(%env)) {
                   3848: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3849: 	    my ($setting) = $1;
                   3850: 	    $returnhash{$setting} = $env{$key};
                   3851: 	}
                   3852: 	return %returnhash;
                   3853:     }
                   3854: 
                   3855:     # get the data agin
                   3856:     if (!$args->{'one_time'}) {
                   3857: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3858:     }
1.811     albertel 3859: 
1.34      www      3860:     if ($chome ne 'no_host') {
1.302     albertel 3861:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3862:        if (!exists($returnhash{'con_lost'})) {
                   3863:            $returnhash{'home'}= $chome;
                   3864: 	   $returnhash{'domain'} = $cdomain;
                   3865: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3866:            if (!defined($returnhash{'type'})) {
                   3867:                $returnhash{'type'} = 'Course';
                   3868:            }
1.130     albertel 3869:            while (my ($name,$value) = each %returnhash) {
1.53      www      3870:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3871:            }
1.270     www      3872:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3873:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3874: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3875:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3876:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3877:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3878:        }
                   3879:     }
1.731     albertel 3880:     if (!$args->{'one_time'}) {
1.949     raeburn  3881: 	&appenv(\%envhash);
1.731     albertel 3882:     }
1.302     albertel 3883:     return %returnhash;
1.461     www      3884: }
                   3885: 
                   3886: # -------------------------------------------------See if a user is privileged
                   3887: 
                   3888: sub privileged {
                   3889:     my ($username,$domain)=@_;
                   3890:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3891: 			&homeserver($username,$domain));
1.1033    raeburn  3892:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3893:         ($rolesdump =~ /^error:/)) {
                   3894:         return 0;
                   3895:     }
1.461     www      3896:     my $now=time;
                   3897:     if ($rolesdump ne '') {
1.800     albertel 3898:         foreach my $entry (split(/&/,$rolesdump)) {
                   3899: 	    if ($entry!~/^rolesdef_/) {
                   3900: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3901: 		$area=~s/\_\w\w$//;
                   3902: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3903: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3904: 		    my $active=1;
                   3905: 		    if ($tend) {
                   3906: 			if ($tend<$now) { $active=0; }
                   3907: 		    }
                   3908: 		    if ($tstart) {
                   3909: 			if ($tstart>$now) { $active=0; }
                   3910: 		    }
                   3911: 		    if ($active) { return 1; }
                   3912: 		}
                   3913: 	    }
                   3914: 	}
                   3915:     }
                   3916:     return 0;
1.9       www      3917: }
1.1       albertel 3918: 
1.103     harris41 3919: # -------------------------------------------------------- Get user privileges
1.11      www      3920: 
                   3921: sub rolesinit {
                   3922:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  3923:     my $now=time;
                   3924:     my %userroles = ('user.login.time' => $now);
1.11      www      3925:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033    raeburn  3926:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3927:         ($rolesdump =~ /^error:/)) { 
                   3928:         return \%userroles;
                   3929:     }
1.11      www      3930:     my %allroles=();
1.678     raeburn  3931:     my %allgroups=();   
                   3932:     my $group_privs;
1.11      www      3933: 
                   3934:     if ($rolesdump ne '') {
1.800     albertel 3935:         foreach my $entry (split(/&/,$rolesdump)) {
                   3936: 	  if ($entry!~/^rolesdef_/) {
                   3937:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3938: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3939:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3940: 	    if ($role=~/^cr/) { 
1.807     albertel 3941: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3942: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3943: 		    ($tend,$tstart)=split('_',$trest);
                   3944: 		} else {
                   3945: 		    $trole=$role;
                   3946: 		}
1.678     raeburn  3947:             } elsif ($role =~ m|^gr/|) {
                   3948:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3949:                 ($trole,$group_privs) = split(/\//,$trole);
                   3950:                 $group_privs = &unescape($group_privs);
1.587     albertel 3951: 	    } else {
                   3952: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3953: 	    }
1.743     albertel 3954: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3955: 					 $username);
                   3956: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3957:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3958:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3959:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3960: 		my $spec=$trole.'.'.$area;
                   3961: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3962: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3963:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3964:                 } elsif ($trole eq 'gr') {
                   3965:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3966: 		} else {
1.567     raeburn  3967:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3968: 		}
1.12      www      3969:             }
1.662     raeburn  3970:           }
1.191     harris41 3971:         }
1.743     albertel 3972:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3973:         $userroles{'user.adv'}    = $adv;
                   3974: 	$userroles{'user.author'} = $author;
1.620     albertel 3975:         $env{'user.adv'}=$adv;
1.11      www      3976:     }
1.743     albertel 3977:     return \%userroles;  
1.11      www      3978: }
                   3979: 
1.567     raeburn  3980: sub set_arearole {
                   3981:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3982: # log the associated role with the area
                   3983:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3984:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3985: }
                   3986: 
                   3987: sub custom_roleprivs {
                   3988:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3989:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3990:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3991:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3992:         my ($rdummy,$roledef)=
                   3993:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3994:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3995:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3996:             if (defined($syspriv)) {
1.1043    raeburn  3997:                 if ($trest =~ /^$match_community$/) {
                   3998:                     $syspriv =~ s/bre\&S//; 
                   3999:                 }
1.567     raeburn  4000:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4001:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4002:             }
                   4003:             if ($tdomain ne '') {
                   4004:                 if (defined($dompriv)) {
                   4005:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4006:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4007:                 }
                   4008:                 if (($trest ne '') && (defined($coursepriv))) {
                   4009:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4010:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4011:                 }
                   4012:             }
                   4013:         }
                   4014:     }
                   4015: }
                   4016: 
1.678     raeburn  4017: sub group_roleprivs {
                   4018:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4019:     my $access = 1;
                   4020:     my $now = time;
                   4021:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4022:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4023:     if ($access) {
1.811     albertel 4024:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4025:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4026:     }
                   4027: }
1.567     raeburn  4028: 
                   4029: sub standard_roleprivs {
                   4030:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4031:     if (defined($pr{$trole.':s'})) {
                   4032:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4033:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4034:     }
                   4035:     if ($tdomain ne '') {
                   4036:         if (defined($pr{$trole.':d'})) {
                   4037:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4038:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4039:         }
                   4040:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4041:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4042:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4043:         }
                   4044:     }
                   4045: }
                   4046: 
                   4047: sub set_userprivs {
1.1064    raeburn  4048:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4049:     my $author=0;
                   4050:     my $adv=0;
1.678     raeburn  4051:     my %grouproles = ();
                   4052:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4053:         my @groupkeys; 
1.1000    raeburn  4054:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4055:             push(@groupkeys,$role);
                   4056:         }
                   4057:         if (ref($groups_roles) eq 'HASH') {
                   4058:             foreach my $key (keys(%{$groups_roles})) {
                   4059:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4060:                     push(@groupkeys,$key);
                   4061:                 }
                   4062:             }
                   4063:         }
                   4064:         if (@groupkeys > 0) {
                   4065:             foreach my $role (@groupkeys) {
                   4066:                 my ($trole,$area,$sec,$extendedarea);
                   4067:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4068:                     $trole = $1;
                   4069:                     $area = $2;
                   4070:                     $sec = $3;
                   4071:                     $extendedarea = $area.$sec;
                   4072:                     if (exists($$allgroups{$area})) {
                   4073:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4074:                             my $spec = $trole.'.'.$extendedarea;
                   4075:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4076:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4077:                         }
1.678     raeburn  4078:                     }
                   4079:                 }
                   4080:             }
                   4081:         }
                   4082:     }
1.800     albertel 4083:     foreach my $group (keys(%grouproles)) {
                   4084:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4085:     }
1.800     albertel 4086:     foreach my $role (keys(%{$allroles})) {
                   4087:         my %thesepriv;
1.941     raeburn  4088:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4089:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4090:             if ($item ne '') {
                   4091:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4092:                 if ($restrictions eq '') {
                   4093:                     $thesepriv{$privilege}='F';
                   4094:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4095:                     $thesepriv{$privilege}.=$restrictions;
                   4096:                 }
                   4097:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4098:             }
                   4099:         }
                   4100:         my $thesestr='';
1.800     albertel 4101:         foreach my $priv (keys(%thesepriv)) {
                   4102: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4103: 	}
                   4104:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4105:     }
                   4106:     return ($author,$adv);
                   4107: }
                   4108: 
1.994     raeburn  4109: sub role_status {
1.1002    raeburn  4110:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4111:     my @pwhere = ();
                   4112:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4113:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4114:         unless (!defined($$role) || $$role eq '') {
                   4115:             $$where=join('.',@pwhere);
                   4116:             $$trolecode=$$role.'.'.$$where;
                   4117:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4118:             $$tstatus='is';
                   4119:             if ($$tstart && $$tstart>$then) {
                   4120:                 $$tstatus='future';
1.1034    raeburn  4121:                 if ($$tstart<$now) {
                   4122:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4123:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4124:                             my (%allroles,%allgroups,$group_privs,
                   4125:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4126:                             my %userroles = (
                   4127:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4128:                             );
1.1064    raeburn  4129:                             @rolecodes = ('cm'); 
1.1002    raeburn  4130:                             my $spec=$$role.'.'.$$where;
                   4131:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4132:                             if ($$role =~ /^cr\//) {
                   4133:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4134:                                 push(@rolecodes,'cr');
1.1002    raeburn  4135:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4136:                                 push(@rolecodes,$$role);
1.1002    raeburn  4137:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4138:                                                     $env{'user.name'});
1.1064    raeburn  4139:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4140:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4141:                                 $group_privs = &unescape($group_privs);
                   4142:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4143:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4144:                                 if (keys(%course_roles) > 0) {
                   4145:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4146:                                     if ($tdomain ne '' && $tnum ne '') { 
                   4147:                                         foreach my $key (keys(%course_roles)) {
                   4148:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4149:                                                 my $crsrole = $1;
                   4150:                                                 my $crssec = $2;
                   4151:                                                 if ($crsrole =~ /^cr/) {
                   4152:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4153:                                                         push(@rolecodes,'cr');
                   4154:                                                     }
                   4155:                                                 } else {
                   4156:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4157:                                                         push(@rolecodes,$crsrole);
                   4158:                                                     }
                   4159:                                                 }
                   4160:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4161:                                                 if ($crssec ne '') {
                   4162:                                                     $rolekey .= '/'.$crssec;
                   4163:                                                 }
                   4164:                                                 $rolekey .= './';
                   4165:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4166:                                             }
                   4167:                                         }
                   4168:                                     }
                   4169:                                 }
1.1002    raeburn  4170:                             } else {
1.1064    raeburn  4171:                                 push(@rolecodes,$$role);
1.1002    raeburn  4172:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4173:                             }
1.1064    raeburn  4174:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4175:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4176:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4177:                         }
                   4178:                     }
1.1034    raeburn  4179:                     $$tstatus = 'is';
1.1002    raeburn  4180:                 }
1.994     raeburn  4181:             }
                   4182:             if ($$tend) {
                   4183:                 if ($$tend<$then) {
                   4184:                     $$tstatus='expired';
                   4185:                 } elsif ($$tend<$now) {
                   4186:                     $$tstatus='will_not';
                   4187:                 }
                   4188:             }
                   4189:         }
                   4190:     }
                   4191: }
                   4192: 
                   4193: sub check_adhoc_privs {
1.1002    raeburn  4194:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4195:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4196:     if ($env{$cckey}) {
                   4197:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4198:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4199:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4200:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4201:         }
                   4202:     } else {
                   4203:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4204:     }
                   4205: }
                   4206: 
                   4207: sub set_adhoc_privileges {
                   4208: # role can be cc or ca
                   4209:     my ($dcdom,$pickedcourse,$role) = @_;
                   4210:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4211:     my $spec = $role.'.'.$area;
                   4212:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4213:                                   $env{'user.name'});
                   4214:     my %ccrole = ();
                   4215:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4216:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4217:     &appenv(\%userroles,[$role,'cm']);
                   4218:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4219:     &appenv( {'request.role'        => $spec,
                   4220:               'request.role.domain' => $dcdom,
                   4221:               'request.course.sec'  => ''
                   4222:              }
                   4223:            );
                   4224:     my $tadv=0;
                   4225:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4226:     &appenv({'request.role.adv'    => $tadv});
                   4227: }
                   4228: 
1.12      www      4229: # --------------------------------------------------------------- get interface
                   4230: 
                   4231: sub get {
1.131     albertel 4232:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4233:    my $items='';
1.800     albertel 4234:    foreach my $item (@$storearr) {
                   4235:        $items.=&escape($item).'&';
1.191     harris41 4236:    }
1.12      www      4237:    $items=~s/\&$//;
1.620     albertel 4238:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4239:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4240:    my $uhome=&homeserver($uname,$udomain);
                   4241: 
1.133     albertel 4242:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4243:    my @pairs=split(/\&/,$rep);
1.273     albertel 4244:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4245:      return @pairs;
                   4246:    }
1.15      www      4247:    my %returnhash=();
1.42      www      4248:    my $i=0;
1.800     albertel 4249:    foreach my $item (@$storearr) {
                   4250:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4251:       $i++;
1.191     harris41 4252:    }
1.15      www      4253:    return %returnhash;
1.27      www      4254: }
                   4255: 
                   4256: # --------------------------------------------------------------- del interface
                   4257: 
                   4258: sub del {
1.133     albertel 4259:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4260:    my $items='';
1.800     albertel 4261:    foreach my $item (@$storearr) {
                   4262:        $items.=&escape($item).'&';
1.191     harris41 4263:    }
1.984     neumanie 4264: 
1.27      www      4265:    $items=~s/\&$//;
1.620     albertel 4266:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4267:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4268:    my $uhome=&homeserver($uname,$udomain);
                   4269:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4270: }
                   4271: 
                   4272: # -------------------------------------------------------------- dump interface
                   4273: 
                   4274: sub dump {
1.755     albertel 4275:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4276:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4277:     if (!$uname) { $uname=$env{'user.name'}; }
                   4278:     my $uhome=&homeserver($uname,$udomain);
                   4279:     if ($regexp) {
                   4280: 	$regexp=&escape($regexp);
                   4281:     } else {
                   4282: 	$regexp='.';
                   4283:     }
                   4284:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4285:     my @pairs=split(/\&/,$rep);
                   4286:     my %returnhash=();
                   4287:     foreach my $item (@pairs) {
                   4288: 	my ($key,$value)=split(/=/,$item,2);
                   4289: 	$key = &unescape($key);
                   4290: 	next if ($key =~ /^error: 2 /);
                   4291: 	$returnhash{$key}=&thaw_unescape($value);
                   4292:     }
                   4293:     return %returnhash;
1.407     www      4294: }
                   4295: 
1.717     albertel 4296: # --------------------------------------------------------- dumpstore interface
                   4297: 
                   4298: sub dumpstore {
                   4299:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4300:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4301:    if (!$uname) { $uname=$env{'user.name'}; }
                   4302:    my $uhome=&homeserver($uname,$udomain);
                   4303:    if ($regexp) {
                   4304:        $regexp=&escape($regexp);
                   4305:    } else {
                   4306:        $regexp='.';
                   4307:    }
                   4308:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4309:    my @pairs=split(/\&/,$rep);
                   4310:    my %returnhash=();
                   4311:    foreach my $item (@pairs) {
                   4312:        my ($key,$value)=split(/=/,$item,2);
                   4313:        next if ($key =~ /^error: 2 /);
                   4314:        $returnhash{$key}=&thaw_unescape($value);
                   4315:    }
                   4316:    return %returnhash;
1.717     albertel 4317: }
                   4318: 
1.407     www      4319: # -------------------------------------------------------------- keys interface
                   4320: 
                   4321: sub getkeys {
                   4322:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4323:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4324:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4325:    my $uhome=&homeserver($uname,$udomain);
                   4326:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4327:    my @keyarray=();
1.800     albertel 4328:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4329:       next if ($key =~ /^error: 2 /);
1.800     albertel 4330:       push(@keyarray,&unescape($key));
1.407     www      4331:    }
                   4332:    return @keyarray;
1.318     matthew  4333: }
                   4334: 
1.319     matthew  4335: # --------------------------------------------------------------- currentdump
                   4336: sub currentdump {
1.328     matthew  4337:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4338:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4339:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4340:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4341:    my $uhome = &homeserver($sname,$sdom);
                   4342:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4343:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4344:    #
1.318     matthew  4345:    my %returnhash=();
1.319     matthew  4346:    #
                   4347:    if ($rep eq "unknown_cmd") { 
                   4348:        # an old lond will not know currentdump
                   4349:        # Do a dump and make it look like a currentdump
1.822     albertel 4350:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4351:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4352:        my %hash = @tmp;
                   4353:        @tmp=();
1.424     matthew  4354:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4355:    } else {
                   4356:        my @pairs=split(/\&/,$rep);
1.800     albertel 4357:        foreach my $pair (@pairs) {
                   4358:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4359:            my ($symb,$param) = split(/:/,$key);
                   4360:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4361:                                                         &thaw_unescape($value);
1.319     matthew  4362:        }
1.191     harris41 4363:    }
1.12      www      4364:    return %returnhash;
1.424     matthew  4365: }
                   4366: 
                   4367: sub convert_dump_to_currentdump{
                   4368:     my %hash = %{shift()};
                   4369:     my %returnhash;
                   4370:     # Code ripped from lond, essentially.  The only difference
                   4371:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4372:     # we might run in to problems with parameter names =~ /^v\./
                   4373:     while (my ($key,$value) = each(%hash)) {
                   4374:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4375: 	$symb  = &unescape($symb);
                   4376: 	$param = &unescape($param);
1.424     matthew  4377:         next if ($v eq 'version' || $symb eq 'keys');
                   4378:         next if (exists($returnhash{$symb}) &&
                   4379:                  exists($returnhash{$symb}->{$param}) &&
                   4380:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4381:         $returnhash{$symb}->{$param}=$value;
                   4382:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4383:     }
                   4384:     #
                   4385:     # Remove all of the keys in the hashes which keep track of
                   4386:     # the version of the parameter.
                   4387:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4388:         # use a foreach because we are going to delete from the hash.
                   4389:         foreach my $key (keys(%$param_hash)) {
                   4390:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4391:         }
                   4392:     }
                   4393:     return \%returnhash;
1.12      www      4394: }
                   4395: 
1.627     albertel 4396: # ------------------------------------------------------ critical inc interface
                   4397: 
                   4398: sub cinc {
                   4399:     return &inc(@_,'critical');
                   4400: }
                   4401: 
1.449     matthew  4402: # --------------------------------------------------------------- inc interface
                   4403: 
                   4404: sub inc {
1.627     albertel 4405:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4406:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4407:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4408:     my $uhome=&homeserver($uname,$udomain);
                   4409:     my $items='';
                   4410:     if (! ref($store)) {
                   4411:         # got a single value, so use that instead
                   4412:         $items = &escape($store).'=&';
                   4413:     } elsif (ref($store) eq 'SCALAR') {
                   4414:         $items = &escape($$store).'=&';        
                   4415:     } elsif (ref($store) eq 'ARRAY') {
                   4416:         $items = join('=&',map {&escape($_);} @{$store});
                   4417:     } elsif (ref($store) eq 'HASH') {
                   4418:         while (my($key,$value) = each(%{$store})) {
                   4419:             $items.= &escape($key).'='.&escape($value).'&';
                   4420:         }
                   4421:     }
                   4422:     $items=~s/\&$//;
1.627     albertel 4423:     if ($critical) {
                   4424: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4425:     } else {
                   4426: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4427:     }
1.449     matthew  4428: }
                   4429: 
1.12      www      4430: # --------------------------------------------------------------- put interface
                   4431: 
                   4432: sub put {
1.134     albertel 4433:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4434:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4435:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4436:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4437:    my $items='';
1.800     albertel 4438:    foreach my $item (keys(%$storehash)) {
                   4439:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4440:    }
1.12      www      4441:    $items=~s/\&$//;
1.134     albertel 4442:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4443: }
                   4444: 
1.631     albertel 4445: # ------------------------------------------------------------ newput interface
                   4446: 
                   4447: sub newput {
                   4448:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4449:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4450:    if (!$uname) { $uname=$env{'user.name'}; }
                   4451:    my $uhome=&homeserver($uname,$udomain);
                   4452:    my $items='';
                   4453:    foreach my $key (keys(%$storehash)) {
                   4454:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4455:    }
                   4456:    $items=~s/\&$//;
                   4457:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4458: }
                   4459: 
                   4460: # ---------------------------------------------------------  putstore interface
                   4461: 
1.524     raeburn  4462: sub putstore {
1.715     albertel 4463:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4464:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4465:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4466:    my $uhome=&homeserver($uname,$udomain);
                   4467:    my $items='';
1.715     albertel 4468:    foreach my $key (keys(%$storehash)) {
                   4469:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4470:    }
1.715     albertel 4471:    $items=~s/\&$//;
1.716     albertel 4472:    my $esc_symb=&escape($symb);
                   4473:    my $esc_v=&escape($version);
1.715     albertel 4474:    my $reply =
1.716     albertel 4475:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4476: 	      $uhome);
                   4477:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4478:        # gfall back to way things use to be done
1.715     albertel 4479:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4480: 			    $uname);
1.524     raeburn  4481:    }
1.715     albertel 4482:    return $reply;
                   4483: }
                   4484: 
                   4485: sub old_putstore {
1.716     albertel 4486:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4487:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4488:     if (!$uname) { $uname=$env{'user.name'}; }
                   4489:     my $uhome=&homeserver($uname,$udomain);
                   4490:     my %newstorehash;
1.800     albertel 4491:     foreach my $item (keys(%$storehash)) {
                   4492: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4493: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4494:     }
                   4495:     my $items='';
                   4496:     my %allitems = ();
1.800     albertel 4497:     foreach my $item (keys(%newstorehash)) {
                   4498: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4499: 	    my $key = $1.':keys:'.$2;
                   4500: 	    $allitems{$key} .= $3.':';
                   4501: 	}
1.800     albertel 4502: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4503:     }
1.800     albertel 4504:     foreach my $item (keys(%allitems)) {
                   4505: 	$allitems{$item} =~ s/\:$//;
                   4506: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4507:     }
                   4508:     $items=~s/\&$//;
                   4509:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4510: }
                   4511: 
1.47      www      4512: # ------------------------------------------------------ critical put interface
                   4513: 
                   4514: sub cput {
1.134     albertel 4515:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4516:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4517:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4518:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4519:    my $items='';
1.800     albertel 4520:    foreach my $item (keys(%$storehash)) {
                   4521:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4522:    }
1.47      www      4523:    $items=~s/\&$//;
1.134     albertel 4524:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4525: }
                   4526: 
                   4527: # -------------------------------------------------------------- eget interface
                   4528: 
                   4529: sub eget {
1.133     albertel 4530:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4531:    my $items='';
1.800     albertel 4532:    foreach my $item (@$storearr) {
                   4533:        $items.=&escape($item).'&';
1.191     harris41 4534:    }
1.12      www      4535:    $items=~s/\&$//;
1.620     albertel 4536:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4537:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4538:    my $uhome=&homeserver($uname,$udomain);
                   4539:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4540:    my @pairs=split(/\&/,$rep);
                   4541:    my %returnhash=();
1.42      www      4542:    my $i=0;
1.800     albertel 4543:    foreach my $item (@$storearr) {
                   4544:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4545:       $i++;
1.191     harris41 4546:    }
1.12      www      4547:    return %returnhash;
                   4548: }
                   4549: 
1.667     albertel 4550: # ------------------------------------------------------------ tmpput interface
                   4551: sub tmpput {
1.802     raeburn  4552:     my ($storehash,$server,$context)=@_;
1.667     albertel 4553:     my $items='';
1.800     albertel 4554:     foreach my $item (keys(%$storehash)) {
                   4555: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4556:     }
                   4557:     $items=~s/\&$//;
1.802     raeburn  4558:     if (defined($context)) {
                   4559:         $items .= ':'.&escape($context);
                   4560:     }
1.667     albertel 4561:     return &reply("tmpput:$items",$server);
                   4562: }
                   4563: 
                   4564: # ------------------------------------------------------------ tmpget interface
                   4565: sub tmpget {
1.688     albertel 4566:     my ($token,$server)=@_;
                   4567:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4568:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4569:     my %returnhash;
                   4570:     foreach my $item (split(/\&/,$rep)) {
                   4571: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4572:         next if ($key =~ /^error: 2 /);
1.667     albertel 4573: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4574:     }
                   4575:     return %returnhash;
                   4576: }
                   4577: 
1.688     albertel 4578: # ------------------------------------------------------------ tmpget interface
                   4579: sub tmpdel {
                   4580:     my ($token,$server)=@_;
                   4581:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4582:     return &reply("tmpdel:$token",$server);
                   4583: }
                   4584: 
1.765     albertel 4585: # -------------------------------------------------- portfolio access checking
                   4586: 
                   4587: sub portfolio_access {
1.766     albertel 4588:     my ($requrl) = @_;
1.765     albertel 4589:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4590:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4591:     if ($result) {
                   4592:         my %setters;
                   4593:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4594:             my ($startblock,$endblock) =
                   4595:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4596:             if ($startblock && $endblock) {
                   4597:                 return 'B';
                   4598:             }
                   4599:         } else {
                   4600:             my ($startblock,$endblock) =
                   4601:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4602:             if ($startblock && $endblock) {
                   4603:                 return 'B';
                   4604:             }
                   4605:         }
                   4606:     }
1.765     albertel 4607:     if ($result eq 'ok') {
1.766     albertel 4608:        return 'F';
1.765     albertel 4609:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4610:        return 'A';
1.765     albertel 4611:     }
1.766     albertel 4612:     return '';
1.765     albertel 4613: }
                   4614: 
                   4615: sub get_portfolio_access {
1.767     albertel 4616:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4617: 
                   4618:     if (!ref($access_hash)) {
                   4619: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4620: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4621: 						   $file_name);
                   4622: 	$access_hash = $access_controls{$file_name};
                   4623:     }
                   4624: 
1.765     albertel 4625:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4626:     my $now = time;
                   4627:     if (ref($access_hash) eq 'HASH') {
                   4628:         foreach my $key (keys(%{$access_hash})) {
                   4629:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4630:             if ($start > $now) {
                   4631:                 next;
                   4632:             }
                   4633:             if ($end && $end<$now) {
                   4634:                 next;
                   4635:             }
                   4636:             if ($scope eq 'public') {
                   4637:                 $public = $key;
                   4638:                 last;
                   4639:             } elsif ($scope eq 'guest') {
                   4640:                 $guest = $key;
                   4641:             } elsif ($scope eq 'domains') {
                   4642:                 push(@domains,$key);
                   4643:             } elsif ($scope eq 'users') {
                   4644:                 push(@users,$key);
                   4645:             } elsif ($scope eq 'course') {
                   4646:                 push(@courses,$key);
                   4647:             } elsif ($scope eq 'group') {
                   4648:                 push(@groups,$key);
                   4649:             }
                   4650:         }
                   4651:         if ($public) {
                   4652:             return 'ok';
                   4653:         }
                   4654:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4655:             if ($guest) {
                   4656:                 return $guest;
                   4657:             }
                   4658:         } else {
                   4659:             if (@domains > 0) {
                   4660:                 foreach my $domkey (@domains) {
                   4661:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4662:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4663:                             return 'ok';
                   4664:                         }
                   4665:                     }
                   4666:                 }
                   4667:             }
                   4668:             if (@users > 0) {
                   4669:                 foreach my $userkey (@users) {
1.865     raeburn  4670:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4671:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4672:                             if (ref($item) eq 'HASH') {
                   4673:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4674:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4675:                                     return 'ok';
                   4676:                                 }
                   4677:                             }
                   4678:                         }
                   4679:                     } 
1.765     albertel 4680:                 }
                   4681:             }
                   4682:             my %roleshash;
                   4683:             my @courses_and_groups = @courses;
                   4684:             push(@courses_and_groups,@groups); 
                   4685:             if (@courses_and_groups > 0) {
                   4686:                 my (%allgroups,%allroles); 
                   4687:                 my ($start,$end,$role,$sec,$group);
                   4688:                 foreach my $envkey (%env) {
1.1060    raeburn  4689:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4690:                         my $cid = $2.'_'.$3; 
                   4691:                         if ($1 eq 'gr') {
                   4692:                             $group = $4;
                   4693:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4694:                         } else {
                   4695:                             if ($4 eq '') {
                   4696:                                 $sec = 'none';
                   4697:                             } else {
                   4698:                                 $sec = $4;
                   4699:                             }
                   4700:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4701:                         }
1.811     albertel 4702:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4703:                         my $cid = $2.'_'.$3;
                   4704:                         if ($4 eq '') {
                   4705:                             $sec = 'none';
                   4706:                         } else {
                   4707:                             $sec = $4;
                   4708:                         }
                   4709:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4710:                     }
                   4711:                 }
                   4712:                 if (keys(%allroles) == 0) {
                   4713:                     return;
                   4714:                 }
                   4715:                 foreach my $key (@courses_and_groups) {
                   4716:                     my %content = %{$$access_hash{$key}};
                   4717:                     my $cnum = $content{'number'};
                   4718:                     my $cdom = $content{'domain'};
                   4719:                     my $cid = $cdom.'_'.$cnum;
                   4720:                     if (!exists($allroles{$cid})) {
                   4721:                         next;
                   4722:                     }    
                   4723:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4724:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4725:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4726:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4727:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4728:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4729:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4730:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4731:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4732:                                         if (grep/^all$/,@sections) {
                   4733:                                             return 'ok';
                   4734:                                         } else {
                   4735:                                             if (grep/^$sec$/,@sections) {
                   4736:                                                 return 'ok';
                   4737:                                             }
                   4738:                                         }
                   4739:                                     }
                   4740:                                 }
                   4741:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4742:                                     if (grep/^none$/,@groups) {
                   4743:                                         return 'ok';
                   4744:                                     }
                   4745:                                 } else {
                   4746:                                     if (grep/^all$/,@groups) {
                   4747:                                         return 'ok';
                   4748:                                     } 
                   4749:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4750:                                         if (grep/^$group$/,@groups) {
                   4751:                                             return 'ok';
                   4752:                                         }
                   4753:                                     }
                   4754:                                 } 
                   4755:                             }
                   4756:                         }
                   4757:                     }
                   4758:                 }
                   4759:             }
                   4760:             if ($guest) {
                   4761:                 return $guest;
                   4762:             }
                   4763:         }
                   4764:     }
                   4765:     return;
                   4766: }
                   4767: 
                   4768: sub course_group_datechecker {
                   4769:     my ($dates,$now,$status) = @_;
                   4770:     my ($start,$end) = split(/\./,$dates);
                   4771:     if (!$start && !$end) {
                   4772:         return 'ok';
                   4773:     }
                   4774:     if (grep/^active$/,@{$status}) {
                   4775:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4776:             return 'ok';
                   4777:         }
                   4778:     }
                   4779:     if (grep/^previous$/,@{$status}) {
                   4780:         if ($end > $now ) {
                   4781:             return 'ok';
                   4782:         }
                   4783:     }
                   4784:     if (grep/^future$/,@{$status}) {
                   4785:         if ($start > $now) {
                   4786:             return 'ok';
                   4787:         }
                   4788:     }
                   4789:     return; 
                   4790: }
                   4791: 
                   4792: sub parse_portfolio_url {
                   4793:     my ($url) = @_;
                   4794: 
                   4795:     my ($type,$udom,$unum,$group,$file_name);
                   4796:     
1.823     albertel 4797:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4798: 	$type = 1;
                   4799:         $udom = $1;
                   4800:         $unum = $2;
                   4801:         $file_name = $3;
1.823     albertel 4802:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4803: 	$type = 2;
                   4804:         $udom = $1;
                   4805:         $unum = $2;
                   4806:         $group = $3;
                   4807:         $file_name = $3.'/'.$4;
                   4808:     }
                   4809:     if (wantarray) {
                   4810: 	return ($type,$udom,$unum,$file_name,$group);
                   4811:     }
                   4812:     return $type;
                   4813: }
                   4814: 
                   4815: sub is_portfolio_url {
                   4816:     my ($url) = @_;
                   4817:     return scalar(&parse_portfolio_url($url));
                   4818: }
                   4819: 
1.798     raeburn  4820: sub is_portfolio_file {
                   4821:     my ($file) = @_;
1.820     raeburn  4822:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4823:         return 1;
                   4824:     }
                   4825:     return;
                   4826: }
                   4827: 
1.976     raeburn  4828: sub usertools_access {
1.985     raeburn  4829:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4830:     my ($access,%tools);
                   4831:     if ($context eq '') {
                   4832:         $context = 'tools';
                   4833:     }
                   4834:     if ($context eq 'requestcourses') {
                   4835:         %tools = (
                   4836:                       official   => 1,
                   4837:                       unofficial => 1,
1.1006    raeburn  4838:                       community  => 1,
1.985     raeburn  4839:                  );
                   4840:     } else {
                   4841:         %tools = (
                   4842:                       aboutme   => 1,
                   4843:                       blog      => 1,
                   4844:                       portfolio => 1,
                   4845:                  );
                   4846:     }
1.976     raeburn  4847:     return if (!defined($tools{$tool}));
                   4848: 
                   4849:     if ((!defined($udom)) || (!defined($uname))) {
                   4850:         $udom = $env{'user.domain'};
                   4851:         $uname = $env{'user.name'};
                   4852:     }
                   4853: 
1.978     raeburn  4854:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4855:         if ($action ne 'reload') {
1.985     raeburn  4856:             if ($context eq 'requestcourses') {
                   4857:                 return $env{'environment.canrequest.'.$tool};
                   4858:             } else {
                   4859:                 return $env{'environment.availabletools.'.$tool};
                   4860:             }
                   4861:         }
1.976     raeburn  4862:     }
                   4863: 
                   4864:     my ($toolstatus,$inststatus);
                   4865: 
1.985     raeburn  4866:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4867:          ($action ne 'reload')) {
                   4868:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4869:         $inststatus = $env{'environment.inststatus'};
                   4870:     } else {
1.1025    raeburn  4871:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985     raeburn  4872:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4873:         $inststatus = $userenv{'inststatus'};
                   4874:     }
                   4875: 
                   4876:     if ($toolstatus ne '') {
                   4877:         if ($toolstatus) {
                   4878:             $access = 1;
                   4879:         } else {
                   4880:             $access = 0;
                   4881:         }
                   4882:         return $access;
                   4883:     }
                   4884: 
                   4885:     my $is_adv = &is_advanced_user($udom,$uname);
                   4886:     my %domdef = &get_domain_defaults($udom);
                   4887:     if (ref($domdef{$tool}) eq 'HASH') {
                   4888:         if ($is_adv) {
                   4889:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4890:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4891:                     $access = 1;
                   4892:                 } else {
                   4893:                     $access = 0;
                   4894:                 }
                   4895:                 return $access;
                   4896:             }
                   4897:         }
                   4898:         if ($inststatus ne '') {
                   4899:             my ($hasaccess,$hasnoaccess);
                   4900:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4901:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4902:                     if ($domdef{$tool}{$affiliation}) {
                   4903:                         $hasaccess = 1;
                   4904:                     } else {
                   4905:                         $hasnoaccess = 1;
                   4906:                     }
                   4907:                 }
                   4908:             }
                   4909:             if ($hasaccess || $hasnoaccess) {
                   4910:                 if ($hasaccess) {
                   4911:                     $access = 1;
                   4912:                 } elsif ($hasnoaccess) {
                   4913:                     $access = 0; 
                   4914:                 }
                   4915:                 return $access;
                   4916:             }
                   4917:         } else {
                   4918:             if ($domdef{$tool}{'default'} ne '') {
                   4919:                 if ($domdef{$tool}{'default'}) {
                   4920:                     $access = 1;
                   4921:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4922:                     $access = 0;
                   4923:                 }
                   4924:                 return $access;
                   4925:             }
                   4926:         }
                   4927:     } else {
1.985     raeburn  4928:         if ($context eq 'tools') {
                   4929:             $access = 1;
                   4930:         } else {
                   4931:             $access = 0;
                   4932:         }
1.976     raeburn  4933:         return $access;
                   4934:     }
                   4935: }
                   4936: 
1.1050    raeburn  4937: sub is_course_owner {
                   4938:     my ($cdom,$cnum,$udom,$uname) = @_;
                   4939:     if (($udom eq '') || ($uname eq '')) {
                   4940:         $udom = $env{'user.domain'};
                   4941:         $uname = $env{'user.name'};
                   4942:     }
                   4943:     unless (($udom eq '') || ($uname eq '')) {
                   4944:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   4945:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   4946:                 return 1;
                   4947:             } else {
                   4948:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   4949:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   4950:                     return 1;
                   4951:                 }
                   4952:             }
                   4953:         }
                   4954:     }
                   4955:     return;
                   4956: }
                   4957: 
1.976     raeburn  4958: sub is_advanced_user {
                   4959:     my ($udom,$uname) = @_;
                   4960:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4961:     my %allroles;
                   4962:     my $is_adv;
                   4963:     foreach my $role (keys(%roleshash)) {
                   4964:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4965:         my $area = '/'.$tdomain.'/'.$trest;
                   4966:         if ($sec ne '') {
                   4967:             $area .= '/'.$sec;
                   4968:         }
                   4969:         if (($area ne '') && ($trole ne '')) {
                   4970:             my $spec=$trole.'.'.$area;
                   4971:             if ($trole =~ /^cr\//) {
                   4972:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4973:             } elsif ($trole ne 'gr') {
                   4974:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4975:             }
                   4976:         }
                   4977:     }
                   4978:     foreach my $role (keys(%allroles)) {
                   4979:         last if ($is_adv);
                   4980:         foreach my $item (split(/:/,$allroles{$role})) {
                   4981:             if ($item ne '') {
                   4982:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4983:                 if ($privilege eq 'adv') {
                   4984:                     $is_adv = 1;
                   4985:                     last;
                   4986:                 }
                   4987:             }
                   4988:         }
                   4989:     }
                   4990:     return $is_adv;
                   4991: }
1.798     raeburn  4992: 
1.1035    raeburn  4993: sub check_can_request {
1.1036    raeburn  4994:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  4995:     my $canreq = 0;
                   4996:     my ($types,$typename) = &Apache::loncommon::course_types();
                   4997:     my @options = ('approval','validate','autolimit');
                   4998:     my $optregex = join('|',@options);
                   4999:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5000:         foreach my $type (@{$types}) {
                   5001:             if (&usertools_access($env{'user.name'},
                   5002:                                   $env{'user.domain'},
                   5003:                                   $type,undef,'requestcourses')) {
                   5004:                 $canreq ++;
1.1036    raeburn  5005:                 if (ref($request_domains) eq 'HASH') {
                   5006:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5007:                 }
1.1035    raeburn  5008:                 if ($dom eq $env{'user.domain'}) {
                   5009:                     $can_request->{$type} = 1;
                   5010:                 }
                   5011:             }
                   5012:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5013:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5014:                 if (@curr > 0) {
1.1036    raeburn  5015:                     foreach my $item (@curr) {
                   5016:                         if (ref($request_domains) eq 'HASH') {
                   5017:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5018:                             if ($otherdom ne '') {
                   5019:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5020:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5021:                                         push(@{$request_domains->{$type}},$otherdom);
                   5022:                                     }
                   5023:                                 } else {
                   5024:                                     push(@{$request_domains->{$type}},$otherdom);
                   5025:                                 }
                   5026:                             }
                   5027:                         }
                   5028:                     }
                   5029:                     unless($dom eq $env{'user.domain'}) {
                   5030:                         $canreq ++;
1.1035    raeburn  5031:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5032:                             $can_request->{$type} = 1;
                   5033:                         }
                   5034:                     }
                   5035:                 }
                   5036:             }
                   5037:         }
                   5038:     }
                   5039:     return $canreq;
                   5040: }
                   5041: 
1.341     www      5042: # ---------------------------------------------- Custom access rule evaluation
                   5043: 
                   5044: sub customaccess {
                   5045:     my ($priv,$uri)=@_;
1.807     albertel 5046:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5047:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5048:     $udom = &LONCAPA::clean_domain($udom);
                   5049:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5050:     my $access=0;
1.800     albertel 5051:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5052: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5053: 	if ($type eq 'user') {
                   5054: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5055: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5056: 		if ($tdom) {
                   5057: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5058: 		}
1.896     albertel 5059: 		if ($tuname) {
                   5060: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5061: 		}
                   5062: 		$access=($effect eq 'allow');
                   5063: 		last;
                   5064: 	    }
                   5065: 	} else {
                   5066: 	    if ($role) {
                   5067: 		if ($role ne $urole) { next; }
                   5068: 	    }
                   5069: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5070: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5071: 		if ($tdom) {
                   5072: 		    if ($tdom ne $udom) { next; }
                   5073: 		}
                   5074: 		if ($tcrs) {
                   5075: 		    if ($tcrs ne $ucrs) { next; }
                   5076: 		}
                   5077: 		if ($tsec) {
                   5078: 		    if ($tsec ne $usec) { next; }
                   5079: 		}
                   5080: 		$access=($effect eq 'allow');
                   5081: 		last;
                   5082: 	    }
                   5083: 	    if ($realm eq '' && $role eq '') {
                   5084: 		$access=($effect eq 'allow');
                   5085: 	    }
1.402     bowersj2 5086: 	}
1.341     www      5087:     }
                   5088:     return $access;
                   5089: }
                   5090: 
1.103     harris41 5091: # ------------------------------------------------- Check for a user privilege
1.12      www      5092: 
                   5093: sub allowed {
1.810     raeburn  5094:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5095:     my $ver_orguri=$uri;
1.439     www      5096:     $uri=&deversion($uri);
1.152     www      5097:     my $orguri=$uri;
1.52      www      5098:     $uri=&declutter($uri);
1.809     raeburn  5099: 
1.810     raeburn  5100:     if ($priv eq 'evb') {
                   5101: # Evade communication block restrictions for specified role in a course
                   5102:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5103:             return $1;
                   5104:         } else {
                   5105:             return;
                   5106:         }
                   5107:     }
                   5108: 
1.620     albertel 5109:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5110: # Free bre access to adm and meta resources
1.775     albertel 5111:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5112: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5113: 	&& ($priv eq 'bre')) {
1.14      www      5114: 	return 'F';
1.159     www      5115:     }
                   5116: 
1.545     banghart 5117: # Free bre access to user's own portfolio contents
1.714     raeburn  5118:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5119:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5120: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5121:         my %setters;
                   5122:         my ($startblock,$endblock) = 
                   5123:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5124:         if ($startblock && $endblock) {
                   5125:             return 'B';
                   5126:         } else {
                   5127:             return 'F';
                   5128:         }
1.545     banghart 5129:     }
                   5130: 
1.762     raeburn  5131: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5132:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5133:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5134:         if (exists($env{'request.course.id'})) {
                   5135:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5136:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5137:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5138:                 my $courseprivid=$env{'request.course.id'};
                   5139:                 $courseprivid=~s/\_/\//;
                   5140:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5141:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5142:                     return $1; 
1.762     raeburn  5143:                 } else {
                   5144:                     if ($env{'request.course.sec'}) {
                   5145:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5146:                     }
                   5147:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5148:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5149:                         return $2;
                   5150:                     }
1.714     raeburn  5151:                 }
                   5152:             }
                   5153:         }
                   5154:     }
                   5155: 
1.159     www      5156: # Free bre to public access
                   5157: 
                   5158:     if ($priv eq 'bre') {
1.238     www      5159:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5160: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5161:            return 'F'; 
                   5162:         }
1.238     www      5163:         if ($copyright eq 'priv') {
                   5164:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5165: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5166: 		return '';
                   5167:             }
                   5168:         }
                   5169:         if ($copyright eq 'domain') {
                   5170:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5171: 	    unless (($env{'user.domain'} eq $1) ||
                   5172:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5173: 		return '';
                   5174:             }
1.262     matthew  5175:         }
1.620     albertel 5176:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5177:             # Library role, so allow browsing of resources in this domain.
                   5178:             return 'F';
1.238     www      5179:         }
1.341     www      5180:         if ($copyright eq 'custom') {
                   5181: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5182:         }
1.14      www      5183:     }
1.264     matthew  5184:     # Domain coordinator is trying to create a course
1.620     albertel 5185:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5186:         # uri is the requested domain in this case.
                   5187:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5188:         # a role of dc for the domain in question.
1.620     albertel 5189:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5190:     }
1.29      www      5191: 
1.52      www      5192:     my $thisallowed='';
                   5193:     my $statecond=0;
                   5194:     my $courseprivid='';
                   5195: 
1.1039    raeburn  5196:     my $ownaccess;
1.1043    raeburn  5197:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5198:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5199:         if ($uri eq '') {
                   5200:             $ownaccess = 1;
                   5201:         } else {
                   5202:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5203:                 my $udom = $env{'user.domain'};
                   5204:                 my $uname = $env{'user.name'};
                   5205:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5206:                     $ownaccess = 1;
1.1040    raeburn  5207:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5208:                     unless ($uri =~ m{\.\./}) {
                   5209:                         $ownaccess = 1;
                   5210:                     }
                   5211:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5212:                     my $now = time;
                   5213:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5214:                         my $adom = $1;
                   5215:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5216:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5217:                                 my ($start,$end) = split('.',$env{$key});
                   5218:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5219:                                     $ownaccess = 1;
                   5220:                                     last;
                   5221:                                 }
                   5222:                             }
                   5223:                         }
                   5224:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5225:                         my $adom = $1;
                   5226:                         my $aname = $2;
1.1042    raeburn  5227:                         foreach my $role ('ca','aa') { 
                   5228:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5229:                                 my ($start,$end) =
                   5230:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5231:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5232:                                     $ownaccess = 1;
                   5233:                                     last;
                   5234:                                 }
1.1039    raeburn  5235:                             }
                   5236:                         }
                   5237:                     }
                   5238:                 }
                   5239:             }
                   5240:         }
                   5241:     }
                   5242: 
1.52      www      5243: # Course
                   5244: 
1.620     albertel 5245:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5246:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5247:             $thisallowed.=$1;
                   5248:         }
1.52      www      5249:     }
1.29      www      5250: 
1.52      www      5251: # Domain
                   5252: 
1.620     albertel 5253:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5254:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5255:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5256:             $thisallowed.=$1;
                   5257:         }
1.12      www      5258:     }
1.52      www      5259: 
                   5260: # Course: uri itself is a course
1.66      www      5261:     my $courseuri=$uri;
                   5262:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5263:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5264: 
1.620     albertel 5265:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5266:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5267:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5268:             $thisallowed.=$1;
                   5269:         }
1.12      www      5270:     }
1.29      www      5271: 
1.665     albertel 5272: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5273: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5274:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5275: 	$thisallowed='';
1.671     raeburn  5276:         my ($match)=&is_on_map($uri);
                   5277:         if ($match) {
                   5278:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5279:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5280:                 $thisallowed.=$1;
                   5281:             }
                   5282:         } else {
1.705     albertel 5283:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5284:             if ($refuri) {
                   5285:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5286:                     $thisallowed='F';
1.671     raeburn  5287:                 } else {
                   5288:                     $refuri=&declutter($refuri);
                   5289:                     my ($match) = &is_on_map($refuri);
                   5290:                     if ($match) {
                   5291:                         $thisallowed='F';
                   5292:                     }
1.669     raeburn  5293:                 }
1.671     raeburn  5294:             }
                   5295:         }
1.314     www      5296:     }
1.492     albertel 5297: 
1.766     albertel 5298:     if ($priv eq 'bre'
                   5299: 	&& $thisallowed ne 'F' 
                   5300: 	&& $thisallowed ne '2'
                   5301: 	&& &is_portfolio_url($uri)) {
                   5302: 	$thisallowed = &portfolio_access($uri);
                   5303:     }
                   5304:     
1.52      www      5305: # Full access at system, domain or course-wide level? Exit.
1.29      www      5306:     if ($thisallowed=~/F/) {
                   5307: 	return 'F';
                   5308:     }
                   5309: 
1.52      www      5310: # If this is generating or modifying users, exit with special codes
1.29      www      5311: 
1.643     www      5312:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5313: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5314: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5315: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5316: 	    unless ($auname) { return $thisallowed; }
                   5317: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5318: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5319: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5320: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5321: 	}
1.52      www      5322: 	return $thisallowed;
                   5323:     }
                   5324: #
1.103     harris41 5325: # Gathered so far: system, domain and course wide privileges
1.52      www      5326: #
                   5327: # Course: See if uri or referer is an individual resource that is part of 
                   5328: # the course
                   5329: 
1.620     albertel 5330:     if ($env{'request.course.id'}) {
1.232     www      5331: 
1.620     albertel 5332:        $courseprivid=$env{'request.course.id'};
                   5333:        if ($env{'request.course.sec'}) {
                   5334:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5335:        }
                   5336:        $courseprivid=~s/\_/\//;
                   5337:        my $checkreferer=1;
1.232     www      5338:        my ($match,$cond)=&is_on_map($uri);
                   5339:        if ($match) {
                   5340:            $statecond=$cond;
1.620     albertel 5341:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5342:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5343:                $thisallowed.=$1;
                   5344:                $checkreferer=0;
                   5345:            }
1.29      www      5346:        }
1.83      www      5347:        
1.148     www      5348:        if ($checkreferer) {
1.620     albertel 5349: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5350:             unless ($refuri) {
1.800     albertel 5351:                 foreach my $key (keys(%env)) {
                   5352: 		    if ($key=~/^httpref\..*\*/) {
                   5353: 			my $pattern=$key;
1.156     www      5354:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5355:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5356:                         $pattern=~s/\//\\\//g;
1.152     www      5357:                         if ($orguri=~/$pattern/) {
1.800     albertel 5358: 			    $refuri=$env{$key};
1.148     www      5359:                         }
                   5360:                     }
1.191     harris41 5361:                 }
1.148     www      5362:             }
1.232     www      5363: 
1.148     www      5364:          if ($refuri) { 
1.152     www      5365: 	  $refuri=&declutter($refuri);
1.232     www      5366:           my ($match,$cond)=&is_on_map($refuri);
                   5367:             if ($match) {
                   5368:               my $refstatecond=$cond;
1.620     albertel 5369:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5370:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5371:                   $thisallowed.=$1;
1.53      www      5372:                   $uri=$refuri;
                   5373:                   $statecond=$refstatecond;
1.52      www      5374:               }
                   5375:           }
1.148     www      5376:         }
1.29      www      5377:        }
1.52      www      5378:    }
1.29      www      5379: 
1.52      www      5380: #
1.103     harris41 5381: # Gathered now: all privileges that could apply, and condition number
1.52      www      5382: # 
                   5383: #
                   5384: # Full or no access?
                   5385: #
1.29      www      5386: 
1.52      www      5387:     if ($thisallowed=~/F/) {
                   5388: 	return 'F';
                   5389:     }
1.29      www      5390: 
1.52      www      5391:     unless ($thisallowed) {
                   5392:         return '';
                   5393:     }
1.29      www      5394: 
1.52      www      5395: # Restrictions exist, deal with them
                   5396: #
                   5397: #   C:according to course preferences
                   5398: #   R:according to resource settings
                   5399: #   L:unless locked
                   5400: #   X:according to user session state
                   5401: #
                   5402: 
                   5403: # Possibly locked functionality, check all courses
1.54      www      5404: # Locks might take effect only after 10 minutes cache expiration for other
                   5405: # courses, and 2 minutes for current course
1.52      www      5406: 
                   5407:     my $envkey;
                   5408:     if ($thisallowed=~/L/) {
1.1000    raeburn  5409:         foreach $envkey (keys(%env)) {
1.54      www      5410:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5411:                my $courseid=$2;
                   5412:                my $roleid=$1.'.'.$2;
1.92      www      5413:                $courseid=~s/^\///;
1.54      www      5414:                my $expiretime=600;
1.620     albertel 5415:                if ($env{'request.role'} eq $roleid) {
1.54      www      5416: 		  $expiretime=120;
                   5417:                }
                   5418: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5419:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5420:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5421: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5422:                }
1.620     albertel 5423:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5424:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5425: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5426:                        &log($env{'user.domain'},$env{'user.name'},
                   5427:                             $env{'user.home'},
1.57      www      5428:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5429:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5430:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5431: 		       return '';
                   5432:                    }
                   5433:                }
1.620     albertel 5434:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5435:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5436: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5437:                        &log($env{'user.domain'},$env{'user.name'},
                   5438:                             $env{'user.home'},
1.57      www      5439:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5440:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5441:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5442: 		       return '';
                   5443:                    }
                   5444:                }
                   5445: 	   }
1.29      www      5446:        }
1.52      www      5447:     }
                   5448:    
                   5449: #
                   5450: # Rest of the restrictions depend on selected course
                   5451: #
                   5452: 
1.620     albertel 5453:     unless ($env{'request.course.id'}) {
1.766     albertel 5454: 	if ($thisallowed eq 'A') {
                   5455: 	    return 'A';
1.814     raeburn  5456:         } elsif ($thisallowed eq 'B') {
                   5457:             return 'B';
1.766     albertel 5458: 	} else {
                   5459: 	    return '1';
                   5460: 	}
1.52      www      5461:     }
1.29      www      5462: 
1.52      www      5463: #
                   5464: # Now user is definitely in a course
                   5465: #
1.53      www      5466: 
                   5467: 
                   5468: # Course preferences
                   5469: 
                   5470:    if ($thisallowed=~/C/) {
1.620     albertel 5471:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5472:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5473:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5474: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5475: 	   if ($priv ne 'pch') { 
                   5476: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5477: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5478: 			$env{'request.course.id'});
                   5479: 	   }
1.237     www      5480:            return '';
                   5481:        }
                   5482: 
1.620     albertel 5483:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5484: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5485: 	   if ($priv ne 'pch') { 
                   5486: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5487: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5488: 			$env{'request.course.id'});
                   5489: 	   }
1.54      www      5490:            return '';
                   5491:        }
1.53      www      5492:    }
                   5493: 
                   5494: # Resource preferences
                   5495: 
                   5496:    if ($thisallowed=~/R/) {
1.620     albertel 5497:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5498:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5499: 	   if ($priv ne 'pch') { 
                   5500: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5501: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5502: 	   }
                   5503: 	   return '';
1.54      www      5504:        }
1.53      www      5505:    }
1.30      www      5506: 
1.246     www      5507: # Restricted by state or randomout?
1.30      www      5508: 
1.52      www      5509:    if ($thisallowed=~/X/) {
1.620     albertel 5510:       if ($env{'acc.randomout'}) {
1.579     albertel 5511: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5512:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5513:             return ''; 
                   5514:          }
1.247     www      5515:       }
                   5516:       if (&condval($statecond)) {
1.52      www      5517: 	 return '2';
                   5518:       } else {
                   5519:          return '';
                   5520:       }
                   5521:    }
1.30      www      5522: 
1.766     albertel 5523:     if ($thisallowed eq 'A') {
                   5524: 	return 'A';
1.814     raeburn  5525:     } elsif ($thisallowed eq 'B') {
                   5526:         return 'B';
1.766     albertel 5527:     }
1.52      www      5528:    return 'F';
1.232     www      5529: }
                   5530: 
1.710     albertel 5531: sub split_uri_for_cond {
                   5532:     my $uri=&deversion(&declutter(shift));
                   5533:     my @uriparts=split(/\//,$uri);
                   5534:     my $filename=pop(@uriparts);
                   5535:     my $pathname=join('/',@uriparts);
                   5536:     return ($pathname,$filename);
                   5537: }
1.232     www      5538: # --------------------------------------------------- Is a resource on the map?
                   5539: 
                   5540: sub is_on_map {
1.710     albertel 5541:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5542:     #Trying to find the conditional for the file
1.620     albertel 5543:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5544: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5545:     if ($match) {
1.289     bowersj2 5546: 	return (1,$1);
                   5547:     } else {
1.434     www      5548: 	return (0,0);
1.289     bowersj2 5549:     }
1.12      www      5550: }
                   5551: 
1.427     www      5552: # --------------------------------------------------------- Get symb from alias
                   5553: 
                   5554: sub get_symb_from_alias {
                   5555:     my $symb=shift;
                   5556:     my ($map,$resid,$url)=&decode_symb($symb);
                   5557: # Already is a symb
                   5558:     if ($url) { return $symb; }
                   5559: # Must be an alias
                   5560:     my $aliassymb='';
                   5561:     my %bighash;
1.620     albertel 5562:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5563:                             &GDBM_READER(),0640)) {
                   5564:         my $rid=$bighash{'mapalias_'.$symb};
                   5565: 	if ($rid) {
                   5566: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5567: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5568: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5569: 	}
                   5570:         untie %bighash;
                   5571:     }
                   5572:     return $aliassymb;
                   5573: }
                   5574: 
1.12      www      5575: # ----------------------------------------------------------------- Define Role
                   5576: 
                   5577: sub definerole {
                   5578:   if (allowed('mcr','/')) {
                   5579:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5580:     foreach my $role (split(':',$sysrole)) {
                   5581: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5582:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5583:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5584: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5585:                return "refused:s:$crole&$cqual"; 
                   5586:             }
                   5587:         }
1.191     harris41 5588:     }
1.800     albertel 5589:     foreach my $role (split(':',$domrole)) {
                   5590: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5591:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5592:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5593: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5594:                return "refused:d:$crole&$cqual"; 
                   5595:             }
                   5596:         }
1.191     harris41 5597:     }
1.800     albertel 5598:     foreach my $role (split(':',$courole)) {
                   5599: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5600:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5601:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5602: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5603:                return "refused:c:$crole&$cqual"; 
                   5604:             }
                   5605:         }
1.191     harris41 5606:     }
1.620     albertel 5607:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5608:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5609: 	        "rolesdef_$rolename=".
                   5610:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5611:     return reply($command,$env{'user.home'});
1.12      www      5612:   } else {
                   5613:     return 'refused';
                   5614:   }
1.105     harris41 5615: }
                   5616: 
                   5617: # ---------------- Make a metadata query against the network of library servers
                   5618: 
                   5619: sub metadata_query {
1.244     matthew  5620:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5621:     my %rhash;
1.845     albertel 5622:     my %libserv = &all_library();
1.244     matthew  5623:     my @server_list = (defined($server_array) ? @$server_array
                   5624:                                               : keys(%libserv) );
                   5625:     for my $server (@server_list) {
1.118     harris41 5626: 	unless ($custom or $customshow) {
                   5627: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5628: 	    $rhash{$server}=$reply;
                   5629: 	}
                   5630: 	else {
                   5631: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5632: 			     &escape($custom).':'.&escape($customshow),
                   5633: 			     $server);
                   5634: 	    $rhash{$server}=$reply;
                   5635: 	}
1.112     harris41 5636:     }
1.118     harris41 5637:     return \%rhash;
1.240     www      5638: }
                   5639: 
                   5640: # ----------------------------------------- Send log queries and wait for reply
                   5641: 
                   5642: sub log_query {
                   5643:     my ($uname,$udom,$query,%filters)=@_;
                   5644:     my $uhome=&homeserver($uname,$udom);
                   5645:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5646:     my $uhost=&hostname($uhome);
1.800     albertel 5647:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5648:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5649:                        $uhome);
1.479     albertel 5650:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5651:     return get_query_reply($queryid);
                   5652: }
                   5653: 
1.818     raeburn  5654: # -------------------------- Update MySQL table for portfolio file
                   5655: 
                   5656: sub update_portfolio_table {
1.821     raeburn  5657:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5658:     if ($group ne '') {
                   5659:         $file_name =~s /^\Q$group\E//;
                   5660:     }
1.818     raeburn  5661:     my $homeserver = &homeserver($uname,$udom);
                   5662:     my $queryid=
1.821     raeburn  5663:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5664:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5665:     my $reply = &get_query_reply($queryid);
                   5666:     return $reply;
                   5667: }
                   5668: 
1.899     raeburn  5669: # -------------------------- Update MySQL allusers table
                   5670: 
                   5671: sub update_allusers_table {
                   5672:     my ($uname,$udom,$names) = @_;
                   5673:     my $homeserver = &homeserver($uname,$udom);
                   5674:     my $queryid=
                   5675:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5676:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5677:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5678:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5679:                'generation='.&escape($names->{'generation'}).'%%'.
                   5680:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5681:                'id='.&escape($names->{'id'}),$homeserver);
1.1075  ! raeburn  5682:     return;
1.899     raeburn  5683: }
                   5684: 
1.508     raeburn  5685: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5686: 
                   5687: sub fetch_enrollment_query {
1.511     raeburn  5688:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5689:     my $homeserver;
1.547     raeburn  5690:     my $maxtries = 1;
1.508     raeburn  5691:     if ($context eq 'automated') {
                   5692:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5693:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5694:     } else {
                   5695:         $homeserver = &homeserver($cnum,$dom);
                   5696:     }
1.838     albertel 5697:     my $host=&hostname($homeserver);
1.506     raeburn  5698:     my $cmd = '';
1.1000    raeburn  5699:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5700:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5701:     }
                   5702:     $cmd =~ s/%%$//;
                   5703:     $cmd = &escape($cmd);
                   5704:     my $query = 'fetchenrollment';
1.620     albertel 5705:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5706:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5707:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5708:         return 'error: '.$queryid;
                   5709:     }
1.506     raeburn  5710:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5711:     my $tries = 1;
                   5712:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5713:         $reply = &get_query_reply($queryid);
                   5714:         $tries ++;
                   5715:     }
1.526     raeburn  5716:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5717:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5718:     } else {
1.901     albertel 5719:         my @responses = split(/:/,$reply);
1.515     raeburn  5720:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5721:             foreach my $line (@responses) {
                   5722:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5723:                 $$replyref{$key} = $value;
                   5724:             }
                   5725:         } else {
1.506     raeburn  5726:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5727:             foreach my $line (@responses) {
                   5728:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5729:                 $$replyref{$key} = $value;
                   5730:                 if ($value > 0) {
1.800     albertel 5731:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5732:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5733:                         my $destname = $pathname.'/'.$filename;
                   5734:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5735:                         if ($xml_classlist =~ /^error/) {
                   5736:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5737:                         } else {
1.506     raeburn  5738:                             if ( open(FILE,">$destname") ) {
                   5739:                                 print FILE &unescape($xml_classlist);
                   5740:                                 close(FILE);
1.526     raeburn  5741:                             } else {
                   5742:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5743:                             }
                   5744:                         }
                   5745:                     }
                   5746:                 }
                   5747:             }
                   5748:         }
                   5749:         return 'ok';
                   5750:     }
                   5751:     return 'error';
                   5752: }
                   5753: 
1.242     www      5754: sub get_query_reply {
                   5755:     my $queryid=shift;
1.240     www      5756:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5757:     my $reply='';
                   5758:     for (1..100) {
                   5759: 	sleep 2;
                   5760:         if (-e $replyfile.'.end') {
1.448     albertel 5761: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5762: 		$reply = join('',<$fh>);
                   5763: 		close($fh);
1.240     www      5764: 	   } else { return 'error: reply_file_error'; }
1.242     www      5765:            return &unescape($reply);
                   5766: 	}
1.240     www      5767:     }
1.242     www      5768:     return 'timeout:'.$queryid;
1.240     www      5769: }
                   5770: 
                   5771: sub courselog_query {
1.241     www      5772: #
                   5773: # possible filters:
                   5774: # url: url or symb
                   5775: # username
                   5776: # domain
                   5777: # action: view, submit, grade
                   5778: # start: timestamp
                   5779: # end: timestamp
                   5780: #
1.240     www      5781:     my (%filters)=@_;
1.620     albertel 5782:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5783:     if ($filters{'url'}) {
                   5784: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5785:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5786:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5787:     }
1.620     albertel 5788:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5789:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5790:     return &log_query($cname,$cdom,'courselog',%filters);
                   5791: }
                   5792: 
                   5793: sub userlog_query {
1.858     raeburn  5794: #
                   5795: # possible filters:
                   5796: # action: log check role
                   5797: # start: timestamp
                   5798: # end: timestamp
                   5799: #
1.240     www      5800:     my ($uname,$udom,%filters)=@_;
                   5801:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5802: }
                   5803: 
1.506     raeburn  5804: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5805: 
                   5806: sub auto_run {
1.508     raeburn  5807:     my ($cnum,$cdom) = @_;
1.876     raeburn  5808:     my $response = 0;
                   5809:     my $settings;
                   5810:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5811:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5812:         $settings = $domconfig{'autoenroll'};
                   5813:         if ($settings->{'run'} eq '1') {
                   5814:             $response = 1;
                   5815:         }
                   5816:     } else {
1.934     raeburn  5817:         my $homeserver;
                   5818:         if (&is_course($cdom,$cnum)) {
                   5819:             $homeserver = &homeserver($cnum,$cdom);
                   5820:         } else {
                   5821:             $homeserver = &domain($cdom,'primary');
                   5822:         }
                   5823:         if ($homeserver ne 'no_host') {
                   5824:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5825:         }
1.876     raeburn  5826:     }
1.506     raeburn  5827:     return $response;
                   5828: }
1.776     albertel 5829: 
1.506     raeburn  5830: sub auto_get_sections {
1.508     raeburn  5831:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5832:     my $homeserver;
                   5833:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5834:         $homeserver = &homeserver($cnum,$cdom);
                   5835:     }
                   5836:     if (!defined($homeserver)) { 
                   5837:         if ($cdom =~ /^$match_domain$/) {
                   5838:             $homeserver = &domain($cdom,'primary');
                   5839:         }
                   5840:     }
                   5841:     my @secs;
                   5842:     if (defined($homeserver)) {
                   5843:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5844:         unless ($response eq 'refused') {
                   5845:             @secs = split(/:/,$response);
                   5846:         }
1.506     raeburn  5847:     }
                   5848:     return @secs;
                   5849: }
1.776     albertel 5850: 
1.506     raeburn  5851: sub auto_new_course {
1.508     raeburn  5852:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5853:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5854:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5855:     return $response;
                   5856: }
1.776     albertel 5857: 
1.506     raeburn  5858: sub auto_validate_courseID {
1.508     raeburn  5859:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5860:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5861:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5862:     return $response;
                   5863: }
1.776     albertel 5864: 
1.1007    raeburn  5865: sub auto_validate_instcode {
1.1020    raeburn  5866:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  5867:     my ($homeserver,$response);
                   5868:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5869:         $homeserver = &homeserver($cnum,$cdom);
                   5870:     }
                   5871:     if (!defined($homeserver)) {
                   5872:         if ($cdom =~ /^$match_domain$/) {
                   5873:             $homeserver = &domain($cdom,'primary');
                   5874:         }
                   5875:     }
1.1065    raeburn  5876:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   5877:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  5878:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   5879:     return ($outcome,$description);
1.1007    raeburn  5880: }
                   5881: 
1.506     raeburn  5882: sub auto_create_password {
1.873     raeburn  5883:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5884:     my ($homeserver,$response);
1.506     raeburn  5885:     my $create_passwd = 0;
                   5886:     my $authchk = '';
1.873     raeburn  5887:     if ($udom =~ /^$match_domain$/) {
                   5888:         $homeserver = &domain($udom,'primary');
                   5889:     }
                   5890:     if ($homeserver eq '') {
                   5891:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5892:             $homeserver = &homeserver($cnum,$cdom);
                   5893:         }
                   5894:     }
                   5895:     if ($homeserver eq '') {
                   5896:         $authchk = 'nodomain';
1.506     raeburn  5897:     } else {
1.873     raeburn  5898:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5899:         if ($response eq 'refused') {
                   5900:             $authchk = 'refused';
                   5901:         } else {
1.901     albertel 5902:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5903:         }
1.506     raeburn  5904:     }
                   5905:     return ($authparam,$create_passwd,$authchk);
                   5906: }
                   5907: 
1.706     raeburn  5908: sub auto_photo_permission {
                   5909:     my ($cnum,$cdom,$students) = @_;
                   5910:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5911:     my ($outcome,$perm_reqd,$conditions) = 
                   5912: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5913:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5914: 	return (undef,undef);
                   5915:     }
1.706     raeburn  5916:     return ($outcome,$perm_reqd,$conditions);
                   5917: }
                   5918: 
                   5919: sub auto_checkphotos {
                   5920:     my ($uname,$udom,$pid) = @_;
                   5921:     my $homeserver = &homeserver($uname,$udom);
                   5922:     my ($result,$resulttype);
                   5923:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5924: 				   &escape($uname).':'.&escape($pid),
                   5925: 				   $homeserver));
1.709     albertel 5926:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5927: 	return (undef,undef);
                   5928:     }
1.706     raeburn  5929:     if ($outcome) {
                   5930:         ($result,$resulttype) = split(/:/,$outcome);
                   5931:     } 
                   5932:     return ($result,$resulttype);
                   5933: }
                   5934: 
                   5935: sub auto_photochoice {
                   5936:     my ($cnum,$cdom) = @_;
                   5937:     my $homeserver = &homeserver($cnum,$cdom);
                   5938:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5939: 						       &escape($cdom),
                   5940: 						       $homeserver)));
1.709     albertel 5941:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5942: 	return (undef,undef);
                   5943:     }
1.706     raeburn  5944:     return ($update,$comment);
                   5945: }
                   5946: 
                   5947: sub auto_photoupdate {
                   5948:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5949:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5950:     my $host=&hostname($homeserver);
1.706     raeburn  5951:     my $cmd = '';
                   5952:     my $maxtries = 1;
1.800     albertel 5953:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5954:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5955:     }
                   5956:     $cmd =~ s/%%$//;
                   5957:     $cmd = &escape($cmd);
                   5958:     my $query = 'institutionalphotos';
                   5959:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5960:     unless ($queryid=~/^\Q$host\E\_/) {
                   5961:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5962:         return 'error: '.$queryid;
                   5963:     }
                   5964:     my $reply = &get_query_reply($queryid);
                   5965:     my $tries = 1;
                   5966:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5967:         $reply = &get_query_reply($queryid);
                   5968:         $tries ++;
                   5969:     }
                   5970:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5971:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5972:     } else {
                   5973:         my @responses = split(/:/,$reply);
                   5974:         my $outcome = shift(@responses); 
                   5975:         foreach my $item (@responses) {
                   5976:             my ($key,$value) = split(/=/,$item);
                   5977:             $$photo{$key} = $value;
                   5978:         }
                   5979:         return $outcome;
                   5980:     }
                   5981:     return 'error';
                   5982: }
                   5983: 
1.521     raeburn  5984: sub auto_instcode_format {
1.793     albertel 5985:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5986: 	$cat_order) = @_;
1.521     raeburn  5987:     my $courses = '';
1.772     raeburn  5988:     my @homeservers;
1.521     raeburn  5989:     if ($caller eq 'global') {
1.841     albertel 5990: 	my %servers = &get_servers($codedom,'library');
                   5991: 	foreach my $tryserver (keys(%servers)) {
                   5992: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5993: 		push(@homeservers,$tryserver);
                   5994: 	    }
1.584     raeburn  5995:         }
1.1022    raeburn  5996:     } elsif ($caller eq 'requests') {
                   5997:         if ($codedom =~ /^$match_domain$/) {
                   5998:             my $chome = &domain($codedom,'primary');
                   5999:             unless ($chome eq 'no_host') {
                   6000:                 push(@homeservers,$chome);
                   6001:             }
                   6002:         }
1.521     raeburn  6003:     } else {
1.772     raeburn  6004:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6005:     }
1.793     albertel 6006:     foreach my $code (keys(%{$instcodes})) {
                   6007:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6008:     }
                   6009:     chop($courses);
1.772     raeburn  6010:     my $ok_response = 0;
                   6011:     my $response;
                   6012:     while (@homeservers > 0 && $ok_response == 0) {
                   6013:         my $server = shift(@homeservers); 
                   6014:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6015:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6016:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6017: 		split(/:/,$response);
1.772     raeburn  6018:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6019:             push(@{$codetitles},&str2array($codetitles_str));
                   6020:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6021:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6022:             $ok_response = 1;
                   6023:         }
                   6024:     }
                   6025:     if ($ok_response) {
1.521     raeburn  6026:         return 'ok';
1.772     raeburn  6027:     } else {
                   6028:         return $response;
1.521     raeburn  6029:     }
                   6030: }
                   6031: 
1.792     raeburn  6032: sub auto_instcode_defaults {
                   6033:     my ($domain,$returnhash,$code_order) = @_;
                   6034:     my @homeservers;
1.841     albertel 6035: 
                   6036:     my %servers = &get_servers($domain,'library');
                   6037:     foreach my $tryserver (keys(%servers)) {
                   6038: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6039: 	    push(@homeservers,$tryserver);
                   6040: 	}
1.792     raeburn  6041:     }
1.841     albertel 6042: 
1.792     raeburn  6043:     my $response;
1.841     albertel 6044:     foreach my $server (@homeservers) {
1.792     raeburn  6045:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6046:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6047: 	
                   6048: 	foreach my $pair (split(/\&/,$response)) {
                   6049: 	    my ($name,$value)=split(/\=/,$pair);
                   6050: 	    if ($name eq 'code_order') {
                   6051: 		@{$code_order} = split(/\&/,&unescape($value));
                   6052: 	    } else {
                   6053: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6054: 	    }
                   6055: 	}
                   6056: 	return 'ok';
1.792     raeburn  6057:     }
1.841     albertel 6058: 
                   6059:     return $response;
1.1003    raeburn  6060: }
                   6061: 
                   6062: sub auto_possible_instcodes {
1.1007    raeburn  6063:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6064:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6065:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6066:         return;
                   6067:     }
1.1003    raeburn  6068:     my (@homeservers,$uhome);
                   6069:     if (defined(&domain($domain,'primary'))) {
                   6070:         $uhome=&domain($domain,'primary');
                   6071:         push(@homeservers,&domain($domain,'primary'));
                   6072:     } else {
                   6073:         my %servers = &get_servers($domain,'library');
                   6074:         foreach my $tryserver (keys(%servers)) {
                   6075:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6076:                 push(@homeservers,$tryserver);
                   6077:             }
                   6078:         }
                   6079:     }
                   6080:     my $response;
                   6081:     foreach my $server (@homeservers) {
                   6082:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6083:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6084:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6085:             split(':',$response);
                   6086:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6087:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6088:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6089:             my ($name,$value)=split('=',$item);
                   6090:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6091:         }
                   6092:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6093:             my ($name,$value)=split('=',$item);
                   6094:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6095:         }
                   6096:         return 'ok';
                   6097:     }
                   6098:     return $response;
                   6099: }
1.792     raeburn  6100: 
1.1010    raeburn  6101: sub auto_courserequest_checks {
                   6102:     my ($dom) = @_;
1.1020    raeburn  6103:     my ($homeserver,%validations);
                   6104:     if ($dom =~ /^$match_domain$/) {
                   6105:         $homeserver = &domain($dom,'primary');
                   6106:     }
                   6107:     unless ($homeserver eq 'no_host') {
                   6108:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6109:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6110:             my @items = split(/&/,$response);
                   6111:             foreach my $item (@items) {
                   6112:                 my ($key,$value) = split('=',$item);
                   6113:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6114:             }
                   6115:         }
                   6116:     }
1.1010    raeburn  6117:     return %validations; 
                   6118: }
                   6119: 
1.1020    raeburn  6120: sub auto_courserequest_validation {
                   6121:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6122:     my ($homeserver,$response);
                   6123:     if ($dom =~ /^$match_domain$/) {
                   6124:         $homeserver = &domain($dom,'primary');
                   6125:     }
                   6126:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6127:           
1.1020    raeburn  6128:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6129:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6130:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6131:                                     $homeserver));
                   6132:     }
                   6133:     return $response;
                   6134: }
                   6135: 
1.777     albertel 6136: sub auto_validate_class_sec {
1.918     raeburn  6137:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6138:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6139:     my $ownerlist;
                   6140:     if (ref($owners) eq 'ARRAY') {
                   6141:         $ownerlist = join(',',@{$owners});
                   6142:     } else {
                   6143:         $ownerlist = $owners;
                   6144:     }
1.773     raeburn  6145:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6146:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6147:     return $response;
                   6148: }
                   6149: 
1.679     raeburn  6150: # ------------------------------------------------------- Course Group routines
                   6151: 
                   6152: sub get_coursegroups {
1.809     raeburn  6153:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6154:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6155: }
                   6156: 
1.679     raeburn  6157: sub modify_coursegroup {
                   6158:     my ($cdom,$cnum,$groupsettings) = @_;
                   6159:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6160: }
                   6161: 
1.809     raeburn  6162: sub toggle_coursegroup_status {
                   6163:     my ($cdom,$cnum,$group,$action) = @_;
                   6164:     my ($from_namespace,$to_namespace);
                   6165:     if ($action eq 'delete') {
                   6166:         $from_namespace = 'coursegroups';
                   6167:         $to_namespace = 'deleted_groups';
                   6168:     } else {
                   6169:         $from_namespace = 'deleted_groups';
                   6170:         $to_namespace = 'coursegroups';
                   6171:     }
                   6172:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6173:     if (my $tmp = &error(%curr_group)) {
                   6174:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6175:         return ('read error',$tmp);
                   6176:     } else {
                   6177:         my %savedsettings = %curr_group; 
1.809     raeburn  6178:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6179:         my $deloutcome;
                   6180:         if ($result eq 'ok') {
1.809     raeburn  6181:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6182:         } else {
                   6183:             return ('write error',$result);
                   6184:         }
                   6185:         if ($deloutcome eq 'ok') {
                   6186:             return 'ok';
                   6187:         } else {
                   6188:             return ('delete error',$deloutcome);
                   6189:         }
                   6190:     }
                   6191: }
                   6192: 
1.679     raeburn  6193: sub modify_group_roles {
1.957     raeburn  6194:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6195:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6196:     my $role = 'gr/'.&escape($userprivs);
                   6197:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6198:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6199:     if ($result eq 'ok') {
                   6200:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6201:     }
1.679     raeburn  6202:     return $result;
                   6203: }
                   6204: 
                   6205: sub modify_coursegroup_membership {
                   6206:     my ($cdom,$cnum,$membership) = @_;
                   6207:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6208:     return $result;
                   6209: }
                   6210: 
1.682     raeburn  6211: sub get_active_groups {
                   6212:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6213:     my $now = time;
                   6214:     my %groups = ();
                   6215:     foreach my $key (keys(%env)) {
1.811     albertel 6216:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6217:             my ($start,$end) = split(/\./,$env{$key});
                   6218:             if (($end!=0) && ($end<$now)) { next; }
                   6219:             if (($start!=0) && ($start>$now)) { next; }
                   6220:             if ($1 eq $cdom && $2 eq $cnum) {
                   6221:                 $groups{$3} = $env{$key} ;
                   6222:             }
                   6223:         }
                   6224:     }
                   6225:     return %groups;
                   6226: }
                   6227: 
1.683     raeburn  6228: sub get_group_membership {
                   6229:     my ($cdom,$cnum,$group) = @_;
                   6230:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6231: }
                   6232: 
                   6233: sub get_users_groups {
                   6234:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6235:     my @usersgroups;
1.683     raeburn  6236:     my $cachetime=1800;
                   6237: 
                   6238:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6239:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6240:     if (defined($cached)) {
1.734     albertel 6241:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6242:     } else {  
                   6243:         $grouplist = '';
1.816     raeburn  6244:         my $courseurl = &courseid_to_courseurl($courseid);
                   6245:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  6246:         my $access_end = $env{'course.'.$courseid.
                   6247:                               '.default_enrollment_end_date'};
                   6248:         my $now = time;
                   6249:         foreach my $key (keys(%roleshash)) {
                   6250:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6251:                 my $group = $1;
                   6252:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6253:                     my $start = $2;
                   6254:                     my $end = $1;
                   6255:                     if ($start == -1) { next; } # deleted from group
                   6256:                     if (($start!=0) && ($start>$now)) { next; }
                   6257:                     if (($end!=0) && ($end<$now)) {
                   6258:                         if ($access_end && $access_end < $now) {
                   6259:                             if ($access_end - $end < 86400) {
                   6260:                                 push(@usersgroups,$group);
1.733     raeburn  6261:                             }
                   6262:                         }
1.817     raeburn  6263:                         next;
1.733     raeburn  6264:                     }
1.817     raeburn  6265:                     push(@usersgroups,$group);
1.683     raeburn  6266:                 }
                   6267:             }
                   6268:         }
1.817     raeburn  6269:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6270:         $grouplist = join(':',@usersgroups);
                   6271:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6272:     }
1.733     raeburn  6273:     return @usersgroups;
1.683     raeburn  6274: }
                   6275: 
                   6276: sub devalidate_getgroups_cache {
                   6277:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6278:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6279: 
1.683     raeburn  6280:     my $hashid="$udom:$uname:$courseid";
                   6281:     &devalidate_cache_new('getgroups',$hashid);
                   6282: }
                   6283: 
1.12      www      6284: # ------------------------------------------------------------------ Plain Text
                   6285: 
                   6286: sub plaintext {
1.988     raeburn  6287:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6288:     if ($short =~ m{^cr/}) {
1.758     albertel 6289: 	return (split('/',$short))[-1];
                   6290:     }
1.742     raeburn  6291:     if (!defined($cid)) {
                   6292:         $cid = $env{'request.course.id'};
                   6293:     }
                   6294:     my %rolenames = (
1.1008    raeburn  6295:                       Course    => 'std',
                   6296:                       Community => 'alt1',
1.742     raeburn  6297:                     );
1.1037    raeburn  6298:     if ($cid ne '') {
                   6299:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6300:             unless ($forcedefault) {
                   6301:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6302:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6303:                 return &Apache::lonlocal::mt($roletext);
                   6304:             }
                   6305:         }
                   6306:     }
                   6307:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6308:         (defined($rolenames{$type})) && 
                   6309:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6310:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6311:     } elsif ($cid ne '') {
                   6312:         my $crstype = $env{'course.'.$cid.'.type'};
                   6313:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6314:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6315:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6316:         }
1.742     raeburn  6317:     }
1.1037    raeburn  6318:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6319: }
                   6320: 
                   6321: # ----------------------------------------------------------------- Assign Role
                   6322: 
                   6323: sub assignrole {
1.957     raeburn  6324:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6325:         $context)=@_;
1.21      www      6326:     my $mrole;
                   6327:     if ($role =~ /^cr\//) {
1.393     www      6328:         my $cwosec=$url;
1.811     albertel 6329:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6330: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6331:            my $refused = 1;
                   6332:            if ($context eq 'requestcourses') {
                   6333:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6334:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6335:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6336:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6337:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6338:                            if ($crsenv{'internal.courseowner'} eq
                   6339:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6340:                                $refused = '';
                   6341:                            }
                   6342:                        }
                   6343:                    }
                   6344:                }
                   6345:            }
                   6346:            if ($refused) {
                   6347:                &logthis('Refused custom assignrole: '.
                   6348:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6349:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6350:                return 'refused';
                   6351:            }
1.104     www      6352:         }
1.21      www      6353:         $mrole='cr';
1.678     raeburn  6354:     } elsif ($role =~ /^gr\//) {
                   6355:         my $cwogrp=$url;
1.811     albertel 6356:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6357:         unless (&allowed('mdg',$cwogrp)) {
                   6358:             &logthis('Refused group assignrole: '.
                   6359:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6360:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6361:             return 'refused';
                   6362:         }
                   6363:         $mrole='gr';
1.21      www      6364:     } else {
1.82      www      6365:         my $cwosec=$url;
1.811     albertel 6366:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6367:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6368:             my $refused;
                   6369:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6370:                 if (!(&allowed('c'.$role,$url))) {
                   6371:                     $refused = 1;
                   6372:                 }
                   6373:             } else {
                   6374:                 $refused = 1;
                   6375:             }
1.947     raeburn  6376:             if ($refused) {
1.1045    raeburn  6377:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6378:                 if (!$selfenroll && $context eq 'course') {
                   6379:                     my %crsenv;
                   6380:                     if ($role eq 'cc' || $role eq 'co') {
                   6381:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6382:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6383:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6384:                                 if ($crsenv{'internal.courseowner'} eq 
                   6385:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6386:                                     $refused = '';
                   6387:                                 }
                   6388:                             }
                   6389:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6390:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6391:                                 if ($crsenv{'internal.courseowner'} eq 
                   6392:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6393:                                     $refused = '';
                   6394:                                 }
                   6395:                             }
                   6396:                         }
                   6397:                     }
                   6398:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6399:                     $refused = '';
1.1017    raeburn  6400:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6401:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6402:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6403:                         my $wrongcc;
                   6404:                         if ($cnum =~ /^$match_community$/) {
                   6405:                             $wrongcc = 1 if ($role eq 'cc');
                   6406:                         } else {
                   6407:                             $wrongcc = 1 if ($role eq 'co');
                   6408:                         }
                   6409:                         unless ($wrongcc) {
                   6410:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6411:                             if ($crsenv{'internal.courseowner'} eq 
                   6412:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6413:                                 $refused = '';
                   6414:                             }
1.1017    raeburn  6415:                         }
                   6416:                     }
                   6417:                 }
                   6418:                 if ($refused) {
1.947     raeburn  6419:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6420:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6421: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6422:                     return 'refused';
                   6423:                 }
1.932     raeburn  6424:             }
1.104     www      6425:         }
1.21      www      6426:         $mrole=$role;
                   6427:     }
1.620     albertel 6428:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6429:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6430:     if ($end) { $command.='_'.$end; }
1.21      www      6431:     if ($start) {
                   6432: 	if ($end) { 
1.81      www      6433:            $command.='_'.$start; 
1.21      www      6434:         } else {
1.81      www      6435:            $command.='_0_'.$start;
1.21      www      6436:         }
                   6437:     }
1.739     raeburn  6438:     my $origstart = $start;
                   6439:     my $origend = $end;
1.957     raeburn  6440:     my $delflag;
1.357     www      6441: # actually delete
                   6442:     if ($deleteflag) {
1.373     www      6443: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6444: # modify command to delete the role
1.620     albertel 6445:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6446:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6447: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6448: # set start and finish to negative values for userrolelog
                   6449:            $start=-1;
                   6450:            $end=-1;
1.957     raeburn  6451:            $delflag = 1;
1.357     www      6452:         }
                   6453:     }
                   6454: # send command
1.349     www      6455:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6456: # log new user role if status is ok
1.349     www      6457:     if ($answer eq 'ok') {
1.663     raeburn  6458: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6459: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6460:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6461:         unless ($role =~ /^gr/) {
                   6462:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6463:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6464:         }
1.1053    raeburn  6465:         if ($role eq 'cc') {
                   6466:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6467:         }
1.349     www      6468:     }
                   6469:     return $answer;
1.169     harris41 6470: }
                   6471: 
1.1053    raeburn  6472: sub autoupdate_coowners {
                   6473:     my ($url,$end,$start,$uname,$udom) = @_;
                   6474:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6475:     if (($cdom ne '') && ($cnum ne '')) {
                   6476:         my $now = time;
                   6477:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6478:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6479:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6480:             my $instcode = $coursehash{'internal.coursecode'};
                   6481:             if ($instcode ne '') {
1.1056    raeburn  6482:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6483:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6484:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6485:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6486:                         if ($result eq 'valid') {
                   6487:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6488:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6489:                                     push(@newcoowners,$coowner);
                   6490:                                 }
                   6491:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6492:                                     push(@newcoowners,$uname.':'.$udom);
                   6493:                                 }
                   6494:                                 @newcoowners = sort(@newcoowners);
                   6495:                             } else {
                   6496:                                 push(@newcoowners,$uname.':'.$udom);
                   6497:                             }
                   6498:                         } else {
                   6499:                             if ($coursehash{'internal.co-owners'}) {
                   6500:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6501:                                     unless ($coowner eq $uname.':'.$udom) {
                   6502:                                         push(@newcoowners,$coowner);
                   6503:                                     }
                   6504:                                 }
                   6505:                                 unless (@newcoowners > 0) {
                   6506:                                     $delcoowners = 1;
                   6507:                                     $coowners = '';
                   6508:                                 }
                   6509:                             }
                   6510:                         }
                   6511:                         if (@newcoowners || $delcoowners) {
                   6512:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6513:                                             $delcoowners,@newcoowners);
                   6514:                         }
                   6515:                     }
                   6516:                 }
                   6517:             }
                   6518:         }
                   6519:     }
                   6520: }
                   6521: 
                   6522: sub store_coowners {
                   6523:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6524:     my $cid = $cdom.'_'.$cnum;
                   6525:     my ($coowners,$delresult,$putresult);
                   6526:     if (@newcoowners) {
                   6527:         $coowners = join(',',@newcoowners);
                   6528:         my %coownershash = (
                   6529:                             'internal.co-owners' => $coowners,
                   6530:                            );
                   6531:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6532:         if ($putresult eq 'ok') {
                   6533:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6534:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6535:             }
                   6536:         }
                   6537:     }
                   6538:     if ($delcoowners) {
                   6539:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6540:         if ($delresult eq 'ok') {
                   6541:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6542:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6543:             }
                   6544:         }
                   6545:     }
                   6546:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6547:         my %crsinfo =
                   6548:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6549:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6550:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6551:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6552:         }
                   6553:     }
                   6554: }
                   6555: 
1.169     harris41 6556: # -------------------------------------------------- Modify user authentication
1.197     www      6557: # Overrides without validation
                   6558: 
1.169     harris41 6559: sub modifyuserauth {
                   6560:     my ($udom,$uname,$umode,$upass)=@_;
                   6561:     my $uhome=&homeserver($uname,$udom);
1.197     www      6562:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6563:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6564:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6565:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6566:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6567: 		     &escape($upass),$uhome);
1.620     albertel 6568:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6569:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6570:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6571:     &log($udom,,$uname,$uhome,
1.620     albertel 6572:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6573:                                      $env{'user.name'}.', '.$umode.
1.197     www      6574:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6575:     unless ($reply eq 'ok') {
1.197     www      6576:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6577: 	return 'error: '.$reply;
                   6578:     }   
1.170     harris41 6579:     return 'ok';
1.80      www      6580: }
                   6581: 
1.81      www      6582: # --------------------------------------------------------------- Modify a user
1.80      www      6583: 
1.81      www      6584: sub modifyuser {
1.206     matthew  6585:     my ($udom,    $uname, $uid,
                   6586:         $umode,   $upass, $first,
                   6587:         $middle,  $last,  $gene,
1.1058    raeburn  6588:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6589:     $udom= &LONCAPA::clean_domain($udom);
                   6590:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6591:     my $showcandelete = 'none';
                   6592:     if (ref($candelete) eq 'ARRAY') {
                   6593:         if (@{$candelete} > 0) {
                   6594:             $showcandelete = join(', ',@{$candelete});
                   6595:         }
                   6596:     }
1.81      www      6597:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6598:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6599: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6600:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6601:                                      ' desiredhome not specified'). 
1.620     albertel 6602:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6603:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6604:     my $uhome=&homeserver($uname,$udom,'true');
1.1075  ! raeburn  6605:     my $newuser;
        !          6606:     if ($uhome eq 'no_host') {
        !          6607:         $newuser = 1;
        !          6608:     }
1.80      www      6609: # ----------------------------------------------------------------- Create User
1.406     albertel 6610:     if (($uhome eq 'no_host') && 
                   6611: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6612:         my $unhome='';
1.844     albertel 6613:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6614:             $unhome = $desiredhome;
1.620     albertel 6615: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6616: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6617:         } else { # load balancing routine for determining $unhome
1.81      www      6618:             my $loadm=10000000;
1.841     albertel 6619: 	    my %servers = &get_servers($udom,'library');
                   6620: 	    foreach my $tryserver (keys(%servers)) {
                   6621: 		my $answer=reply('load',$tryserver);
                   6622: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6623: 		    $loadm=$answer;
                   6624: 		    $unhome=$tryserver;
                   6625: 		}
1.80      www      6626: 	    }
                   6627:         }
                   6628:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6629: 	    return 'error: unable to find a home server for '.$uname.
                   6630:                    ' in domain '.$udom;
1.80      www      6631:         }
                   6632:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6633:                          &escape($upass),$unhome);
                   6634: 	unless ($reply eq 'ok') {
                   6635:             return 'error: '.$reply;
                   6636:         }   
1.230     stredwic 6637:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6638:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6639: 	    return 'error: unable verify users home machine.';
1.80      www      6640:         }
1.209     matthew  6641:     }   # End of creation of new user
1.80      www      6642: # ---------------------------------------------------------------------- Add ID
                   6643:     if ($uid) {
                   6644:        $uid=~tr/A-Z/a-z/;
                   6645:        my %uidhash=&idrget($udom,$uname);
1.196     www      6646:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6647:          && (!$forceid)) {
1.80      www      6648: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6649: 	      return 'error: user id "'.$uid.'" does not match '.
                   6650:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6651:           }
                   6652:        } else {
                   6653: 	  &idput($udom,($uname => $uid));
                   6654:        }
                   6655:     }
                   6656: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6657:     my @tmp=&get('environment',
1.899     raeburn  6658: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6659:                     'permanentemail','inststatus'],
1.134     albertel 6660: 		   $udom,$uname);
1.1075  ! raeburn  6661:     my (%names,%oldnames);
1.313     matthew  6662:     if ($tmp[0] =~ m/^error:.*/) { 
                   6663:         %names=(); 
                   6664:     } else {
                   6665:         %names = @tmp;
1.1075  ! raeburn  6666:         %oldnames = %names;
1.313     matthew  6667:     }
1.388     www      6668: #
1.1058    raeburn  6669: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6670: # of users did not contain them), do not overwrite existing values
                   6671: # unless field is in $candelete array ref.  
                   6672: #
                   6673: 
                   6674:     my @fields = ('firstname','middlename','lastname','generation',
                   6675:                   'permanentemail','id');
                   6676:     my %newvalues;
                   6677:     if (ref($candelete) eq 'ARRAY') {
                   6678:         foreach my $field (@fields) {
                   6679:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6680:                 if ($field eq 'firstname') {
                   6681:                     $names{$field} = $first;
                   6682:                 } elsif ($field eq 'middlename') {
                   6683:                     $names{$field} = $middle;
                   6684:                 } elsif ($field eq 'lastname') {
                   6685:                     $names{$field} = $last;
                   6686:                 } elsif ($field eq 'generation') { 
                   6687:                     $names{$field} = $gene;
                   6688:                 } elsif ($field eq 'permanentemail') {
                   6689:                     $names{$field} = $email;
                   6690:                 } elsif ($field eq 'id') {
                   6691:                     $names{$field}  = $uid;
                   6692:                 }
                   6693:             }
                   6694:         }
                   6695:     }
1.388     www      6696:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6697:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6698:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6699:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6700:     if ($email) {
                   6701:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6702:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6703:     }
1.899     raeburn  6704:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6705:     if (defined($inststatus)) {
                   6706:         $names{'inststatus'} = '';
                   6707:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6708:         if (ref($usertypes) eq 'HASH') {
                   6709:             my @okstatuses; 
                   6710:             foreach my $item (split(/:/,$inststatus)) {
                   6711:                 if (defined($usertypes->{$item})) {
                   6712:                     push(@okstatuses,$item);  
                   6713:                 }
                   6714:             }
                   6715:             if (@okstatuses) {
                   6716:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6717:             }
                   6718:         }
                   6719:     }
1.1075  ! raeburn  6720:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6721:                  $umode.', '.$first.', '.$middle.', '.
1.1075  ! raeburn  6722:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6723:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6724:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6725:     } else {
                   6726:         $logmsg .= ' during self creation';
                   6727:     }
1.1075  ! raeburn  6728:     my $changed;
        !          6729:     if ($newuser) {
        !          6730:         $changed = 1;
        !          6731:     } else {
        !          6732:         foreach my $field (@fields) {
        !          6733:             if ($names{$field} ne $oldnames{$field}) {
        !          6734:                 $changed = 1;
        !          6735:                 last;
        !          6736:             }
        !          6737:         }
        !          6738:     }
        !          6739:     unless ($changed) {
        !          6740:         $logmsg = 'No changes in user information needed for: '.$logmsg;
        !          6741:         &logthis($logmsg);
        !          6742:         return 'ok';
        !          6743:     }
        !          6744:     my $reply = &put('environment', \%names, $udom,$uname);
        !          6745:     if ($reply ne 'ok') { 
        !          6746:         return 'error: '.$reply;
        !          6747:     }
        !          6748:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
        !          6749:     &devalidate_cache_new('namescache',$uname.':'.$udom);
        !          6750:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6751:     &logthis($logmsg);
1.134     albertel 6752:     return 'ok';
1.80      www      6753: }
                   6754: 
1.81      www      6755: # -------------------------------------------------------------- Modify student
1.80      www      6756: 
1.81      www      6757: sub modifystudent {
                   6758:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6759:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6760:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6761:     if (!$cid) {
1.620     albertel 6762: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6763: 	    return 'not_in_class';
                   6764: 	}
1.80      www      6765:     }
                   6766: # --------------------------------------------------------------- Make the user
1.81      www      6767:     my $reply=&modifyuser
1.209     matthew  6768: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6769:          $desiredhome,$email,$inststatus);
1.80      www      6770:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6771:     # This will cause &modify_student_enrollment to get the uid from the
                   6772:     # students environment
                   6773:     $uid = undef if (!$forceid);
1.455     albertel 6774:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6775: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6776:     return $reply;
                   6777: }
                   6778: 
                   6779: sub modify_student_enrollment {
1.957     raeburn  6780:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6781:     my ($cdom,$cnum,$chome);
                   6782:     if (!$cid) {
1.620     albertel 6783: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6784: 	    return 'not_in_class';
                   6785: 	}
1.620     albertel 6786: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6787: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6788:     } else {
                   6789: 	($cdom,$cnum)=split(/_/,$cid);
                   6790:     }
1.620     albertel 6791:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6792:     if (!$chome) {
1.457     raeburn  6793: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6794:     }
1.455     albertel 6795:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6796:     # Make sure the user exists
1.81      www      6797:     my $uhome=&homeserver($uname,$udom);
                   6798:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6799: 	return 'error: no such user';
                   6800:     }
1.297     matthew  6801:     # Get student data if we were not given enough information
                   6802:     if (!defined($first)  || $first  eq '' || 
                   6803:         !defined($last)   || $last   eq '' || 
                   6804:         !defined($uid)    || $uid    eq '' || 
                   6805:         !defined($middle) || $middle eq '' || 
                   6806:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6807:         # They did not supply us with enough data to enroll the student, so
                   6808:         # we need to pick up more information.
1.297     matthew  6809:         my %tmp = &get('environment',
1.294     matthew  6810:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6811:                        ,$udom,$uname);
                   6812: 
1.800     albertel 6813:         #foreach my $key (keys(%tmp)) {
                   6814:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6815:         #}
1.294     matthew  6816:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6817:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6818:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6819:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6820:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6821:     }
1.556     albertel 6822:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6823:     my $reply=cput('classlist',
                   6824: 		   {"$uname:$udom" => 
1.515     raeburn  6825: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6826: 		   $cdom,$cnum);
1.81      www      6827:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6828: 	return 'error: '.$reply;
1.652     albertel 6829:     } else {
                   6830: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6831:     }
1.297     matthew  6832:     # Add student role to user
1.83      www      6833:     my $uurl='/'.$cid;
1.81      www      6834:     $uurl=~s/\_/\//g;
                   6835:     if ($usec) {
                   6836: 	$uurl.='/'.$usec;
                   6837:     }
1.957     raeburn  6838:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6839: }
                   6840: 
1.556     albertel 6841: sub format_name {
                   6842:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6843:     my $name;
                   6844:     if ($first ne 'lastname') {
                   6845: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6846:     } else {
                   6847: 	if ($lastname=~/\S/) {
                   6848: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6849: 	    $name=~s/\s+,/,/;
                   6850: 	} else {
                   6851: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6852: 	}
                   6853:     }
                   6854:     $name=~s/^\s+//;
                   6855:     $name=~s/\s+$//;
                   6856:     $name=~s/\s+/ /g;
                   6857:     return $name;
                   6858: }
                   6859: 
1.84      www      6860: # ------------------------------------------------- Write to course preferences
                   6861: 
                   6862: sub writecoursepref {
                   6863:     my ($courseid,%prefs)=@_;
                   6864:     $courseid=~s/^\///;
                   6865:     $courseid=~s/\_/\//g;
                   6866:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6867:     my $chome=homeserver($cnum,$cdomain);
                   6868:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6869: 	return 'error: no such course';
                   6870:     }
                   6871:     my $cstring='';
1.800     albertel 6872:     foreach my $pref (keys(%prefs)) {
                   6873: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6874:     }
1.84      www      6875:     $cstring=~s/\&$//;
                   6876:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6877: }
                   6878: 
                   6879: # ---------------------------------------------------------- Make/modify course
                   6880: 
                   6881: sub createcourse {
1.741     raeburn  6882:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  6883:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      6884:     $url=&declutter($url);
                   6885:     my $cid='';
1.1028    raeburn  6886:     if ($context eq 'requestcourses') {
                   6887:         my $can_create = 0;
                   6888:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   6889:         if ($udom eq $ownerdom) {
                   6890:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   6891:                                   $context)) {
                   6892:                 $can_create = 1;
                   6893:             }
                   6894:         } else {
                   6895:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   6896:                                            $category);
                   6897:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   6898:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   6899:                 if (@curr > 0) {
                   6900:                     my @options = qw(approval validate autolimit);
                   6901:                     my $optregex = join('|',@options);
                   6902:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   6903:                         $can_create = 1;
                   6904:                     }
                   6905:                 }
                   6906:             }
                   6907:         }
                   6908:         if ($can_create) {
                   6909:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   6910:                 unless (&allowed('ccc',$udom)) {
                   6911:                     return 'refused'; 
                   6912:                 }
1.1017    raeburn  6913:             }
                   6914:         } else {
                   6915:             return 'refused';
                   6916:         }
1.1028    raeburn  6917:     } elsif (!&allowed('ccc',$udom)) {
                   6918:         return 'refused';
1.84      www      6919:     }
1.1011    raeburn  6920: # --------------------------------------------------------------- Get Unique ID
                   6921:     my $uname;
                   6922:     if ($cnum =~ /^$match_courseid$/) {
                   6923:         my $chome=&homeserver($cnum,$udom,'true');
                   6924:         if (($chome eq '') || ($chome eq 'no_host')) {
                   6925:             $uname = $cnum;
                   6926:         } else {
1.1038    raeburn  6927:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  6928:         }
                   6929:     } else {
1.1038    raeburn  6930:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  6931:     }
                   6932:     return $uname if ($uname =~ /^error/);
                   6933: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  6934:     if (!defined($course_server)) {
                   6935:         if (defined(&domain($udom,'primary'))) {
                   6936:             $course_server = &domain($udom,'primary');
                   6937:         } else {
                   6938:             $course_server = $env{'user.home'}; 
                   6939:         }
                   6940:     }
                   6941:     my %host_servers =
                   6942:         &Apache::lonnet::get_servers($udom,'library');
                   6943:     unless ($host_servers{$course_server}) {
                   6944:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  6945:     }
1.84      www      6946: # ------------------------------------------------------------- Make the course
                   6947:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6948:                       $course_server);
1.84      www      6949:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  6950:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6951:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6952: 	return 'error: no such course';
                   6953:     }
1.271     www      6954: # ----------------------------------------------------------------- Course made
1.516     raeburn  6955: # log existence
1.1029    raeburn  6956:     my $now = time;
1.918     raeburn  6957:     my $newcourse = {
                   6958:                     $udom.'_'.$uname => {
1.921     raeburn  6959:                                      description => $description,
                   6960:                                      inst_code   => $inst_code,
                   6961:                                      owner       => $course_owner,
                   6962:                                      type        => $crstype,
1.1029    raeburn  6963:                                      creator     => $env{'user.name'}.':'.
                   6964:                                                     $env{'user.domain'},
                   6965:                                      created     => $now,
                   6966:                                      context     => $context,
1.918     raeburn  6967:                                                 },
                   6968:                     };
1.921     raeburn  6969:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6970: # set toplevel url
1.271     www      6971:     my $topurl=$url;
                   6972:     unless ($nonstandard) {
                   6973: # ------------------------------------------ For standard courses, make top url
                   6974:         my $mapurl=&clutter($url);
1.278     www      6975:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6976:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6977: <map>
                   6978: <resource id="1" type="start"></resource>
                   6979: <resource id="2" src="$mapurl"></resource>
                   6980: <resource id="3" type="finish"></resource>
                   6981: <link index="1" from="1" to="2"></link>
                   6982: <link index="2" from="2" to="3"></link>
                   6983: </map>
                   6984: ENDINITMAP
                   6985:         $topurl=&declutter(
1.638     albertel 6986:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6987:                           );
                   6988:     }
                   6989: # ----------------------------------------------------------- Write preferences
1.84      www      6990:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  6991:                      ('description'              => $description,
                   6992:                       'url'                      => $topurl,
                   6993:                       'internal.creator'         => $env{'user.name'}.':'.
                   6994:                                                     $env{'user.domain'},
                   6995:                       'internal.created'         => $now,
                   6996:                       'internal.creationcontext' => $context)
                   6997:                     );
1.84      www      6998:     return '/'.$udom.'/'.$uname;
                   6999: }
                   7000: 
1.1011    raeburn  7001: # ------------------------------------------------------------------- Create ID
                   7002: sub generate_coursenum {
1.1038    raeburn  7003:     my ($udom,$crstype) = @_;
1.1011    raeburn  7004:     my $domdesc = &domain($udom);
                   7005:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7006:     my $first;
                   7007:     if ($crstype eq 'Community') {
                   7008:         $first = '0';
                   7009:     } else {
                   7010:         $first = int(1+rand(9)); 
                   7011:     } 
                   7012:     my $uname=$first.
1.1011    raeburn  7013:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7014:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7015:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7016: # ----------------------------------------------- Make sure that does not exist
                   7017:     my $uhome=&homeserver($uname,$udom,'true');
                   7018:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7019:         if ($crstype eq 'Community') {
                   7020:             $first = '0';
                   7021:         } else {
                   7022:             $first = int(1+rand(9));
                   7023:         }
                   7024:         $uname=$first.
1.1011    raeburn  7025:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7026:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7027:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7028:         $uhome=&homeserver($uname,$udom,'true');
                   7029:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7030:             return 'error: unable to generate unique course-ID';
                   7031:         }
                   7032:     }
                   7033:     return $uname;
                   7034: }
                   7035: 
1.813     albertel 7036: sub is_course {
                   7037:     my ($cdom,$cnum) = @_;
                   7038:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7039: 				undef,'.');
1.813     albertel 7040:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7041:         return 1;
                   7042:     }
                   7043:     return 0;
                   7044: }
                   7045: 
1.1015    raeburn  7046: sub store_userdata {
                   7047:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7048:     my $result;
1.1016    raeburn  7049:     if ($datakey ne '') {
1.1013    raeburn  7050:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7051:             if ($udom eq '' || $uname eq '') {
                   7052:                 $udom = $env{'user.domain'};
                   7053:                 $uname = $env{'user.name'};
                   7054:             }
                   7055:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7056:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7057:                 $result = 'error: no_host';
                   7058:             } else {
                   7059:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7060:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7061: 
                   7062:                 my $namevalue='';
                   7063:                 foreach my $key (keys(%{$storehash})) {
                   7064:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7065:                 }
                   7066:                 $namevalue=~s/\&$//;
                   7067:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7068:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7069:             }
                   7070:         } else {
                   7071:             $result = 'error: data to store was not a hash reference'; 
                   7072:         }
                   7073:     } else {
                   7074:         $result= 'error: invalid requestkey'; 
                   7075:     }
                   7076:     return $result;
                   7077: }
                   7078: 
1.21      www      7079: # ---------------------------------------------------------- Assign Custom Role
                   7080: 
                   7081: sub assigncustomrole {
1.957     raeburn  7082:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7083:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7084:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7085: }
                   7086: 
                   7087: # ----------------------------------------------------------------- Revoke Role
                   7088: 
                   7089: sub revokerole {
1.957     raeburn  7090:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7091:     my $now=time;
1.965     raeburn  7092:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7093: }
                   7094: 
                   7095: # ---------------------------------------------------------- Revoke Custom Role
                   7096: 
                   7097: sub revokecustomrole {
1.957     raeburn  7098:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7099:     my $now=time;
1.357     www      7100:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7101:            $deleteflag,$selfenroll,$context);
1.17      www      7102: }
                   7103: 
1.533     banghart 7104: # ------------------------------------------------------------ Disk usage
1.535     albertel 7105: sub diskusage {
1.955     raeburn  7106:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7107:     $directorypath =~ s/\/$//;
                   7108:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7109:                        .&escape($getpropath).':'.&escape($uname).':'
                   7110:                        .&escape($udom),homeserver($uname,$udom));
                   7111:     if ($listing eq 'unknown_cmd') {
                   7112:         if ($getpropath) {
                   7113:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7114:         }
                   7115:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7116:     }
1.514     albertel 7117:     return $listing;
1.512     banghart 7118: }
                   7119: 
1.566     banghart 7120: sub is_locked {
                   7121:     my ($file_name, $domain, $user) = @_;
                   7122:     my @check;
                   7123:     my $is_locked;
                   7124:     push @check, $file_name;
1.613     albertel 7125:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7126: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7127:     my ($tmp)=keys(%locked);
                   7128:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7129:     
1.566     banghart 7130:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7131:         $is_locked = 'false';
                   7132:         foreach my $entry (@{$locked{$file_name}}) {
                   7133:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7134:                $is_locked = 'true';
                   7135:                last;
1.745     raeburn  7136:            }
                   7137:        }
1.566     banghart 7138:     } else {
                   7139:         $is_locked = 'false';
                   7140:     }
                   7141: }
                   7142: 
1.759     albertel 7143: sub declutter_portfile {
                   7144:     my ($file) = @_;
1.833     albertel 7145:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7146:     return $file;
                   7147: }
                   7148: 
1.559     banghart 7149: # ------------------------------------------------------------- Mark as Read Only
                   7150: 
                   7151: sub mark_as_readonly {
                   7152:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7153:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7154:     my ($tmp)=keys(%current_permissions);
                   7155:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7156:     foreach my $file (@{$files}) {
1.759     albertel 7157: 	$file = &declutter_portfile($file);
1.561     banghart 7158:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7159:     }
1.613     albertel 7160:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7161:     return;
                   7162: }
                   7163: 
1.572     banghart 7164: # ------------------------------------------------------------Save Selected Files
                   7165: 
                   7166: sub save_selected_files {
                   7167:     my ($user, $path, @files) = @_;
                   7168:     my $filename = $user."savedfiles";
1.573     banghart 7169:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7170:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7171:     foreach my $file (@files) {
1.620     albertel 7172:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7173:     }
                   7174:     foreach my $file (@other_files) {
1.574     banghart 7175:         print (OUT $file."\n");
1.572     banghart 7176:     }
1.574     banghart 7177:     close (OUT);
1.572     banghart 7178:     return 'ok';
                   7179: }
                   7180: 
1.574     banghart 7181: sub clear_selected_files {
                   7182:     my ($user) = @_;
                   7183:     my $filename = $user."savedfiles";
                   7184:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7185:     print (OUT undef);
                   7186:     close (OUT);
                   7187:     return ("ok");    
                   7188: }
                   7189: 
1.572     banghart 7190: sub files_in_path {
                   7191:     my ($user, $path) = @_;
                   7192:     my $filename = $user."savedfiles";
                   7193:     my %return_files;
1.574     banghart 7194:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7195:     while (my $line_in = <IN>) {
1.574     banghart 7196:         chomp ($line_in);
                   7197:         my @paths_and_file = split (m!/!, $line_in);
                   7198:         my $file_part = pop (@paths_and_file);
                   7199:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7200:         $path_part.='/';
                   7201:         my $path_and_file = $path_part.$file_part;
                   7202:         if ($path_part eq $path) {
                   7203:             $return_files{$file_part}= 'selected';
                   7204:         }
                   7205:     }
1.574     banghart 7206:     close (IN);
                   7207:     return (\%return_files);
1.572     banghart 7208: }
                   7209: 
                   7210: # called in portfolio select mode, to show files selected NOT in current directory
                   7211: sub files_not_in_path {
                   7212:     my ($user, $path) = @_;
                   7213:     my $filename = $user."savedfiles";
                   7214:     my @return_files;
                   7215:     my $path_part;
1.800     albertel 7216:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7217:     while (my $line = <IN>) {
1.572     banghart 7218:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7219:         my @paths_and_file = split(m|/|, $line);
                   7220:         my $file_part = pop(@paths_and_file);
                   7221:         chomp($file_part);
                   7222:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7223:         $path_part .= '/';
                   7224:         my $path_and_file = $path_part.$file_part;
                   7225:         if ($path_part ne $path) {
1.800     albertel 7226:             push(@return_files, ($path_and_file));
1.572     banghart 7227:         }
                   7228:     }
1.800     albertel 7229:     close(OUT);
1.574     banghart 7230:     return (@return_files);
1.572     banghart 7231: }
                   7232: 
1.745     raeburn  7233: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7234: 
1.745     raeburn  7235: sub get_portfile_permissions {
                   7236:     my ($domain,$user) = @_;
1.613     albertel 7237:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7238:     my ($tmp)=keys(%current_permissions);
                   7239:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7240:     return \%current_permissions;
                   7241: }
                   7242: 
                   7243: #---------------------------------------------Get portfolio file access controls
                   7244: 
1.749     raeburn  7245: sub get_access_controls {
1.745     raeburn  7246:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7247:     my %access;
                   7248:     my $real_file = $file;
                   7249:     $file =~ s/\.meta$//;
1.745     raeburn  7250:     if (defined($file)) {
1.749     raeburn  7251:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7252:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7253:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7254:             }
                   7255:         }
1.745     raeburn  7256:     } else {
1.749     raeburn  7257:         foreach my $key (keys(%{$current_permissions})) {
                   7258:             if ($key =~ /\0accesscontrol$/) {
                   7259:                 if (defined($group)) {
                   7260:                     if ($key !~ m-^\Q$group\E/-) {
                   7261:                         next;
                   7262:                     }
                   7263:                 }
                   7264:                 my ($fullpath) = split(/\0/,$key);
                   7265:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7266:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7267:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7268:                     }
                   7269:                 }
                   7270:             }
                   7271:         }
                   7272:     }
                   7273:     return %access;
                   7274: }
                   7275: 
                   7276: sub modify_access_controls {
                   7277:     my ($file_name,$changes,$domain,$user)=@_;
                   7278:     my ($outcome,$deloutcome);
                   7279:     my %store_permissions;
                   7280:     my %new_values;
                   7281:     my %new_control;
                   7282:     my %translation;
                   7283:     my @deletions = ();
                   7284:     my $now = time;
                   7285:     if (exists($$changes{'activate'})) {
                   7286:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7287:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7288:             my $numnew = scalar(@newitems);
                   7289:             for (my $i=0; $i<$numnew; $i++) {
                   7290:                 my $newkey = $newitems[$i];
                   7291:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7292:                 if ($newkey =~ /^\d+:/) { 
                   7293:                     $newkey =~ s/^(\d+)/$newid/;
                   7294:                     $translation{$1} = $newid;
                   7295:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7296:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7297:                     $translation{$1} = $newid;
                   7298:                 }
1.749     raeburn  7299:                 $new_values{$file_name."\0".$newkey} = 
                   7300:                                           $$changes{'activate'}{$newitems[$i]};
                   7301:                 $new_control{$newkey} = $now;
                   7302:             }
                   7303:         }
                   7304:     }
                   7305:     my %todelete;
                   7306:     my %changed_items;
                   7307:     foreach my $action ('delete','update') {
                   7308:         if (exists($$changes{$action})) {
                   7309:             if (ref($$changes{$action}) eq 'HASH') {
                   7310:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7311:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7312:                     if ($action eq 'delete') { 
                   7313:                         $todelete{$itemnum} = 1;
                   7314:                     } else {
                   7315:                         $changed_items{$itemnum} = $key;
                   7316:                     }
                   7317:                 }
1.745     raeburn  7318:             }
                   7319:         }
1.749     raeburn  7320:     }
                   7321:     # get lock on access controls for file.
                   7322:     my $lockhash = {
                   7323:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7324:                                                        ':'.$env{'user.domain'},
                   7325:                    }; 
                   7326:     my $tries = 0;
                   7327:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7328:    
                   7329:     while (($gotlock ne 'ok') && $tries <3) {
                   7330:         $tries ++;
                   7331:         sleep 1;
                   7332:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7333:     }
                   7334:     if ($gotlock eq 'ok') {
                   7335:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7336:         my ($tmp)=keys(%curr_permissions);
                   7337:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7338:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7339:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7340:             if (ref($curr_controls) eq 'HASH') {
                   7341:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7342:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7343:                     if (defined($todelete{$itemnum})) {
                   7344:                         push(@deletions,$file_name."\0".$control_item);
                   7345:                     } else {
                   7346:                         if (defined($changed_items{$itemnum})) {
                   7347:                             $new_control{$changed_items{$itemnum}} = $now;
                   7348:                             push(@deletions,$file_name."\0".$control_item);
                   7349:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7350:                         } else {
                   7351:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7352:                         }
                   7353:                     }
1.745     raeburn  7354:                 }
                   7355:             }
                   7356:         }
1.970     raeburn  7357:         my ($group);
                   7358:         if (&is_course($domain,$user)) {
                   7359:             ($group,my $file) = split(/\//,$file_name,2);
                   7360:         }
1.749     raeburn  7361:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7362:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7363:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7364:         #  remove lock
                   7365:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7366:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7367:         my $sqlresult =
1.970     raeburn  7368:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7369:                                     $group);
1.749     raeburn  7370:     } else {
                   7371:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7372:     }
1.749     raeburn  7373:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7374: }
                   7375: 
1.827     raeburn  7376: sub make_public_indefinitely {
                   7377:     my ($requrl) = @_;
                   7378:     my $now = time;
                   7379:     my $action = 'activate';
                   7380:     my $aclnum = 0;
                   7381:     if (&is_portfolio_url($requrl)) {
                   7382:         my (undef,$udom,$unum,$file_name,$group) =
                   7383:             &parse_portfolio_url($requrl);
                   7384:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7385:         my %access_controls = &get_access_controls($current_perms,
                   7386:                                                    $group,$file_name);
                   7387:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7388:             my ($num,$scope,$end,$start) = 
                   7389:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7390:             if ($scope eq 'public') {
                   7391:                 if ($start <= $now && $end == 0) {
                   7392:                     $action = 'none';
                   7393:                 } else {
                   7394:                     $action = 'update';
                   7395:                     $aclnum = $num;
                   7396:                 }
                   7397:                 last;
                   7398:             }
                   7399:         }
                   7400:         if ($action eq 'none') {
                   7401:              return 'ok';
                   7402:         } else {
                   7403:             my %changes;
                   7404:             my $newend = 0;
                   7405:             my $newstart = $now;
                   7406:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7407:             $changes{$action}{$newkey} = {
                   7408:                 type => 'public',
                   7409:                 time => {
                   7410:                     start => $newstart,
                   7411:                     end   => $newend,
                   7412:                 },
                   7413:             };
                   7414:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7415:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7416:             return $outcome;
                   7417:         }
                   7418:     } else {
                   7419:         return 'invalid';
                   7420:     }
                   7421: }
                   7422: 
1.745     raeburn  7423: #------------------------------------------------------Get Marked as Read Only
                   7424: 
                   7425: sub get_marked_as_readonly {
                   7426:     my ($domain,$user,$what,$group) = @_;
                   7427:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7428:     my @readonly_files;
1.629     banghart 7429:     my $cmp1=$what;
                   7430:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7431:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7432:         if (defined($group)) {
                   7433:             if ($file_name !~ m-^\Q$group\E/-) {
                   7434:                 next;
                   7435:             }
                   7436:         }
1.561     banghart 7437:         if (ref($value) eq "ARRAY"){
                   7438:             foreach my $stored_what (@{$value}) {
1.629     banghart 7439:                 my $cmp2=$stored_what;
1.759     albertel 7440:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7441:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7442:                 }
1.629     banghart 7443:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7444:                     push(@readonly_files, $file_name);
1.745     raeburn  7445:                     last;
1.563     banghart 7446:                 } elsif (!defined($what)) {
                   7447:                     push(@readonly_files, $file_name);
1.745     raeburn  7448:                     last;
1.561     banghart 7449:                 }
                   7450:             }
1.745     raeburn  7451:         }
1.561     banghart 7452:     }
                   7453:     return @readonly_files;
                   7454: }
1.577     banghart 7455: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7456: 
1.577     banghart 7457: sub get_marked_as_readonly_hash {
1.745     raeburn  7458:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7459:     my %readonly_files;
1.745     raeburn  7460:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7461:         if (defined($group)) {
                   7462:             if ($file_name !~ m-^\Q$group\E/-) {
                   7463:                 next;
                   7464:             }
                   7465:         }
1.577     banghart 7466:         if (ref($value) eq "ARRAY"){
                   7467:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7468:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7469:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7470:                         if ($lock_descriptor eq 'graded') {
                   7471:                             $readonly_files{$file_name} = 'graded';
                   7472:                         } elsif ($lock_descriptor eq 'handback') {
                   7473:                             $readonly_files{$file_name} = 'handback';
                   7474:                         } else {
                   7475:                             if (!exists($readonly_files{$file_name})) {
                   7476:                                 $readonly_files{$file_name} = 'locked';
                   7477:                             }
                   7478:                         }
1.745     raeburn  7479:                     }
1.750     banghart 7480:                 } 
1.577     banghart 7481:             }
                   7482:         } 
                   7483:     }
                   7484:     return %readonly_files;
                   7485: }
1.559     banghart 7486: # ------------------------------------------------------------ Unmark as Read Only
                   7487: 
                   7488: sub unmark_as_readonly {
1.629     banghart 7489:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7490:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7491:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7492:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7493:     my $symb_crs = $what;
                   7494:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7495:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7496:     my ($tmp)=keys(%current_permissions);
                   7497:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7498:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7499:     foreach my $file (@readonly_files) {
1.759     albertel 7500: 	my $clean_file = &declutter_portfile($file);
                   7501: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7502: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7503:         my @new_locks;
                   7504:         my @del_keys;
                   7505:         if (ref($current_locks) eq "ARRAY"){
                   7506:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7507:                 my $compare=$locker;
1.749     raeburn  7508:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7509:                     $compare=join('',@{$locker});
1.746     raeburn  7510:                     if ($compare ne $symb_crs) {
                   7511:                         push(@new_locks, $locker);
                   7512:                     }
1.563     banghart 7513:                 }
                   7514:             }
1.650     albertel 7515:             if (scalar(@new_locks) > 0) {
1.563     banghart 7516:                 $current_permissions{$file} = \@new_locks;
                   7517:             } else {
                   7518:                 push(@del_keys, $file);
1.613     albertel 7519:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7520:                 delete($current_permissions{$file});
1.563     banghart 7521:             }
                   7522:         }
1.561     banghart 7523:     }
1.613     albertel 7524:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7525:     return;
                   7526: }
1.512     banghart 7527: 
1.17      www      7528: # ------------------------------------------------------------ Directory lister
                   7529: 
                   7530: sub dirlist {
1.955     raeburn  7531:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7532:     $uri=~s/^\///;
                   7533:     $uri=~s/\/$//;
1.253     stredwic 7534:     my ($udom, $uname);
1.955     raeburn  7535:     if ($getuserdir) {
1.253     stredwic 7536:         $udom = $userdomain;
                   7537:         $uname = $username;
1.955     raeburn  7538:     } else {
                   7539:         (undef,$udom,$uname)=split(/\//,$uri);
                   7540:         if(defined($userdomain)) {
                   7541:             $udom = $userdomain;
                   7542:         }
                   7543:         if(defined($username)) {
                   7544:             $uname = $username;
                   7545:         }
1.253     stredwic 7546:     }
1.955     raeburn  7547:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7548: 
1.955     raeburn  7549:     $dirRoot = $perlvar{'lonDocRoot'};
                   7550:     if (defined($getpropath)) {
                   7551:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7552:         $dirRoot =~ s/\/$//;
1.955     raeburn  7553:     } elsif (defined($getuserdir)) {
                   7554:         my $subdir=$uname.'__';
                   7555:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7556:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7557:                    ."/$udom/$subdir/$uname";
                   7558:     } elsif (defined($alternateRoot)) {
                   7559:         $dirRoot = $alternateRoot;
1.751     banghart 7560:     }
1.253     stredwic 7561: 
                   7562:     if($udom) {
                   7563:         if($uname) {
1.955     raeburn  7564:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7565:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7566:                               .':'.&escape($uname).':'.&escape($udom),
                   7567:                               &homeserver($uname,$udom));
                   7568:             if ($listing eq 'unknown_cmd') {
                   7569:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7570:                                   &homeserver($uname,$udom));
                   7571:             } else {
                   7572:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7573:             }
1.605     matthew  7574:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7575:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7576: 				  &homeserver($uname,$udom));
1.605     matthew  7577:                 @listing_results = split(/:/,$listing);
                   7578:             } else {
                   7579:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7580:             }
                   7581:             return @listing_results;
1.955     raeburn  7582:         } elsif(!$alternateRoot) {
1.800     albertel 7583:             my %allusers;
1.841     albertel 7584: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7585:  	    foreach my $tryserver (keys(%servers)) {
                   7586:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7587:                                   &escape($udom),$tryserver);
                   7588:                 if ($listing eq 'unknown_cmd') {
                   7589: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7590: 				      $udom, $tryserver);
                   7591:                 } else {
                   7592:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7593:                 }
1.841     albertel 7594: 		if ($listing eq 'unknown_cmd') {
                   7595: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7596: 				      $udom, $tryserver);
                   7597: 		    @listing_results = split(/:/,$listing);
                   7598: 		} else {
                   7599: 		    @listing_results =
                   7600: 			map { &unescape($_); } split(/:/,$listing);
                   7601: 		}
                   7602: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7603: 		    $listing_results[0] ne 'empty'       &&
                   7604: 		    $listing_results[0] ne 'con_lost') {
                   7605: 		    foreach my $line (@listing_results) {
                   7606: 			my ($entry) = split(/&/,$line,2);
                   7607: 			$allusers{$entry} = 1;
                   7608: 		    }
                   7609: 		}
1.253     stredwic 7610:             }
                   7611:             my $alluserstr='';
1.800     albertel 7612:             foreach my $user (sort(keys(%allusers))) {
                   7613:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7614:             }
                   7615:             $alluserstr=~s/:$//;
                   7616:             return split(/:/,$alluserstr);
                   7617:         } else {
1.800     albertel 7618:             return ('missing user name');
1.253     stredwic 7619:         }
1.955     raeburn  7620:     } elsif(!defined($getpropath)) {
1.841     albertel 7621:         my @all_domains = sort(&all_domains());
1.955     raeburn  7622:         foreach my $domain (@all_domains) {
                   7623:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7624:         }
                   7625:         return @all_domains;
                   7626:     } else {
1.800     albertel 7627:         return ('missing domain');
1.275     stredwic 7628:     }
                   7629: }
                   7630: 
                   7631: # --------------------------------------------- GetFileTimestamp
                   7632: # This function utilizes dirlist and returns the date stamp for
                   7633: # when it was last modified.  It will also return an error of -1
                   7634: # if an error occurs
                   7635: 
                   7636: sub GetFileTimestamp {
1.955     raeburn  7637:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7638:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7639:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7640:     my ($fileStat) = 
                   7641:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7642:                                  undef,$getuserdir);
1.275     stredwic 7643:     my @stats = split('&', $fileStat);
                   7644:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7645:         # @stats contains first the filename, then the stat output
                   7646:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7647:     } else {
                   7648:         return -1;
1.253     stredwic 7649:     }
1.26      www      7650: }
                   7651: 
1.712     albertel 7652: sub stat_file {
                   7653:     my ($uri) = @_;
1.787     albertel 7654:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7655: 
1.955     raeburn  7656:     my ($udom,$uname,$file);
1.712     albertel 7657:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7658: 	($udom,$uname,$file) =
1.811     albertel 7659: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7660: 	$file = 'userfiles/'.$file;
                   7661:     }
                   7662:     if ($uri =~ m-^/res/-) {
                   7663: 	($udom,$uname) = 
1.807     albertel 7664: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7665: 	$file = $uri;
                   7666:     }
                   7667: 
                   7668:     if (!$udom || !$uname || !$file) {
                   7669: 	# unable to handle the uri
                   7670: 	return ();
                   7671:     }
1.956     raeburn  7672:     my $getpropath;
                   7673:     if ($file =~ /^userfiles\//) {
                   7674:         $getpropath = 1;
                   7675:     }
1.955     raeburn  7676:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7677:     my @stats = split('&', $result);
1.721     banghart 7678:     
1.712     albertel 7679:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7680: 	shift(@stats); #filename is first
                   7681: 	return @stats;
                   7682:     }
                   7683:     return ();
                   7684: }
                   7685: 
1.26      www      7686: # -------------------------------------------------------- Value of a Condition
                   7687: 
1.713     albertel 7688: # gets the value of a specific preevaluated condition
                   7689: #    stored in the string  $env{user.state.<cid>}
                   7690: # or looks up a condition reference in the bighash and if if hasn't
                   7691: # already been evaluated recurses into docondval to get the value of
                   7692: # the condition, then memoizing it to 
                   7693: #   $env{user.state.<cid>.<condition>}
1.40      www      7694: sub directcondval {
                   7695:     my $number=shift;
1.620     albertel 7696:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7697: 	&Apache::lonuserstate::evalstate();
                   7698:     }
1.713     albertel 7699:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7700: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7701:     } elsif ($number =~ /^_/) {
                   7702: 	my $sub_condition;
                   7703: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7704: 		&GDBM_READER(),0640)) {
                   7705: 	    $sub_condition=$bighash{'conditions'.$number};
                   7706: 	    untie(%bighash);
                   7707: 	}
                   7708: 	my $value = &docondval($sub_condition);
1.949     raeburn  7709: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7710: 	return $value;
                   7711:     }
1.620     albertel 7712:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7713:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7714:     } else {
                   7715:        return 2;
                   7716:     }
                   7717: }
                   7718: 
1.713     albertel 7719: # get the collection of conditions for this resource
1.26      www      7720: sub condval {
                   7721:     my $condidx=shift;
1.54      www      7722:     my $allpathcond='';
1.713     albertel 7723:     foreach my $cond (split(/\|/,$condidx)) {
                   7724: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7725: 	    $allpathcond.=
                   7726: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7727: 	}
1.191     harris41 7728:     }
1.54      www      7729:     $allpathcond=~s/\|$//;
1.713     albertel 7730:     return &docondval($allpathcond);
                   7731: }
                   7732: 
                   7733: #evaluates an expression of conditions
                   7734: sub docondval {
                   7735:     my ($allpathcond) = @_;
                   7736:     my $result=0;
                   7737:     if ($env{'request.course.id'}
                   7738: 	&& defined($allpathcond)) {
                   7739: 	my $operand='|';
                   7740: 	my @stack;
                   7741: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7742: 	    if ($chunk eq '(') {
                   7743: 		push @stack,($operand,$result);
                   7744: 	    } elsif ($chunk eq ')') {
                   7745: 		my $before=pop @stack;
                   7746: 		if (pop @stack eq '&') {
                   7747: 		    $result=$result>$before?$before:$result;
                   7748: 		} else {
                   7749: 		    $result=$result>$before?$result:$before;
                   7750: 		}
                   7751: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7752: 		$operand=$chunk;
                   7753: 	    } else {
                   7754: 		my $new=directcondval($chunk);
                   7755: 		if ($operand eq '&') {
                   7756: 		    $result=$result>$new?$new:$result;
                   7757: 		} else {
                   7758: 		    $result=$result>$new?$result:$new;
                   7759: 		}
                   7760: 	    }
                   7761: 	}
1.26      www      7762:     }
                   7763:     return $result;
1.421     albertel 7764: }
                   7765: 
                   7766: # ---------------------------------------------------- Devalidate courseresdata
                   7767: 
                   7768: sub devalidatecourseresdata {
                   7769:     my ($coursenum,$coursedomain)=@_;
                   7770:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7771:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7772: }
                   7773: 
1.763     www      7774: 
1.200     www      7775: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7776: #
                   7777: #  Parameters:
                   7778: #      $coursenum    - Number of the course.
                   7779: #      $coursedomain - Domain at which the course was created.
                   7780: #  Returns:
                   7781: #     A hash of the course parameters along (I think) with timestamps
                   7782: #     and version info.
1.877     foxr     7783: 
1.624     albertel 7784: sub get_courseresdata {
                   7785:     my ($coursenum,$coursedomain)=@_;
1.200     www      7786:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7787:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7788:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7789:     my %dumpreply;
1.417     albertel 7790:     unless (defined($cached)) {
1.624     albertel 7791: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7792: 	$result=\%dumpreply;
1.251     albertel 7793: 	my ($tmp) = keys(%dumpreply);
                   7794: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7795: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7796: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7797: 	    return $tmp;
1.416     albertel 7798: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7799: 	    $result=undef;
1.599     albertel 7800: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7801: 	}
                   7802:     }
1.624     albertel 7803:     return $result;
                   7804: }
                   7805: 
1.633     albertel 7806: sub devalidateuserresdata {
                   7807:     my ($uname,$udom)=@_;
                   7808:     my $hashid="$udom:$uname";
                   7809:     &devalidate_cache_new('userres',$hashid);
                   7810: }
                   7811: 
1.624     albertel 7812: sub get_userresdata {
                   7813:     my ($uname,$udom)=@_;
                   7814:     #most student don\'t have any data set, check if there is some data
                   7815:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7816: 
                   7817:     my $hashid="$udom:$uname";
                   7818:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7819:     if (!defined($cached)) {
                   7820: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7821: 	$result=\%resourcedata;
                   7822: 	&do_cache_new('userres',$hashid,$result,600);
                   7823:     }
                   7824:     my ($tmp)=keys(%$result);
                   7825:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7826: 	return $result;
                   7827:     }
                   7828:     #error 2 occurs when the .db doesn't exist
                   7829:     if ($tmp!~/error: 2 /) {
1.672     albertel 7830: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7831: 		 " Trying to get resource data for ".
                   7832: 		 $uname." at ".$udom.": ".
                   7833: 		 $tmp."</font>");
                   7834:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7835: 	#&EXT_cache_set($udom,$uname);
                   7836: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7837: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7838:     }
                   7839:     return $tmp;
                   7840: }
1.879     foxr     7841: #----------------------------------------------- resdata - return resource data
                   7842: #  Purpose:
                   7843: #    Return resource data for either users or for a course.
                   7844: #  Parameters:
                   7845: #     $name      - Course/user name.
                   7846: #     $domain    - Name of the domain the user/course is registered on.
                   7847: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7848: #     @which     - Array of names of resources desired.
                   7849: #  Returns:
                   7850: #     The value of the first reasource in @which that is found in the
                   7851: #     resource hash.
                   7852: #  Exceptional Conditions:
                   7853: #     If the $type passed in is not valid (not the string 'course' or 
                   7854: #     'user', an undefined  reference is returned.
                   7855: #     If none of the resources are found, an undef is returned
1.624     albertel 7856: sub resdata {
                   7857:     my ($name,$domain,$type,@which)=@_;
                   7858:     my $result;
                   7859:     if ($type eq 'course') {
                   7860: 	$result=&get_courseresdata($name,$domain);
                   7861:     } elsif ($type eq 'user') {
                   7862: 	$result=&get_userresdata($name,$domain);
                   7863:     }
                   7864:     if (!ref($result)) { return $result; }    
1.251     albertel 7865:     foreach my $item (@which) {
1.927     albertel 7866: 	if (defined($result->{$item->[0]})) {
                   7867: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7868: 	}
1.250     albertel 7869:     }
1.291     albertel 7870:     return undef;
1.200     www      7871: }
                   7872: 
1.379     matthew  7873: #
                   7874: # EXT resource caching routines
                   7875: #
                   7876: 
                   7877: sub clear_EXT_cache_status {
1.383     albertel 7878:     &delenv('cache.EXT.');
1.379     matthew  7879: }
                   7880: 
                   7881: sub EXT_cache_status {
                   7882:     my ($target_domain,$target_user) = @_;
1.383     albertel 7883:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7884:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7885:         # We know already the user has no data
                   7886:         return 1;
                   7887:     } else {
                   7888:         return 0;
                   7889:     }
                   7890: }
                   7891: 
                   7892: sub EXT_cache_set {
                   7893:     my ($target_domain,$target_user) = @_;
1.383     albertel 7894:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7895:     #&appenv({$cachename => time});
1.379     matthew  7896: }
                   7897: 
1.28      www      7898: # --------------------------------------------------------- Value of a Variable
1.58      www      7899: sub EXT {
1.715     albertel 7900: 
1.395     albertel 7901:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7902:     unless ($varname) { return ''; }
1.218     albertel 7903:     #get real user name/domain, courseid and symb
                   7904:     my $courseid;
1.359     albertel 7905:     my $publicuser;
1.427     www      7906:     if ($symbparm) {
                   7907: 	$symbparm=&get_symb_from_alias($symbparm);
                   7908:     }
1.218     albertel 7909:     if (!($uname && $udom)) {
1.790     albertel 7910:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7911:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7912:     } else {
1.620     albertel 7913: 	$courseid=$env{'request.course.id'};
1.218     albertel 7914:     }
1.48      www      7915:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7916:     my $rest;
1.320     albertel 7917:     if (defined($therest[0])) {
1.48      www      7918:        $rest=join('.',@therest);
                   7919:     } else {
                   7920:        $rest='';
                   7921:     }
1.320     albertel 7922: 
1.57      www      7923:     my $qualifierrest=$qualifier;
                   7924:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7925:     my $spacequalifierrest=$space;
                   7926:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7927:     if ($realm eq 'user') {
1.48      www      7928: # --------------------------------------------------------------- user.resource
                   7929: 	if ($space eq 'resource') {
1.651     albertel 7930: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7931: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7932: 		 &&
1.744     albertel 7933: 		 ($symbparm eq &symbread()) ) {	
                   7934: 		# if we are in the middle of processing the resource the
                   7935: 		# get the value we are planning on committing
                   7936:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7937:                     return $Apache::lonhomework::results{$qualifierrest};
                   7938:                 } else {
                   7939:                     return $Apache::lonhomework::history{$qualifierrest};
                   7940:                 }
1.335     albertel 7941: 	    } else {
1.359     albertel 7942: 		my %restored;
1.620     albertel 7943: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7944: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7945: 		} else {
                   7946: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7947: 		}
1.335     albertel 7948: 		return $restored{$qualifierrest};
                   7949: 	    }
1.48      www      7950: # ----------------------------------------------------------------- user.access
                   7951:         } elsif ($space eq 'access') {
1.218     albertel 7952: 	    # FIXME - not supporting calls for a specific user
1.48      www      7953:             return &allowed($qualifier,$rest);
                   7954: # ------------------------------------------ user.preferences, user.environment
                   7955:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7956: 	    if (($uname eq $env{'user.name'}) &&
                   7957: 		($udom eq $env{'user.domain'})) {
                   7958: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7959: 	    } else {
1.359     albertel 7960: 		my %returnhash;
                   7961: 		if (!$publicuser) {
                   7962: 		    %returnhash=&userenvironment($udom,$uname,
                   7963: 						 $qualifierrest);
                   7964: 		}
1.218     albertel 7965: 		return $returnhash{$qualifierrest};
                   7966: 	    }
1.48      www      7967: # ----------------------------------------------------------------- user.course
                   7968:         } elsif ($space eq 'course') {
1.218     albertel 7969: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7970:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7971: # ------------------------------------------------------------------- user.role
                   7972:         } elsif ($space eq 'role') {
1.218     albertel 7973: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7974:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7975:             if ($qualifier eq 'value') {
                   7976: 		return $role;
                   7977:             } elsif ($qualifier eq 'extent') {
                   7978:                 return $where;
                   7979:             }
                   7980: # ----------------------------------------------------------------- user.domain
                   7981:         } elsif ($space eq 'domain') {
1.218     albertel 7982:             return $udom;
1.48      www      7983: # ------------------------------------------------------------------- user.name
                   7984:         } elsif ($space eq 'name') {
1.218     albertel 7985:             return $uname;
1.48      www      7986: # ---------------------------------------------------- Any other user namespace
1.29      www      7987:         } else {
1.359     albertel 7988: 	    my %reply;
                   7989: 	    if (!$publicuser) {
                   7990: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7991: 	    }
                   7992: 	    return $reply{$qualifierrest};
1.48      www      7993:         }
1.236     www      7994:     } elsif ($realm eq 'query') {
                   7995: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7996:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7997: 						[$spacequalifierrest]);
1.620     albertel 7998: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7999:    } elsif ($realm eq 'request') {
1.48      www      8000: # ------------------------------------------------------------- request.browser
                   8001:         if ($space eq 'browser') {
1.430     www      8002: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8003: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8004: 		    return 1;
                   8005: 		} else {
                   8006: 		    return 0;
                   8007: 		}
                   8008: 	    } else {
1.620     albertel 8009: 		return $env{'browser.'.$qualifier};
1.430     www      8010: 	    }
1.57      www      8011: # ------------------------------------------------------------ request.filename
                   8012:         } else {
1.620     albertel 8013:             return $env{'request.'.$spacequalifierrest};
1.29      www      8014:         }
1.28      www      8015:     } elsif ($realm eq 'course') {
1.48      www      8016: # ---------------------------------------------------------- course.description
1.620     albertel 8017:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8018:     } elsif ($realm eq 'resource') {
1.165     www      8019: 
1.620     albertel 8020: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8021: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8022: 	}
1.693     albertel 8023: 
                   8024: 	if ($space eq 'title') {
                   8025: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8026: 	    return &gettitle($symbparm);
                   8027: 	}
                   8028: 	
                   8029: 	if ($space eq 'map') {
                   8030: 	    my ($map) = &decode_symb($symbparm);
                   8031: 	    return &symbread($map);
                   8032: 	}
1.905     albertel 8033: 	if ($space eq 'filename') {
                   8034: 	    if ($symbparm) {
                   8035: 		return &clutter((&decode_symb($symbparm))[2]);
                   8036: 	    }
                   8037: 	    return &hreflocation('',$env{'request.filename'});
                   8038: 	}
1.693     albertel 8039: 
                   8040: 	my ($section, $group, @groups);
1.593     albertel 8041: 	my ($courselevelm,$courselevel);
1.539     albertel 8042: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8043: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8044: 
1.218     albertel 8045: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8046: 
1.60      www      8047: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8048: 	    my $symbp=$symbparm;
1.735     albertel 8049: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8050: 
                   8051: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8052: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8053: 
1.620     albertel 8054: 	    if (($env{'user.name'} eq $uname) &&
                   8055: 		($env{'user.domain'} eq $udom)) {
                   8056: 		$section=$env{'request.course.sec'};
1.733     raeburn  8057:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8058:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8059: 	    } else {
1.539     albertel 8060: 		if (! defined($usection)) {
1.551     albertel 8061: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8062: 		} else {
                   8063: 		    $section = $usection;
                   8064: 		}
1.733     raeburn  8065:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8066: 	    }
                   8067: 
                   8068: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8069: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8070: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8071: 
1.593     albertel 8072: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8073: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8074: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8075: 
1.60      www      8076: # ----------------------------------------------------------- first, check user
1.624     albertel 8077: 
                   8078: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8079: 				       ([$courselevelr,'resource'],
                   8080: 					[$courselevelm,'map'     ],
                   8081: 					[$courselevel, 'course'  ]));
1.931     albertel 8082: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8083: 
1.594     albertel 8084: # ------------------------------------------------ second, check some of course
1.684     raeburn  8085:             my $coursereply;
1.691     raeburn  8086:             if (@groups > 0) {
                   8087:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8088:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8089:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8090:             }
1.96      www      8091: 
1.684     raeburn  8092: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8093: 				  $env{'course.'.$courseid.'.domain'},
                   8094: 				  'course',
                   8095: 				  ([$seclevelr,   'resource'],
                   8096: 				   [$seclevelm,   'map'     ],
                   8097: 				   [$seclevel,    'course'  ],
                   8098: 				   [$courselevelr,'resource']));
                   8099: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8100: 
1.60      www      8101: # ------------------------------------------------------ third, check map parms
1.218     albertel 8102: 	    my %parmhash=();
                   8103: 	    my $thisparm='';
                   8104: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8105: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8106: 		    &GDBM_READER(),0640)) {
1.218     albertel 8107: 		$thisparm=$parmhash{$symbparm};
                   8108: 		untie(%parmhash);
                   8109: 	    }
1.927     albertel 8110: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8111: 	}
1.594     albertel 8112: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8113: 
1.218     albertel 8114: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8115: 	my $filename;
                   8116: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8117: 	if ($symbparm) {
1.409     www      8118: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8119: 	} else {
1.620     albertel 8120: 	    $filename=$env{'request.filename'};
1.282     albertel 8121: 	}
                   8122: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8123: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8124: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8125: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8126: 
1.927     albertel 8127: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8128: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8129: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8130: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8131: 				     $env{'course.'.$courseid.'.domain'},
                   8132: 				     'course',
1.927     albertel 8133: 				     ([$courselevelm,'map'   ],
                   8134: 				      [$courselevel, 'course']));
                   8135: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8136: 	}
1.145     www      8137: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8138: 	unless ($space eq '0') {
1.336     albertel 8139: 	    my @parts=split(/_/,$space);
                   8140: 	    my $id=pop(@parts);
                   8141: 	    my $part=join('_',@parts);
                   8142: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8143: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8144: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8145: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8146: 	}
1.395     albertel 8147: 	if ($recurse) { return undef; }
                   8148: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8149: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8150: # ---------------------------------------------------- Any other user namespace
                   8151:     } elsif ($realm eq 'environment') {
                   8152: # ----------------------------------------------------------------- environment
1.620     albertel 8153: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8154: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8155: 	} else {
1.770     albertel 8156: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8157: 		return '';
                   8158: 	    }
1.219     albertel 8159: 	    my %returnhash=&userenvironment($udom,$uname,
                   8160: 					    $spacequalifierrest);
                   8161: 	    return $returnhash{$spacequalifierrest};
                   8162: 	}
1.28      www      8163:     } elsif ($realm eq 'system') {
1.48      www      8164: # ----------------------------------------------------------------- system.time
                   8165: 	if ($space eq 'time') {
                   8166: 	    return time;
                   8167:         }
1.696     albertel 8168:     } elsif ($realm eq 'server') {
                   8169: # ----------------------------------------------------------------- system.time
                   8170: 	if ($space eq 'name') {
                   8171: 	    return $ENV{'SERVER_NAME'};
                   8172:         }
1.28      www      8173:     }
1.48      www      8174:     return '';
1.61      www      8175: }
                   8176: 
1.927     albertel 8177: sub get_reply {
                   8178:     my ($reply_value) = @_;
1.940     raeburn  8179:     if (ref($reply_value) eq 'ARRAY') {
                   8180:         if (wantarray) {
                   8181: 	    return @$reply_value;
                   8182:         }
                   8183:         return $reply_value->[0];
                   8184:     } else {
                   8185:         return $reply_value;
1.927     albertel 8186:     }
                   8187: }
                   8188: 
1.691     raeburn  8189: sub check_group_parms {
                   8190:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8191:     my @groupitems = ();
                   8192:     my $resultitem;
1.927     albertel 8193:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8194:     foreach my $group (@{$groups}) {
                   8195:         foreach my $level (@levels) {
1.927     albertel 8196:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8197:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8198:         }
                   8199:     }
                   8200:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8201:                             $env{'course.'.$courseid.'.domain'},
                   8202:                                      'course',@groupitems);
                   8203:     return $coursereply;
                   8204: }
                   8205: 
                   8206: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8207:     my ($courseid,@groups) = @_;
                   8208:     @groups = sort(@groups);
1.691     raeburn  8209:     return @groups;
                   8210: }
                   8211: 
1.395     albertel 8212: sub packages_tab_default {
                   8213:     my ($uri,$varname)=@_;
                   8214:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8215: 
                   8216:     my (@extension,@specifics,$do_default);
                   8217:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8218: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8219: 	if ($pack_type eq 'default') {
                   8220: 	    $do_default=1;
                   8221: 	} elsif ($pack_type eq 'extension') {
                   8222: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8223: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8224: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8225: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8226: 	}
                   8227:     }
                   8228:     # first look for a package that matches the requested part id
                   8229:     foreach my $package (@specifics) {
                   8230: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8231: 	next if ($pack_part ne $part);
                   8232: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8233: 	    return $packagetab{"$pack_type&$name&default"};
                   8234: 	}
                   8235:     }
                   8236:     # look for any possible matching non extension_ package
                   8237:     foreach my $package (@specifics) {
                   8238: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8239: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8240: 	    return $packagetab{"$pack_type&$name&default"};
                   8241: 	}
1.585     albertel 8242: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8243: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8244: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8245: 	}
                   8246:     }
1.738     albertel 8247:     # look for any posible extension_ match
                   8248:     foreach my $package (@extension) {
                   8249: 	my ($package,$pack_type)=@{$package};
                   8250: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8251: 	    return $packagetab{"$pack_type&$name&default"};
                   8252: 	}
                   8253: 	if (defined($packagetab{$package."&$name&default"})) {
                   8254: 	    return $packagetab{$package."&$name&default"};
                   8255: 	}
                   8256:     }
                   8257:     # look for a global default setting
                   8258:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8259: 	return $packagetab{"default&$name&default"};
                   8260:     }
1.395     albertel 8261:     return undef;
                   8262: }
                   8263: 
1.334     albertel 8264: sub add_prefix_and_part {
                   8265:     my ($prefix,$part)=@_;
                   8266:     my $keyroot;
                   8267:     if (defined($prefix) && $prefix !~ /^__/) {
                   8268: 	# prefix that has a part already
                   8269: 	$keyroot=$prefix;
                   8270:     } elsif (defined($prefix)) {
                   8271: 	# prefix that is missing a part
                   8272: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8273:     } else {
                   8274: 	# no prefix at all
                   8275: 	if (defined($part)) { $keyroot='_'.$part; }
                   8276:     }
                   8277:     return $keyroot;
                   8278: }
                   8279: 
1.71      www      8280: # ---------------------------------------------------------------- Get metadata
                   8281: 
1.599     albertel 8282: my %metaentry;
1.1070    www      8283: my %importedpartids;
1.71      www      8284: sub metadata {
1.176     www      8285:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8286:     $uri=&declutter($uri);
1.288     albertel 8287:     # if it is a non metadata possible uri return quickly
1.529     albertel 8288:     if (($uri eq '') || 
                   8289: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8290: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8291:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8292: 	return undef;
                   8293:     }
                   8294:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8295: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8296: 	return undef;
1.288     albertel 8297:     }
1.73      www      8298:     my $filename=$uri;
                   8299:     $uri=~s/\.meta$//;
1.172     www      8300: #
                   8301: # Is the metadata already cached?
1.177     www      8302: # Look at timestamp of caching
1.172     www      8303: # Everything is cached by the main uri, libraries are never directly cached
                   8304: #
1.428     albertel 8305:     if (!defined($liburi)) {
1.599     albertel 8306: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8307: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8308:     }
                   8309:     {
1.1069    www      8310: # Imported parts would go here
1.1070    www      8311:         my %importedids=();
                   8312:         my @origfileimportpartids=();
1.1069    www      8313:         my $importedparts=0;
1.172     www      8314: #
                   8315: # Is this a recursive call for a library?
                   8316: #
1.599     albertel 8317: #	if (! exists($metacache{$uri})) {
                   8318: #	    $metacache{$uri}={};
                   8319: #	}
1.924     albertel 8320: 	my $cachetime = 60*60;
1.171     www      8321:         if ($liburi) {
                   8322: 	    $liburi=&declutter($liburi);
                   8323:             $filename=$liburi;
1.401     bowersj2 8324:         } else {
1.599     albertel 8325: 	    &devalidate_cache_new('meta',$uri);
                   8326: 	    undef(%metaentry);
1.401     bowersj2 8327: 	}
1.140     www      8328:         my %metathesekeys=();
1.73      www      8329:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8330: 	my $metastring;
1.924     albertel 8331: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8332: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8333: 	    $metastring = 
1.929     albertel 8334: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8335: 					  ('grade_target' => 'meta'));
                   8336: 	    $cachetime = 1; # only want this cached in the child not long term
                   8337: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8338: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8339: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8340: 	    $metastring=&getfile($file);
1.489     albertel 8341: 	}
1.208     albertel 8342:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8343:         my $token;
1.140     www      8344:         undef %metathesekeys;
1.71      www      8345:         while ($token=$parser->get_token) {
1.339     albertel 8346: 	    if ($token->[0] eq 'S') {
                   8347: 		if (defined($token->[2]->{'package'})) {
1.172     www      8348: #
                   8349: # This is a package - get package info
                   8350: #
1.339     albertel 8351: 		    my $package=$token->[2]->{'package'};
                   8352: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8353: 		    if (defined($token->[2]->{'id'})) { 
                   8354: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8355: 		    }
1.599     albertel 8356: 		    if ($metaentry{':packages'}) {
                   8357: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8358: 		    } else {
1.599     albertel 8359: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8360: 		    }
1.736     albertel 8361: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8362: 			my $part=$keyroot;
                   8363: 			$part=~s/^\_//;
1.736     albertel 8364: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8365: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8366: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8367: 			    # ignore package.tab specified default values
                   8368:                             # here &package_tab_default() will fetch those
                   8369: 			    if ($subp eq 'default') { next; }
1.736     albertel 8370: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8371: 			    my $unikey;
                   8372: 			    if ($pack =~ /_0$/) {
                   8373: 				$unikey='parameter_0_'.$name;
                   8374: 				$part=0;
                   8375: 			    } else {
                   8376: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8377: 			    }
1.339     albertel 8378: 			    if ($subp eq 'display') {
                   8379: 				$value.=' [Part: '.$part.']';
                   8380: 			    }
1.599     albertel 8381: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8382: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8383: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8384: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8385: 			    }
1.599     albertel 8386: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8387: 				$metaentry{':'.$unikey}=
                   8388: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8389: 			    }
1.339     albertel 8390: 			}
                   8391: 		    }
                   8392: 		} else {
1.172     www      8393: #
                   8394: # This is not a package - some other kind of start tag
1.339     albertel 8395: #
                   8396: 		    my $entry=$token->[1];
1.1068    www      8397: 		    my $unikey='';
1.175     www      8398: 
1.339     albertel 8399: 		    if ($entry eq 'import') {
1.175     www      8400: #
                   8401: # Importing a library here
1.339     albertel 8402: #
1.1067    www      8403:                         my $location=$parser->get_text('/import');
                   8404:                         my $dir=$filename;
                   8405:                         $dir=~s|[^/]*$||;
                   8406:                         $location=&filelocation($dir,$location);
1.1069    www      8407:                        
1.1068    www      8408:                         my $importmode=$token->[2]->{'importmode'};
                   8409:                         if ($importmode eq 'problem') {
1.1069    www      8410: # Import as problem/response
1.1068    www      8411:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8412:                         } elsif ($importmode eq 'part') {
                   8413: # Import as part(s)
1.1069    www      8414:                            $importedparts=1;
                   8415: # We need to get the original file and the imported file to get the part order correct
                   8416: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8417: # Load and inspect original file
1.1070    www      8418:                            if ($#origfileimportpartids<0) {
                   8419:                               undef(%importedpartids);
                   8420:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8421:                               my $origfile=&getfile($origfilelocation);
                   8422:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8423:                            }
                   8424: 
1.1069    www      8425: # Load and inspect imported file
                   8426:                            my $impfile=&getfile($location);
                   8427:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8428:                            if ($#impfilepartids>=0) {
                   8429: # This problem had parts
1.1070    www      8430:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8431:                            } else {
                   8432: # Importing by turning a single problem into a problem part
                   8433: # It gets the import-tags ID as part-ID
                   8434:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8435:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8436:                            }
1.1068    www      8437:                         } else {
                   8438: # Normal import
                   8439:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8440:                            if (defined($token->[2]->{'id'})) {
                   8441:                               $unikey.='_'.$token->[2]->{'id'};
                   8442:                            }
1.1067    www      8443:                         }
                   8444: 
1.339     albertel 8445: 			if ($depthcount<20) {
1.736     albertel 8446: 			    my $metadata = 
                   8447: 				&metadata($uri,'keys', $location,$unikey,
                   8448: 					  $depthcount+1);
                   8449: 			    foreach my $meta (split(',',$metadata)) {
                   8450: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8451: 				$metathesekeys{$meta}=1;
1.339     albertel 8452: 			    }
1.1068    www      8453: 			
                   8454:                         }
1.1067    www      8455: 		    } else {
                   8456: #
                   8457: # Not importing, some other kind of non-package, non-library start tag
                   8458: # 
                   8459:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8460:                         if (defined($token->[2]->{'id'})) {
                   8461:                             $unikey.='_'.$token->[2]->{'id'};
                   8462:                         }
1.339     albertel 8463: 			if (defined($token->[2]->{'name'})) { 
                   8464: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8465: 			}
                   8466: 			$metathesekeys{$unikey}=1;
1.736     albertel 8467: 			foreach my $param (@{$token->[3]}) {
                   8468: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8469: 				$token->[2]->{$param};
1.339     albertel 8470: 			}
                   8471: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8472: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8473: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8474: 		 # only ws inside the tag, and not in default, so use default
                   8475: 		 # as value
1.599     albertel 8476: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8477: 			} elsif ( $internaltext =~ /\S/ ) {
                   8478: 		  # something interesting inside the tag
                   8479: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8480: 			} else {
1.908     albertel 8481: 		  # no interesting values, don't set a default
1.339     albertel 8482: 			}
1.172     www      8483: # end of not-a-package not-a-library import
1.339     albertel 8484: 		    }
1.172     www      8485: # end of not-a-package start tag
1.339     albertel 8486: 		}
1.172     www      8487: # the next is the end of "start tag"
1.339     albertel 8488: 	    }
                   8489: 	}
1.483     albertel 8490: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8491: 	$extension = lc($extension);
                   8492: 	if ($extension eq 'htm') { $extension='html'; }
                   8493: 
1.737     albertel 8494: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8495: 	    #no specific packages #how's our extension
                   8496: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8497: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8498: 					 \%metathesekeys);
                   8499: 	}
1.883     albertel 8500: 
                   8501: 	if (!exists($metaentry{':packages'})
                   8502: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8503: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8504: 		#no specific packages well let's get default then
                   8505: 		if ($key!~/^default&/) { next; }
1.488     albertel 8506: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8507: 					     \%metathesekeys);
                   8508: 	    }
                   8509: 	}
1.338     www      8510: # are there custom rights to evaluate
1.599     albertel 8511: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8512: 
1.338     www      8513:     #
                   8514:     # Importing a rights file here
1.339     albertel 8515:     #
                   8516: 	    unless ($depthcount) {
1.599     albertel 8517: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8518: 		my $dir=$filename;
                   8519: 		$dir=~s|[^/]*$||;
                   8520: 		$location=&filelocation($dir,$location);
1.736     albertel 8521: 		my $rights_metadata =
                   8522: 		    &metadata($uri,'keys',$location,'_rights',
                   8523: 			      $depthcount+1);
                   8524: 		foreach my $rights (split(',',$rights_metadata)) {
                   8525: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8526: 		    $metathesekeys{$rights}=1;
1.339     albertel 8527: 		}
                   8528: 	    }
                   8529: 	}
1.737     albertel 8530: 	# uniqifiy package listing
                   8531: 	my %seen;
                   8532: 	my @uniq_packages =
                   8533: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8534: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8535: 
1.1070    www      8536:         if ($importedparts) {
                   8537: # We had imported parts and need to rebuild partorder
                   8538:            $metaentry{':partorder'}='';
                   8539:            $metathesekeys{'partorder'}=1;
                   8540:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8541:                if ($origfileimportpartids[$index] eq 'part') {
                   8542: # original part, part of the problem
                   8543:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8544:                } else {
                   8545: # we have imported parts at this position
                   8546:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8547:                }
                   8548:            }
                   8549:            $metaentry{':partorder'}=~s/^\,//;
                   8550:         }
                   8551: 
1.737     albertel 8552: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8553: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8554: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8555: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8556: # this is the end of "was not already recently cached
1.71      www      8557:     }
1.599     albertel 8558:     return $metaentry{':'.$what};
1.261     albertel 8559: }
                   8560: 
1.488     albertel 8561: sub metadata_create_package_def {
1.483     albertel 8562:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8563:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8564:     if ($subp eq 'default') { next; }
                   8565:     
1.599     albertel 8566:     if (defined($metaentry{':packages'})) {
                   8567: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8568:     } else {
1.599     albertel 8569: 	$metaentry{':packages'}=$package;
1.483     albertel 8570:     }
                   8571:     my $value=$packagetab{$key};
                   8572:     my $unikey;
                   8573:     $unikey='parameter_0_'.$name;
1.599     albertel 8574:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8575:     $$metathesekeys{$unikey}=1;
1.599     albertel 8576:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8577: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8578:     }
1.599     albertel 8579:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8580: 	$metaentry{':'.$unikey}=
                   8581: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8582:     }
                   8583: }
                   8584: 
1.261     albertel 8585: sub metadata_generate_part0 {
                   8586:     my ($metadata,$metacache,$uri) = @_;
                   8587:     my %allnames;
1.737     albertel 8588:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8589: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8590: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8591: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8592: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8593: 	    $allnames{$name}=$part;
                   8594: 	  }
                   8595: 	}
                   8596:     }
                   8597:     foreach my $name (keys(%allnames)) {
                   8598:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8599:       my $key=":parameter_0_$name";
1.261     albertel 8600:       $$metacache{"$key.part"}='0';
                   8601:       $$metacache{"$key.name"}=$name;
1.428     albertel 8602:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8603: 					   $allnames{$name}.'_'.$name.
                   8604: 					   '.type'};
1.428     albertel 8605:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8606: 			     '.display'};
1.644     www      8607:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8608:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8609:       $$metacache{"$key.display"}=$olddis;
                   8610:     }
1.71      www      8611: }
                   8612: 
1.764     albertel 8613: # ------------------------------------------------------ Devalidate title cache
                   8614: 
                   8615: sub devalidate_title_cache {
                   8616:     my ($url)=@_;
                   8617:     if (!$env{'request.course.id'}) { return; }
                   8618:     my $symb=&symbread($url);
                   8619:     if (!$symb) { return; }
                   8620:     my $key=$env{'request.course.id'}."\0".$symb;
                   8621:     &devalidate_cache_new('title',$key);
                   8622: }
                   8623: 
1.1014    droeschl 8624: # ------------------------------------------------- Get the title of a course
                   8625: 
                   8626: sub current_course_title {
                   8627:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8628: }
1.301     www      8629: # ------------------------------------------------- Get the title of a resource
                   8630: 
                   8631: sub gettitle {
                   8632:     my $urlsymb=shift;
                   8633:     my $symb=&symbread($urlsymb);
1.534     albertel 8634:     if ($symb) {
1.620     albertel 8635: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8636: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8637: 	if (defined($cached)) { 
                   8638: 	    return $result;
                   8639: 	}
1.534     albertel 8640: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8641: 	my $title='';
1.907     albertel 8642: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8643: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8644: 	} else {
                   8645: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8646: 		    &GDBM_READER(),0640)) {
                   8647: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8648: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8649: 		untie(%bighash);
                   8650: 	    }
1.534     albertel 8651: 	}
                   8652: 	$title=~s/\&colon\;/\:/gs;
                   8653: 	if ($title) {
1.599     albertel 8654: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8655: 	}
                   8656: 	$urlsymb=$url;
                   8657:     }
                   8658:     my $title=&metadata($urlsymb,'title');
                   8659:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8660:     return $title;
1.301     www      8661: }
1.613     albertel 8662: 
1.614     albertel 8663: sub get_slot {
                   8664:     my ($which,$cnum,$cdom)=@_;
                   8665:     if (!$cnum || !$cdom) {
1.790     albertel 8666: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8667: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8668: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8669:     }
1.703     albertel 8670:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8671:     my %slotinfo;
                   8672:     if (exists($remembered{$key})) {
                   8673: 	$slotinfo{$which} = $remembered{$key};
                   8674:     } else {
                   8675: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8676: 	&Apache::lonhomework::showhash(%slotinfo);
                   8677: 	my ($tmp)=keys(%slotinfo);
                   8678: 	if ($tmp=~/^error:/) { return (); }
                   8679: 	$remembered{$key} = $slotinfo{$which};
                   8680:     }
1.616     albertel 8681:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8682: 	return %{$slotinfo{$which}};
                   8683:     }
                   8684:     return $slotinfo{$which};
1.614     albertel 8685: }
1.31      www      8686: # ------------------------------------------------- Update symbolic store links
                   8687: 
                   8688: sub symblist {
                   8689:     my ($mapname,%newhash)=@_;
1.438     www      8690:     $mapname=&deversion(&declutter($mapname));
1.31      www      8691:     my %hash;
1.620     albertel 8692:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8693:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8694:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8695: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8696: 		next if ($url eq 'last_known'
                   8697: 			 && $env{'form.no_update_last_known'});
                   8698: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8699: 						    $newhash{$url}->[1],
                   8700: 						    $newhash{$url}->[0]);
1.191     harris41 8701:             }
1.31      www      8702:             if (untie(%hash)) {
                   8703: 		return 'ok';
                   8704:             }
                   8705:         }
                   8706:     }
                   8707:     return 'error';
1.212     www      8708: }
                   8709: 
                   8710: # --------------------------------------------------------------- Verify a symb
                   8711: 
                   8712: sub symbverify {
1.510     www      8713:     my ($symb,$thisurl)=@_;
                   8714:     my $thisfn=$thisurl;
1.439     www      8715:     $thisfn=&declutter($thisfn);
1.215     www      8716: # direct jump to resource in page or to a sequence - will construct own symbs
                   8717:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8718: # check URL part
1.409     www      8719:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8720: 
1.431     www      8721:     unless ($url eq $thisfn) { return 0; }
1.213     www      8722: 
1.216     www      8723:     $symb=&symbclean($symb);
1.510     www      8724:     $thisurl=&deversion($thisurl);
1.439     www      8725:     $thisfn=&deversion($thisfn);
1.213     www      8726: 
                   8727:     my %bighash;
                   8728:     my $okay=0;
1.431     www      8729: 
1.620     albertel 8730:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8731:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8732:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8733:             $thisurl =~ s/\?.+$//;
                   8734:         }
1.510     www      8735:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8736:         unless ($ids) { 
1.510     www      8737:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8738:         }
                   8739:         if ($ids) {
                   8740: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8741: 	    foreach my $id (split(/\,/,$ids)) {
                   8742: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8743:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8744:                    $symb =~ s/\?.+$//;
                   8745:                }
1.216     www      8746:                if (
                   8747:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8748:    eq $symb) { 
1.620     albertel 8749: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8750: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8751: 		       $okay=1; 
                   8752: 		   }
                   8753: 	       }
1.216     www      8754: 	   }
                   8755:         }
1.213     www      8756: 	untie(%bighash);
                   8757:     }
                   8758:     return $okay;
1.31      www      8759: }
                   8760: 
1.210     www      8761: # --------------------------------------------------------------- Clean-up symb
                   8762: 
                   8763: sub symbclean {
                   8764:     my $symb=shift;
1.568     albertel 8765:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8766: # remove version from map
                   8767:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8768: 
1.210     www      8769: # remove version from URL
                   8770:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8771: 
1.507     www      8772: # remove wrapper
                   8773: 
1.510     www      8774:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8775:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8776:     return $symb;
1.409     www      8777: }
                   8778: 
                   8779: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8780: 
                   8781: sub encode_symb {
                   8782:     my ($map,$resid,$url)=@_;
                   8783:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8784: }
1.409     www      8785: 
                   8786: sub decode_symb {
1.568     albertel 8787:     my $symb=shift;
                   8788:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8789:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8790:     return (&fixversion($map),$resid,&fixversion($url));
                   8791: }
                   8792: 
                   8793: sub fixversion {
                   8794:     my $fn=shift;
1.609     banghart 8795:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8796:     my %bighash;
                   8797:     my $uri=&clutter($fn);
1.620     albertel 8798:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8799: # is this cached?
1.599     albertel 8800:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8801:     if (defined($cached)) { return $result; }
                   8802: # unfortunately not cached, or expired
1.620     albertel 8803:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8804: 	    &GDBM_READER(),0640)) {
                   8805:  	if ($bighash{'version_'.$uri}) {
                   8806:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8807:  	    unless (($version eq 'mostrecent') || 
                   8808: 		    ($version==&getversion($uri))) {
1.440     www      8809:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8810:  	    }
                   8811:  	}
                   8812:  	untie %bighash;
1.413     www      8813:     }
1.599     albertel 8814:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8815: }
                   8816: 
                   8817: sub deversion {
                   8818:     my $url=shift;
                   8819:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8820:     return $url;
1.210     www      8821: }
                   8822: 
1.31      www      8823: # ------------------------------------------------------ Return symb list entry
                   8824: 
                   8825: sub symbread {
1.249     www      8826:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8827:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8828:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8829: # no filename provided? try from environment
1.44      www      8830:     unless ($thisfn) {
1.620     albertel 8831:         if ($env{'request.symb'}) {
                   8832: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8833: 	}
1.620     albertel 8834: 	$thisfn=$env{'request.filename'};
1.44      www      8835:     }
1.569     albertel 8836:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8837: # is that filename actually a symb? Verify, clean, and return
                   8838:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8839: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8840: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8841: 	}
1.242     www      8842:     }
1.44      www      8843:     $thisfn=declutter($thisfn);
1.31      www      8844:     my %hash;
1.37      www      8845:     my %bighash;
                   8846:     my $syval='';
1.620     albertel 8847:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8848:         my $targetfn = $thisfn;
1.609     banghart 8849:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8850:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8851:         }
1.687     albertel 8852: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8853: 	    $targetfn=$1;
                   8854: 	}
1.620     albertel 8855:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8856:                       &GDBM_READER(),0640)) {
1.481     raeburn  8857: 	    $syval=$hash{$targetfn};
1.37      www      8858:             untie(%hash);
                   8859:         }
                   8860: # ---------------------------------------------------------- There was an entry
                   8861:         if ($syval) {
1.601     albertel 8862: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8863: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8864: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8865: 		    #return $env{$cache_str}='';
1.601     albertel 8866: 		#}    
                   8867: 		#$syval.=$1;
                   8868: 	    #}
1.37      www      8869:         } else {
                   8870: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8871:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8872:                             &GDBM_READER(),0640)) {
1.37      www      8873: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8874:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8875:               unless ($ids) { 
                   8876:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8877:               }
                   8878:               unless ($ids) {
                   8879: # alias?
                   8880: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8881:               }
1.37      www      8882:               if ($ids) {
                   8883: # ------------------------------------------------------------------- Has ID(s)
                   8884:                  my @possibilities=split(/\,/,$ids);
1.39      www      8885:                  if ($#possibilities==0) {
                   8886: # ----------------------------------------------- There is only one possibility
1.37      www      8887: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8888: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8889: 						    $resid,$thisfn);
1.249     www      8890:                  } elsif (!$donotrecurse) {
1.39      www      8891: # ------------------------------------------ There is more than one possibility
                   8892:                      my $realpossible=0;
1.800     albertel 8893:                      foreach my $id (@possibilities) {
                   8894: 			 my $file=$bighash{'src_'.$id};
1.39      www      8895:                          if (&allowed('bre',$file)) {
1.800     albertel 8896:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8897:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8898: 				$realpossible++;
1.626     albertel 8899:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8900: 						    $resid,$thisfn);
1.39      www      8901:                             }
                   8902: 			 }
1.191     harris41 8903:                      }
1.39      www      8904: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8905:                  } else {
                   8906:                      $syval='';
1.37      www      8907:                  }
                   8908: 	      }
                   8909:               untie(%bighash)
1.481     raeburn  8910:            }
1.31      www      8911:         }
1.62      www      8912:         if ($syval) {
1.620     albertel 8913: 	    return $env{$cache_str}=$syval;
1.62      www      8914:         }
1.31      www      8915:     }
1.949     raeburn  8916:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8917:     return $env{$cache_str}='';
1.31      www      8918: }
                   8919: 
                   8920: # ---------------------------------------------------------- Return random seed
                   8921: 
1.32      www      8922: sub numval {
                   8923:     my $txt=shift;
                   8924:     $txt=~tr/A-J/0-9/;
                   8925:     $txt=~tr/a-j/0-9/;
                   8926:     $txt=~tr/K-T/0-9/;
                   8927:     $txt=~tr/k-t/0-9/;
                   8928:     $txt=~tr/U-Z/0-5/;
                   8929:     $txt=~tr/u-z/0-5/;
                   8930:     $txt=~s/\D//g;
1.564     albertel 8931:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8932:     return int($txt);
1.368     albertel 8933: }
                   8934: 
1.484     albertel 8935: sub numval2 {
                   8936:     my $txt=shift;
                   8937:     $txt=~tr/A-J/0-9/;
                   8938:     $txt=~tr/a-j/0-9/;
                   8939:     $txt=~tr/K-T/0-9/;
                   8940:     $txt=~tr/k-t/0-9/;
                   8941:     $txt=~tr/U-Z/0-5/;
                   8942:     $txt=~tr/u-z/0-5/;
                   8943:     $txt=~s/\D//g;
                   8944:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8945:     my $total;
                   8946:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8947:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8948:     return int($total);
                   8949: }
                   8950: 
1.575     albertel 8951: sub numval3 {
                   8952:     use integer;
                   8953:     my $txt=shift;
                   8954:     $txt=~tr/A-J/0-9/;
                   8955:     $txt=~tr/a-j/0-9/;
                   8956:     $txt=~tr/K-T/0-9/;
                   8957:     $txt=~tr/k-t/0-9/;
                   8958:     $txt=~tr/U-Z/0-5/;
                   8959:     $txt=~tr/u-z/0-5/;
                   8960:     $txt=~s/\D//g;
                   8961:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8962:     my $total;
                   8963:     foreach my $val (@txts) { $total+=$val; }
                   8964:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8965:     return $total;
                   8966: }
                   8967: 
1.675     albertel 8968: sub digest {
                   8969:     my ($data)=@_;
                   8970:     my $digest=&Digest::MD5::md5($data);
                   8971:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8972:     my ($e,$f);
                   8973:     {
                   8974:         use integer;
                   8975:         $e=($a+$b);
                   8976:         $f=($c+$d);
                   8977:         if ($_64bit) {
                   8978:             $e=(($e<<32)>>32);
                   8979:             $f=(($f<<32)>>32);
                   8980:         }
                   8981:     }
                   8982:     if (wantarray) {
                   8983: 	return ($e,$f);
                   8984:     } else {
                   8985: 	my $g;
                   8986: 	{
                   8987: 	    use integer;
                   8988: 	    $g=($e+$f);
                   8989: 	    if ($_64bit) {
                   8990: 		$g=(($g<<32)>>32);
                   8991: 	    }
                   8992: 	}
                   8993: 	return $g;
                   8994:     }
                   8995: }
                   8996: 
1.368     albertel 8997: sub latest_rnd_algorithm_id {
1.675     albertel 8998:     return '64bit5';
1.366     albertel 8999: }
1.32      www      9000: 
1.503     albertel 9001: sub get_rand_alg {
                   9002:     my ($courseid)=@_;
1.790     albertel 9003:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9004:     if ($courseid) {
1.620     albertel 9005: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9006:     }
                   9007:     return &latest_rnd_algorithm_id();
                   9008: }
                   9009: 
1.562     albertel 9010: sub validCODE {
                   9011:     my ($CODE)=@_;
                   9012:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9013:     return 0;
                   9014: }
                   9015: 
1.491     albertel 9016: sub getCODE {
1.620     albertel 9017:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9018:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9019: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9020: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9021: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9022:     }
                   9023:     return undef;
                   9024: }
                   9025: 
1.31      www      9026: sub rndseed {
1.155     albertel 9027:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9028:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9029:     if (!defined($symb)) {
1.366     albertel 9030: 	unless ($symb=$wsymb) { return time; }
                   9031:     }
                   9032:     if (!$courseid) { $courseid=$wcourseid; }
                   9033:     if (!$domain) { $domain=$wdomain; }
                   9034:     if (!$username) { $username=$wusername }
1.503     albertel 9035:     my $which=&get_rand_alg();
1.803     albertel 9036: 
1.491     albertel 9037:     if (defined(&getCODE())) {
1.675     albertel 9038: 	if ($which eq '64bit5') {
                   9039: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9040: 	} elsif ($which eq '64bit4') {
1.575     albertel 9041: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9042: 	} else {
                   9043: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9044: 	}
1.675     albertel 9045:     } elsif ($which eq '64bit5') {
                   9046: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9047:     } elsif ($which eq '64bit4') {
                   9048: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9049:     } elsif ($which eq '64bit3') {
                   9050: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9051:     } elsif ($which eq '64bit2') {
                   9052: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9053:     } elsif ($which eq '64bit') {
                   9054: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9055:     }
                   9056:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9057: }
                   9058: 
                   9059: sub rndseed_32bit {
                   9060:     my ($symb,$courseid,$domain,$username)=@_;
                   9061:     {
                   9062: 	use integer;
                   9063: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9064: 	my $symbseed=numval($symb) << 22;
                   9065: 	my $namechck=unpack("%32C*",$username) << 17;
                   9066: 	my $nameseed=numval($username) << 12;
                   9067: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9068: 	my $courseseed=unpack("%32C*",$courseid);
                   9069: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9070: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9071: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9072: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9073: 	return $num;
                   9074:     }
                   9075: }
                   9076: 
                   9077: sub rndseed_64bit {
                   9078:     my ($symb,$courseid,$domain,$username)=@_;
                   9079:     {
                   9080: 	use integer;
                   9081: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9082: 	my $symbseed=numval($symb) << 10;
                   9083: 	my $namechck=unpack("%32S*",$username);
                   9084: 	
                   9085: 	my $nameseed=numval($username) << 21;
                   9086: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9087: 	my $courseseed=unpack("%32S*",$courseid);
                   9088: 	
                   9089: 	my $num1=$symbchck+$symbseed+$namechck;
                   9090: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9091: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9092: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9093: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9094: 	return "$num1,$num2";
1.155     albertel 9095:     }
1.366     albertel 9096: }
                   9097: 
1.443     albertel 9098: sub rndseed_64bit2 {
                   9099:     my ($symb,$courseid,$domain,$username)=@_;
                   9100:     {
                   9101: 	use integer;
                   9102: 	# strings need to be an even # of cahracters long, it it is odd the
                   9103:         # last characters gets thrown away
                   9104: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9105: 	my $symbseed=numval($symb) << 10;
                   9106: 	my $namechck=unpack("%32S*",$username.' ');
                   9107: 	
                   9108: 	my $nameseed=numval($username) << 21;
1.501     albertel 9109: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9110: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9111: 	
                   9112: 	my $num1=$symbchck+$symbseed+$namechck;
                   9113: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9114: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9115: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9116: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9117: 	return "$num1,$num2";
                   9118:     }
                   9119: }
                   9120: 
                   9121: sub rndseed_64bit3 {
                   9122:     my ($symb,$courseid,$domain,$username)=@_;
                   9123:     {
                   9124: 	use integer;
                   9125: 	# strings need to be an even # of cahracters long, it it is odd the
                   9126:         # last characters gets thrown away
                   9127: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9128: 	my $symbseed=numval2($symb) << 10;
                   9129: 	my $namechck=unpack("%32S*",$username.' ');
                   9130: 	
                   9131: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9132: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9133: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9134: 	
                   9135: 	my $num1=$symbchck+$symbseed+$namechck;
                   9136: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9137: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9138: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9139: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9140: 	
1.503     albertel 9141: 	return "$num1:$num2";
1.443     albertel 9142:     }
                   9143: }
                   9144: 
1.575     albertel 9145: sub rndseed_64bit4 {
                   9146:     my ($symb,$courseid,$domain,$username)=@_;
                   9147:     {
                   9148: 	use integer;
                   9149: 	# strings need to be an even # of cahracters long, it it is odd the
                   9150:         # last characters gets thrown away
                   9151: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9152: 	my $symbseed=numval3($symb) << 10;
                   9153: 	my $namechck=unpack("%32S*",$username.' ');
                   9154: 	
                   9155: 	my $nameseed=numval3($username) << 21;
                   9156: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9157: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9158: 	
                   9159: 	my $num1=$symbchck+$symbseed+$namechck;
                   9160: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9161: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9162: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9163: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9164: 	
                   9165: 	return "$num1:$num2";
                   9166:     }
                   9167: }
                   9168: 
1.675     albertel 9169: sub rndseed_64bit5 {
                   9170:     my ($symb,$courseid,$domain,$username)=@_;
                   9171:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9172:     return "$num1:$num2";
                   9173: }
                   9174: 
1.366     albertel 9175: sub rndseed_CODE_64bit {
                   9176:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9177:     {
1.366     albertel 9178: 	use integer;
1.443     albertel 9179: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9180: 	my $symbseed=numval2($symb);
1.491     albertel 9181: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9182: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9183: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9184: 	my $num1=$symbseed+$CODEchck;
                   9185: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9186: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9187: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9188: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9189: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9190: 	return "$num1:$num2";
1.366     albertel 9191:     }
                   9192: }
                   9193: 
1.575     albertel 9194: sub rndseed_CODE_64bit4 {
                   9195:     my ($symb,$courseid,$domain,$username)=@_;
                   9196:     {
                   9197: 	use integer;
                   9198: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9199: 	my $symbseed=numval3($symb);
                   9200: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9201: 	my $CODEseed=numval3(&getCODE());
                   9202: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9203: 	my $num1=$symbseed+$CODEchck;
                   9204: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9205: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9206: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9207: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9208: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9209: 	return "$num1:$num2";
                   9210:     }
                   9211: }
                   9212: 
1.675     albertel 9213: sub rndseed_CODE_64bit5 {
                   9214:     my ($symb,$courseid,$domain,$username)=@_;
                   9215:     my $code = &getCODE();
                   9216:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9217:     return "$num1:$num2";
                   9218: }
                   9219: 
1.366     albertel 9220: sub setup_random_from_rndseed {
                   9221:     my ($rndseed)=@_;
1.503     albertel 9222:     if ($rndseed =~/([,:])/) {
                   9223: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9224: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9225:     } else {
                   9226: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9227:     }
1.36      albertel 9228: }
                   9229: 
1.474     albertel 9230: sub latest_receipt_algorithm_id {
1.835     albertel 9231:     return 'receipt3';
1.474     albertel 9232: }
                   9233: 
1.480     www      9234: sub recunique {
                   9235:     my $fucourseid=shift;
                   9236:     my $unique;
1.835     albertel 9237:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9238: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9239: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9240:     } else {
                   9241: 	$unique=$perlvar{'lonReceipt'};
                   9242:     }
                   9243:     return unpack("%32C*",$unique);
                   9244: }
                   9245: 
                   9246: sub recprefix {
                   9247:     my $fucourseid=shift;
                   9248:     my $prefix;
1.835     albertel 9249:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9250: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9251: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9252:     } else {
                   9253: 	$prefix=$perlvar{'lonHostID'};
                   9254:     }
                   9255:     return unpack("%32C*",$prefix);
                   9256: }
                   9257: 
1.76      www      9258: sub ireceipt {
1.474     albertel 9259:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9260: 
                   9261:     my $return =&recprefix($fucourseid).'-';
                   9262: 
                   9263:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9264: 	$env{'request.state'} eq 'construct') {
                   9265: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9266: 	return $return;
                   9267:     }
                   9268: 
1.76      www      9269:     my $cuname=unpack("%32C*",$funame);
                   9270:     my $cudom=unpack("%32C*",$fudom);
                   9271:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9272:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9273:     my $cunique=&recunique($fucourseid);
1.474     albertel 9274:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9275:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9276: 
1.790     albertel 9277: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9278: 			       
                   9279: 	$return.= ($cunique%$cuname+
                   9280: 		   $cunique%$cudom+
                   9281: 		   $cusymb%$cuname+
                   9282: 		   $cusymb%$cudom+
                   9283: 		   $cucourseid%$cuname+
                   9284: 		   $cucourseid%$cudom+
                   9285: 		   $cpart%$cuname+
                   9286: 		   $cpart%$cudom);
                   9287:     } else {
                   9288: 	$return.= ($cunique%$cuname+
                   9289: 		   $cunique%$cudom+
                   9290: 		   $cusymb%$cuname+
                   9291: 		   $cusymb%$cudom+
                   9292: 		   $cucourseid%$cuname+
                   9293: 		   $cucourseid%$cudom);
                   9294:     }
                   9295:     return $return;
1.76      www      9296: }
                   9297: 
                   9298: sub receipt {
1.474     albertel 9299:     my ($part)=@_;
1.790     albertel 9300:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9301:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9302: }
1.260     ng       9303: 
1.790     albertel 9304: sub whichuser {
                   9305:     my ($passedsymb)=@_;
                   9306:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9307:     if (defined($env{'form.grade_symb'})) {
                   9308: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9309: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9310: 	if (!$allowed &&
                   9311: 	    exists($env{'request.course.sec'}) &&
                   9312: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9313: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9314: 			      '/'.$env{'request.course.sec'});
                   9315: 	}
                   9316: 	if ($allowed) {
                   9317: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9318: 	    $courseid=$tmp_courseid;
                   9319: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9320: 	    ($name)=&get_env_multiple('form.grade_username');
                   9321: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9322: 	}
                   9323:     }
                   9324:     if (!$passedsymb) {
                   9325: 	$symb=&symbread();
                   9326:     } else {
                   9327: 	$symb=$passedsymb;
                   9328:     }
                   9329:     $courseid=$env{'request.course.id'};
                   9330:     $domain=$env{'user.domain'};
                   9331:     $name=$env{'user.name'};
                   9332:     if ($name eq 'public' && $domain eq 'public') {
                   9333: 	if (!defined($env{'form.username'})) {
                   9334: 	    $env{'form.username'}.=time.rand(10000000);
                   9335: 	}
                   9336: 	$name.=$env{'form.username'};
                   9337:     }
                   9338:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9339: 
                   9340: }
                   9341: 
1.36      albertel 9342: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9343: # returns either the contents of the file or 
                   9344: # -1 if the file doesn't exist
1.481     raeburn  9345: #
                   9346: # if the target is a file that was uploaded via DOCS, 
                   9347: # a check will be made to see if a current copy exists on the local server,
                   9348: # if it does this will be served, otherwise a copy will be retrieved from
                   9349: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9350: # the local server.   
1.472     albertel 9351: 
1.36      albertel 9352: sub getfile {
1.538     albertel 9353:     my ($file) = @_;
1.609     banghart 9354:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9355:     &repcopy($file);
                   9356:     return &readfile($file);
                   9357: }
                   9358: 
                   9359: sub repcopy_userfile {
                   9360:     my ($file)=@_;
1.609     banghart 9361:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9362:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9363:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9364: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9365:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9366:     if (-e "$file") {
1.828     www      9367: # we already have a local copy, check it out
1.538     albertel 9368: 	my @fileinfo = stat($file);
1.828     www      9369: 	my $rtncode;
                   9370: 	my $info;
1.538     albertel 9371: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9372: 	if ($lwpresp ne 'ok') {
1.828     www      9373: # there is no such file anymore, even though we had a local copy
1.482     albertel 9374: 	    if ($rtncode eq '404') {
1.538     albertel 9375: 		unlink($file);
1.482     albertel 9376: 	    }
                   9377: 	    return -1;
                   9378: 	}
                   9379: 	if ($info < $fileinfo[9]) {
1.828     www      9380: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9381: 	    return 'ok';
1.828     www      9382: 	} else {
                   9383: # the file is outdated, get rid of it
                   9384: 	    unlink($file);
1.482     albertel 9385: 	}
1.828     www      9386:     }
                   9387: # one way or the other, at this point, we don't have the file
                   9388: # construct the correct path for the file
                   9389:     my @parts = ($cdom,$cnum); 
                   9390:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9391: 	push @parts, split(/\//,$1);
                   9392:     }
                   9393:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9394:     foreach my $part (@parts) {
                   9395: 	$path .= '/'.$part;
                   9396: 	if (!-e $path) {
                   9397: 	    mkdir($path,0770);
1.482     albertel 9398: 	}
                   9399:     }
1.828     www      9400: # now the path exists for sure
                   9401: # get a user agent
                   9402:     my $ua=new LWP::UserAgent;
                   9403:     my $transferfile=$file.'.in.transfer';
                   9404: # FIXME: this should flock
                   9405:     if (-e $transferfile) { return 'ok'; }
                   9406:     my $request;
                   9407:     $uri=~s/^\///;
1.980     raeburn  9408:     my $homeserver = &homeserver($cnum,$cdom);
                   9409:     my $protocol = $protocol{$homeserver};
                   9410:     $protocol = 'http' if ($protocol ne 'https');
                   9411:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9412:     my $response=$ua->request($request,$transferfile);
                   9413: # did it work?
                   9414:     if ($response->is_error()) {
                   9415: 	unlink($transferfile);
                   9416: 	&logthis("Userfile repcopy failed for $uri");
                   9417: 	return -1;
                   9418:     }
                   9419: # worked, rename the transfer file
                   9420:     rename($transferfile,$file);
1.607     raeburn  9421:     return 'ok';
1.481     raeburn  9422: }
                   9423: 
1.517     albertel 9424: sub tokenwrapper {
                   9425:     my $uri=shift;
1.980     raeburn  9426:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9427:     $uri=~s|^/||;
1.620     albertel 9428:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9429:     my $token=$1;
1.552     albertel 9430:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9431:     if ($udom && $uname && $file) {
                   9432: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9433:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9434:         my $homeserver = &homeserver($uname,$udom);
                   9435:         my $protocol = $protocol{$homeserver};
                   9436:         $protocol = 'http' if ($protocol ne 'https');
                   9437:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9438:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9439:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9440:     } else {
                   9441:         return '/adm/notfound.html';
                   9442:     }
                   9443: }
                   9444: 
1.828     www      9445: # call with reqtype HEAD: get last modification time
                   9446: # call with reqtype GET: get the file contents
                   9447: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9448: #
1.481     raeburn  9449: sub getuploaded {
                   9450:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9451:     $uri=~s/^\///;
1.980     raeburn  9452:     my $homeserver = &homeserver($cnum,$cdom);
                   9453:     my $protocol = $protocol{$homeserver};
                   9454:     $protocol = 'http' if ($protocol ne 'https');
                   9455:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9456:     my $ua=new LWP::UserAgent;
                   9457:     my $request=new HTTP::Request($reqtype,$uri);
                   9458:     my $response=$ua->request($request);
                   9459:     $$rtncode = $response->code;
1.482     albertel 9460:     if (! $response->is_success()) {
                   9461: 	return 'failed';
                   9462:     }      
                   9463:     if ($reqtype eq 'HEAD') {
1.486     www      9464: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9465:     } elsif ($reqtype eq 'GET') {
                   9466: 	$$info = $response->content;
1.472     albertel 9467:     }
1.482     albertel 9468:     return 'ok';
1.36      albertel 9469: }
                   9470: 
1.481     raeburn  9471: sub readfile {
                   9472:     my $file = shift;
                   9473:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9474:     my $fh;
                   9475:     open($fh,"<$file");
                   9476:     my $a='';
1.800     albertel 9477:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9478:     return $a;
                   9479: }
                   9480: 
1.36      albertel 9481: sub filelocation {
1.590     banghart 9482:     my ($dir,$file) = @_;
                   9483:     my $location;
                   9484:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9485: 
                   9486:     if ($file =~ m-^/adm/-) {
                   9487: 	$file=~s-^/adm/wrapper/-/-;
                   9488: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9489:     }
1.882     albertel 9490: 
1.590     banghart 9491:     if ($file=~m:^/~:) { # is a contruction space reference
                   9492:         $location = $file;
                   9493:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9494:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9495: 	# is a correct contruction space reference
                   9496:         $location = $file;
1.956     raeburn  9497:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9498:         $location = $file;
1.609     banghart 9499:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9500:         my ($udom,$uname,$filename)=
1.811     albertel 9501:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9502:         my $home=&homeserver($uname,$udom);
                   9503:         my $is_me=0;
                   9504:         my @ids=&current_machine_ids();
                   9505:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9506:         if ($is_me) {
1.955     raeburn  9507:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9508:         } else {
                   9509:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9510:   	      $udom.'/'.$uname.'/'.$filename;
                   9511:         }
1.882     albertel 9512:     } elsif ($file =~ m-^/adm/-) {
                   9513: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9514:     } else {
                   9515:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9516:         $file=~s:^/res/:/:;
                   9517:         if ( !( $file =~ m:^/:) ) {
                   9518:             $location = $dir. '/'.$file;
                   9519:         } else {
                   9520:             $location = '/home/httpd/html/res'.$file;
                   9521:         }
1.59      albertel 9522:     }
1.590     banghart 9523:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9524:     while ($location=~m{/\.\./}) {
                   9525: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9526: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9527: 	} else {
                   9528: 	    $location=~ s{/\.\./}{/}g;
                   9529: 	}
                   9530:     } #remove dir/..
1.590     banghart 9531:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9532:     return $location;
1.46      www      9533: }
1.36      albertel 9534: 
1.46      www      9535: sub hreflocation {
                   9536:     my ($dir,$file)=@_;
1.980     raeburn  9537:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9538: 	$file=filelocation($dir,$file);
1.700     albertel 9539:     } elsif ($file=~m-^/adm/-) {
                   9540: 	$file=~s-^/adm/wrapper/-/-;
                   9541: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9542:     }
                   9543:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9544: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9545:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9546: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9547:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9548: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9549: 	    -/uploaded/$1/$2/-x;
1.46      www      9550:     }
1.913     albertel 9551:     if ($file=~ m{^/userfiles/}) {
                   9552: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9553:     }
1.462     albertel 9554:     return $file;
1.465     albertel 9555: }
                   9556: 
                   9557: sub current_machine_domains {
1.853     albertel 9558:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9559: }
                   9560: 
                   9561: sub machine_domains {
                   9562:     my ($hostname) = @_;
1.465     albertel 9563:     my @domains;
1.838     albertel 9564:     my %hostname = &all_hostnames();
1.465     albertel 9565:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9566: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9567: 	if ($hostname eq $name) {
1.844     albertel 9568: 	    push(@domains,&host_domain($id));
1.465     albertel 9569: 	}
                   9570:     }
                   9571:     return @domains;
                   9572: }
                   9573: 
                   9574: sub current_machine_ids {
1.853     albertel 9575:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9576: }
                   9577: 
                   9578: sub machine_ids {
                   9579:     my ($hostname) = @_;
                   9580:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9581:     my @ids;
1.888     albertel 9582:     my %name_to_host = &all_names();
1.889     albertel 9583:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9584: 	return @{ $name_to_host{$hostname} };
                   9585:     }
                   9586:     return;
1.31      www      9587: }
                   9588: 
1.824     raeburn  9589: sub additional_machine_domains {
                   9590:     my @domains;
                   9591:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9592:     while( my $line = <$fh>) {
                   9593:         $line =~ s/\s//g;
                   9594:         push(@domains,$line);
                   9595:     }
                   9596:     return @domains;
                   9597: }
                   9598: 
                   9599: sub default_login_domain {
                   9600:     my $domain = $perlvar{'lonDefDomain'};
                   9601:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9602:     foreach my $posdom (&current_machine_domains(),
                   9603:                         &additional_machine_domains()) {
                   9604:         if (lc($posdom) eq lc($testdomain)) {
                   9605:             $domain=$posdom;
                   9606:             last;
                   9607:         }
                   9608:     }
                   9609:     return $domain;
                   9610: }
                   9611: 
1.31      www      9612: # ------------------------------------------------------------- Declutters URLs
                   9613: 
                   9614: sub declutter {
                   9615:     my $thisfn=shift;
1.569     albertel 9616:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9617:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9618:     $thisfn=~s/^\///;
1.697     albertel 9619:     $thisfn=~s|^adm/wrapper/||;
                   9620:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9621:     $thisfn=~s/^res\///;
1.1032    raeburn  9622:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9623:         $thisfn=~s/\?.+$//;
                   9624:     }
1.268     www      9625:     return $thisfn;
                   9626: }
                   9627: 
                   9628: # ------------------------------------------------------------- Clutter up URLs
                   9629: 
                   9630: sub clutter {
                   9631:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9632:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9633: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9634:        $thisfn='/res'.$thisfn; 
                   9635:     }
1.1031    raeburn  9636:     if ($thisfn !~m|^/adm|) {
                   9637: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9638: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9639: 	} else {
                   9640: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9641: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9642: 	    if ($embstyle eq 'ssi'
                   9643: 		|| ($embstyle eq 'hdn')
                   9644: 		|| ($embstyle eq 'rat')
                   9645: 		|| ($embstyle eq 'prv')
                   9646: 		|| ($embstyle eq 'ign')) {
                   9647: 		#do nothing with these
                   9648: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9649: 		|| ($embstyle eq 'emb')
                   9650: 		|| ($embstyle eq 'wrp')) {
                   9651: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9652: 	    } elsif ($embstyle eq 'unk'
                   9653: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9654: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9655: 	    } else {
1.718     www      9656: #		&logthis("Got a blank emb style");
1.695     albertel 9657: 	    }
1.694     albertel 9658: 	}
                   9659:     }
1.31      www      9660:     return $thisfn;
1.12      www      9661: }
                   9662: 
1.787     albertel 9663: sub clutter_with_no_wrapper {
                   9664:     my $uri = &clutter(shift);
                   9665:     if ($uri =~ m-^/adm/-) {
                   9666: 	$uri =~ s-^/adm/wrapper/-/-;
                   9667: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9668:     }
                   9669:     return $uri;
                   9670: }
                   9671: 
1.557     albertel 9672: sub freeze_escape {
                   9673:     my ($value)=@_;
                   9674:     if (ref($value)) {
                   9675: 	$value=&nfreeze($value);
                   9676: 	return '__FROZEN__'.&escape($value);
                   9677:     }
                   9678:     return &escape($value);
                   9679: }
                   9680: 
1.11      www      9681: 
1.557     albertel 9682: sub thaw_unescape {
                   9683:     my ($value)=@_;
                   9684:     if ($value =~ /^__FROZEN__/) {
                   9685: 	substr($value,0,10,undef);
                   9686: 	$value=&unescape($value);
                   9687: 	return &thaw($value);
                   9688:     }
                   9689:     return &unescape($value);
                   9690: }
                   9691: 
1.436     albertel 9692: sub correct_line_ends {
                   9693:     my ($result)=@_;
                   9694:     $$result =~s/\r\n/\n/mg;
                   9695:     $$result =~s/\r/\n/mg;
1.415     albertel 9696: }
1.1       albertel 9697: # ================================================================ Main Program
                   9698: 
1.184     www      9699: sub goodbye {
1.204     albertel 9700:    &logthis("Starting Shut down");
1.443     albertel 9701: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9702:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9703: #converted
1.599     albertel 9704: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9705:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9706: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9707: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9708: #1.1 only
1.870     albertel 9709: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9710: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9711: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9712: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9713:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9714:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9715:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9716:    &flushcourselogs();
                   9717:    &logthis("Shutting down");
                   9718: }
                   9719: 
1.852     albertel 9720: sub get_dns {
1.869     albertel 9721:     my ($url,$func,$ignore_cache) = @_;
                   9722:     if (!$ignore_cache) {
                   9723: 	my ($content,$cached)=
                   9724: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9725: 	if ($cached) {
                   9726: 	    &$func($content);
                   9727: 	    return;
                   9728: 	}
                   9729:     }
                   9730: 
                   9731:     my %alldns;
1.852     albertel 9732:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9733:     foreach my $dns (<$config>) {
                   9734: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9735:         my $line = $1;
                   9736:         my ($host,$protocol) = split(/:/,$line);
                   9737:         if ($protocol ne 'https') {
                   9738:             $protocol = 'http';
                   9739:         }
                   9740: 	$alldns{$host} = $protocol;
1.869     albertel 9741:     }
                   9742:     while (%alldns) {
                   9743: 	my ($dns) = keys(%alldns);
1.852     albertel 9744: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9745: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9746: 	my $response=$ua->request($request);
1.979     raeburn  9747:         delete($alldns{$dns});
1.852     albertel 9748: 	next if ($response->is_error());
                   9749: 	my @content = split("\n",$response->content);
1.869     albertel 9750: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9751: 	&$func(\@content);
1.869     albertel 9752: 	return;
1.852     albertel 9753:     }
                   9754:     close($config);
1.871     albertel 9755:     my $which = (split('/',$url))[3];
                   9756:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9757:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9758:     my @content = <$config>;
                   9759:     &$func(\@content);
                   9760:     return;
1.852     albertel 9761: }
1.327     albertel 9762: # ------------------------------------------------------------ Read domain file
                   9763: {
1.852     albertel 9764:     my $loaded;
1.846     albertel 9765:     my %domain;
                   9766: 
1.852     albertel 9767:     sub parse_domain_tab {
                   9768: 	my ($lines) = @_;
                   9769: 	foreach my $line (@$lines) {
                   9770: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9771: 
1.846     albertel 9772: 	    chomp($line);
1.852     albertel 9773: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9774: 	    my %this_domain;
                   9775: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9776: 			       'lang_def', 'city', 'longi', 'lati',
                   9777: 			       'primary') {
                   9778: 		$this_domain{$field} = shift(@elements);
                   9779: 	    }
                   9780: 	    $domain{$name} = \%this_domain;
1.852     albertel 9781: 	}
                   9782:     }
1.864     albertel 9783: 
                   9784:     sub reset_domain_info {
                   9785: 	undef($loaded);
                   9786: 	undef(%domain);
                   9787:     }
                   9788: 
1.852     albertel 9789:     sub load_domain_tab {
1.869     albertel 9790: 	my ($ignore_cache) = @_;
                   9791: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9792: 	my $fh;
                   9793: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9794: 	    my @lines = <$fh>;
                   9795: 	    &parse_domain_tab(\@lines);
1.448     albertel 9796: 	}
1.852     albertel 9797: 	close($fh);
                   9798: 	$loaded = 1;
1.327     albertel 9799:     }
1.846     albertel 9800: 
                   9801:     sub domain {
1.852     albertel 9802: 	&load_domain_tab() if (!$loaded);
                   9803: 
1.846     albertel 9804: 	my ($name,$what) = @_;
                   9805: 	return if ( !exists($domain{$name}) );
                   9806: 
                   9807: 	if (!$what) {
                   9808: 	    return $domain{$name}{'description'};
                   9809: 	}
                   9810: 	return $domain{$name}{$what};
                   9811:     }
1.974     raeburn  9812: 
                   9813:     sub domain_info {
                   9814:         &load_domain_tab() if (!$loaded);
                   9815:         return %domain;
                   9816:     }
                   9817: 
1.327     albertel 9818: }
                   9819: 
                   9820: 
1.1       albertel 9821: # ------------------------------------------------------------- Read hosts file
                   9822: {
1.838     albertel 9823:     my %hostname;
1.844     albertel 9824:     my %hostdom;
1.845     albertel 9825:     my %libserv;
1.852     albertel 9826:     my $loaded;
1.888     albertel 9827:     my %name_to_host;
1.1074    raeburn  9828:     my %internetdom;
1.852     albertel 9829: 
                   9830:     sub parse_hosts_tab {
                   9831: 	my ($file) = @_;
                   9832: 	foreach my $configline (@$file) {
                   9833: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9834: 	    next if ($configline =~ /^\^/);
                   9835: 	    chomp($configline);
1.1074    raeburn  9836: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 9837: 	    $name=~s/\s//g;
                   9838: 	    if ($id && $domain && $role && $name) {
                   9839: 		$hostname{$id}=$name;
1.888     albertel 9840: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9841: 		$hostdom{$id}=$domain;
                   9842: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9843:                 if (defined($protocol)) {
                   9844:                     if ($protocol eq 'https') {
                   9845:                         $protocol{$id} = $protocol;
                   9846:                     } else {
                   9847:                         $protocol{$id} = 'http'; 
                   9848:                     }
1.968     raeburn  9849:                 } else {
1.969     raeburn  9850:                     $protocol{$id} = 'http';
1.968     raeburn  9851:                 }
1.1074    raeburn  9852:                 if (defined($intdom)) {
                   9853:                     $internetdom{$id} = $intdom;
                   9854:                 }
1.852     albertel 9855: 	    }
                   9856: 	}
                   9857:     }
1.864     albertel 9858:     
                   9859:     sub reset_hosts_info {
1.897     albertel 9860: 	&purge_remembered();
1.864     albertel 9861: 	&reset_domain_info();
                   9862: 	&reset_hosts_ip_info();
1.892     albertel 9863: 	undef(%name_to_host);
1.864     albertel 9864: 	undef(%hostname);
                   9865: 	undef(%hostdom);
                   9866: 	undef(%libserv);
                   9867: 	undef($loaded);
                   9868:     }
1.1       albertel 9869: 
1.852     albertel 9870:     sub load_hosts_tab {
1.869     albertel 9871: 	my ($ignore_cache) = @_;
                   9872: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9873: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9874: 	my @config = <$config>;
                   9875: 	&parse_hosts_tab(\@config);
                   9876: 	close($config);
                   9877: 	$loaded=1;
1.1       albertel 9878:     }
1.852     albertel 9879: 
1.838     albertel 9880:     sub hostname {
1.852     albertel 9881: 	&load_hosts_tab() if (!$loaded);
                   9882: 
1.838     albertel 9883: 	my ($lonid) = @_;
                   9884: 	return $hostname{$lonid};
                   9885:     }
1.845     albertel 9886: 
1.838     albertel 9887:     sub all_hostnames {
1.852     albertel 9888: 	&load_hosts_tab() if (!$loaded);
                   9889: 
1.838     albertel 9890: 	return %hostname;
                   9891:     }
1.845     albertel 9892: 
1.888     albertel 9893:     sub all_names {
                   9894: 	&load_hosts_tab() if (!$loaded);
                   9895: 
                   9896: 	return %name_to_host;
                   9897:     }
                   9898: 
1.974     raeburn  9899:     sub all_host_domain {
                   9900:         &load_hosts_tab() if (!$loaded);
                   9901:         return %hostdom;
                   9902:     }
                   9903: 
1.845     albertel 9904:     sub is_library {
1.852     albertel 9905: 	&load_hosts_tab() if (!$loaded);
                   9906: 
1.845     albertel 9907: 	return exists($libserv{$_[0]});
                   9908:     }
                   9909: 
                   9910:     sub all_library {
1.852     albertel 9911: 	&load_hosts_tab() if (!$loaded);
                   9912: 
1.845     albertel 9913: 	return %libserv;
                   9914:     }
                   9915: 
1.1062    droeschl 9916:     sub unique_library {
                   9917: 	#2x reverse removes all hostnames that appear more than once
                   9918:         my %unique = reverse &all_library();
                   9919:         return reverse %unique;
                   9920:     }
                   9921: 
1.841     albertel 9922:     sub get_servers {
1.852     albertel 9923: 	&load_hosts_tab() if (!$loaded);
                   9924: 
1.841     albertel 9925: 	my ($domain,$type) = @_;
                   9926: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9927: 	                                          : %hostname;
                   9928: 	my %result;
1.842     albertel 9929: 	if (ref($domain) eq 'ARRAY') {
                   9930: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9931: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9932: 		    $result{$host} = $hostname;
                   9933: 		}
                   9934: 	    }
                   9935: 	} else {
                   9936: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9937: 		if ($hostdom{$host} eq $domain) {
                   9938: 		    $result{$host} = $hostname;
                   9939: 		}
1.841     albertel 9940: 	    }
                   9941: 	}
                   9942: 	return %result;
                   9943:     }
1.845     albertel 9944: 
1.1062    droeschl 9945:     sub get_unique_servers {
                   9946:         my %unique = reverse &get_servers(@_);
                   9947: 	return reverse %unique;
                   9948:     }
                   9949: 
1.844     albertel 9950:     sub host_domain {
1.852     albertel 9951: 	&load_hosts_tab() if (!$loaded);
                   9952: 
1.844     albertel 9953: 	my ($lonid) = @_;
                   9954: 	return $hostdom{$lonid};
                   9955:     }
                   9956: 
1.841     albertel 9957:     sub all_domains {
1.852     albertel 9958: 	&load_hosts_tab() if (!$loaded);
                   9959: 
1.841     albertel 9960: 	my %seen;
                   9961: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9962: 	return @uniq;
                   9963:     }
1.1074    raeburn  9964: 
                   9965:     sub internet_dom {
                   9966:         &load_hosts_tab() if (!$loaded);
                   9967: 
                   9968:         my ($lonid) = @_;
                   9969:         return $internetdom{$lonid};
                   9970:     }
1.1       albertel 9971: }
                   9972: 
1.847     albertel 9973: { 
                   9974:     my %iphost;
1.856     albertel 9975:     my %name_to_ip;
                   9976:     my %lonid_to_ip;
1.869     albertel 9977: 
1.847     albertel 9978:     sub get_hosts_from_ip {
                   9979: 	my ($ip) = @_;
                   9980: 	my %iphosts = &get_iphost();
                   9981: 	if (ref($iphosts{$ip})) {
                   9982: 	    return @{$iphosts{$ip}};
                   9983: 	}
                   9984: 	return;
1.839     albertel 9985:     }
1.864     albertel 9986:     
                   9987:     sub reset_hosts_ip_info {
                   9988: 	undef(%iphost);
                   9989: 	undef(%name_to_ip);
                   9990: 	undef(%lonid_to_ip);
                   9991:     }
1.856     albertel 9992: 
                   9993:     sub get_host_ip {
                   9994: 	my ($lonid) = @_;
                   9995: 	if (exists($lonid_to_ip{$lonid})) {
                   9996: 	    return $lonid_to_ip{$lonid};
                   9997: 	}
                   9998: 	my $name=&hostname($lonid);
                   9999:    	my $ip = gethostbyname($name);
                   10000: 	return if (!$ip || length($ip) ne 4);
                   10001: 	$ip=inet_ntoa($ip);
                   10002: 	$name_to_ip{$name}   = $ip;
                   10003: 	$lonid_to_ip{$lonid} = $ip;
                   10004: 	return $ip;
                   10005:     }
1.847     albertel 10006:     
                   10007:     sub get_iphost {
1.869     albertel 10008: 	my ($ignore_cache) = @_;
1.894     albertel 10009: 
1.869     albertel 10010: 	if (!$ignore_cache) {
                   10011: 	    if (%iphost) {
                   10012: 		return %iphost;
                   10013: 	    }
                   10014: 	    my ($ip_info,$cached)=
                   10015: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10016: 	    if ($cached) {
                   10017: 		%iphost      = %{$ip_info->[0]};
                   10018: 		%name_to_ip  = %{$ip_info->[1]};
                   10019: 		%lonid_to_ip = %{$ip_info->[2]};
                   10020: 		return %iphost;
                   10021: 	    }
                   10022: 	}
1.894     albertel 10023: 
                   10024: 	# get yesterday's info for fallback
                   10025: 	my %old_name_to_ip;
                   10026: 	my ($ip_info,$cached)=
                   10027: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10028: 	if ($cached) {
                   10029: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10030: 	}
                   10031: 
1.888     albertel 10032: 	my %name_to_host = &all_names();
                   10033: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10034: 	    my $ip;
                   10035: 	    if (!exists($name_to_ip{$name})) {
                   10036: 		$ip = gethostbyname($name);
                   10037: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10038: 		    if (defined($old_name_to_ip{$name})) {
                   10039: 			$ip = $old_name_to_ip{$name};
                   10040: 			&logthis("Can't find $name defaulting to old $ip");
                   10041: 		    } else {
                   10042: 			&logthis("Name $name no IP found");
                   10043: 			next;
                   10044: 		    }
                   10045: 		} else {
                   10046: 		    $ip=inet_ntoa($ip);
1.847     albertel 10047: 		}
                   10048: 		$name_to_ip{$name} = $ip;
                   10049: 	    } else {
                   10050: 		$ip = $name_to_ip{$name};
1.653     albertel 10051: 	    }
1.888     albertel 10052: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10053: 		$lonid_to_ip{$id} = $ip;
                   10054: 	    }
                   10055: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10056: 	}
1.869     albertel 10057: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10058: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10059: 				      48*60*60);
1.869     albertel 10060: 
1.847     albertel 10061: 	return %iphost;
1.598     albertel 10062:     }
                   10063: 
1.992     raeburn  10064:     #
                   10065:     #  Given a DNS returns the loncapa host name for that DNS 
                   10066:     # 
                   10067:     sub host_from_dns {
                   10068:         my ($dns) = @_;
                   10069:         my @hosts;
                   10070:         my $ip;
                   10071: 
1.993     raeburn  10072:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10073:             $ip = $name_to_ip{$dns};
                   10074:         }
                   10075:         if (!$ip) {
                   10076:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10077:             if (length($ip) == 4) { 
                   10078: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10079:             }
                   10080:         }
                   10081:         if ($ip) {
                   10082: 	    @hosts = get_hosts_from_ip($ip);
                   10083: 	    return $hosts[0];
                   10084:         }
                   10085:         return undef;
1.986     foxr     10086:     }
1.992     raeburn  10087: 
1.1074    raeburn  10088:     sub get_internet_names {
                   10089:         my ($lonid) = @_;
                   10090:         return if ($lonid eq '');
                   10091:         my ($idnref,$cached)=
                   10092:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10093:         if ($cached) {
                   10094:             return $idnref;
                   10095:         }
                   10096:         my $ip = &get_host_ip($lonid);
                   10097:         my @hosts = &get_hosts_from_ip($ip);
                   10098:         my %iphost = &get_iphost();
                   10099:         my (@idns,%seen);
                   10100:         foreach my $id (@hosts) {
                   10101:             my $dom = &host_domain($id);
                   10102:             my $prim_id = &domain($dom,'primary');
                   10103:             my $prim_ip = &get_host_ip($prim_id);
                   10104:             next if ($seen{$prim_ip});
                   10105:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10106:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10107:                     my $intdom = &internet_dom($id);
                   10108:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10109:                         push(@idns,$intdom);
                   10110:                     }
                   10111:                 }
                   10112:             }
                   10113:             $seen{$prim_ip} = 1;
                   10114:         }
                   10115:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10116:     }
                   10117: 
1.986     foxr     10118: }
                   10119: 
1.862     albertel 10120: BEGIN {
                   10121: 
                   10122: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10123:     unless ($readit) {
                   10124: {
                   10125:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10126:     %perlvar = (%perlvar,%{$configvars});
                   10127: }
                   10128: 
                   10129: 
1.1       albertel 10130: # ------------------------------------------------------ Read spare server file
                   10131: {
1.448     albertel 10132:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10133: 
                   10134:     while (my $configline=<$config>) {
                   10135:        chomp($configline);
1.284     matthew  10136:        if ($configline) {
1.784     albertel 10137: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10138: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10139: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10140:        }
                   10141:     }
1.448     albertel 10142:     close($config);
1.1       albertel 10143: }
1.11      www      10144: # ------------------------------------------------------------ Read permissions
                   10145: {
1.448     albertel 10146:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10147: 
                   10148:     while (my $configline=<$config>) {
1.448     albertel 10149: 	chomp($configline);
                   10150: 	if ($configline) {
                   10151: 	    my ($role,$perm)=split(/ /,$configline);
                   10152: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10153: 	}
1.11      www      10154:     }
1.448     albertel 10155:     close($config);
1.11      www      10156: }
                   10157: 
                   10158: # -------------------------------------------- Read plain texts for permissions
                   10159: {
1.448     albertel 10160:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10161: 
                   10162:     while (my $configline=<$config>) {
1.448     albertel 10163: 	chomp($configline);
                   10164: 	if ($configline) {
1.742     raeburn  10165: 	    my ($short,@plain)=split(/:/,$configline);
                   10166:             %{$prp{$short}} = ();
                   10167: 	    if (@plain > 0) {
                   10168:                 $prp{$short}{'std'} = $plain[0];
                   10169:                 for (my $i=1; $i<@plain; $i++) {
                   10170:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10171:                 }
                   10172:             }
1.448     albertel 10173: 	}
1.135     www      10174:     }
1.448     albertel 10175:     close($config);
1.135     www      10176: }
                   10177: 
                   10178: # ---------------------------------------------------------- Read package table
                   10179: {
1.448     albertel 10180:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10181: 
                   10182:     while (my $configline=<$config>) {
1.483     albertel 10183: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10184: 	chomp($configline);
                   10185: 	my ($short,$plain)=split(/:/,$configline);
                   10186: 	my ($pack,$name)=split(/\&/,$short);
                   10187: 	if ($plain ne '') {
                   10188: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10189: 	    $packagetab{$short}=$plain; 
                   10190: 	}
1.11      www      10191:     }
1.448     albertel 10192:     close($config);
1.329     matthew  10193: }
                   10194: 
1.1073    raeburn  10195: # ---------------------------------------------------------- Read loncaparev table
                   10196: {
                   10197:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10198:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10199:             while (my $configline=<$config>) {
                   10200:                 chomp($configline);
                   10201:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10202:                 $loncaparevs{$hostid}=$loncaparev;
                   10203:             }
                   10204:             close($config);
                   10205:         }
                   10206:     }
                   10207: }
                   10208: 
1.1074    raeburn  10209: # ---------------------------------------------------------- Read serverhostID table
                   10210: {
                   10211:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10212:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10213:             while (my $configline=<$config>) {
                   10214:                 chomp($configline);
                   10215:                 my ($name,$id)=split(/:/,$configline);
                   10216:                 $serverhomeIDs{$name}=$id;
                   10217:             }
                   10218:             close($config);
                   10219:         }
                   10220:     }
                   10221: }
                   10222: 
1.1073    raeburn  10223: sub all_loncaparevs {
                   10224:     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);
                   10225: }
                   10226: 
1.329     matthew  10227: # ------------- set up temporary directory
                   10228: {
                   10229:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10230: 
1.11      www      10231: }
                   10232: 
1.794     albertel 10233: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10234: 				'compress_threshold'=> 20_000,
                   10235:  			        });
1.185     www      10236: 
1.281     www      10237: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10238: $dumpcount=0;
1.958     www      10239: $locknum=0;
1.22      www      10240: 
1.163     harris41 10241: &logtouch();
1.672     albertel 10242: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10243: $readit=1;
1.564     albertel 10244:     {
                   10245: 	use integer;
                   10246: 	my $test=(2**32)+1;
1.568     albertel 10247: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10248: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10249:     }
1.195     www      10250: }
1.1       albertel 10251: }
1.179     www      10252: 
1.1       albertel 10253: 1;
1.191     harris41 10254: __END__
                   10255: 
1.243     albertel 10256: =pod
                   10257: 
1.191     harris41 10258: =head1 NAME
                   10259: 
1.243     albertel 10260: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10261: 
                   10262: =head1 SYNOPSIS
                   10263: 
1.243     albertel 10264: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10265: 
                   10266:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10267: 
1.243     albertel 10268: Common parameters:
                   10269: 
                   10270: =over 4
                   10271: 
                   10272: =item *
                   10273: 
                   10274: $uname : an internal username (if $cname expecting a course Id specifically)
                   10275: 
                   10276: =item *
                   10277: 
                   10278: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10279: 
                   10280: =item *
                   10281: 
                   10282: $symb : a resource instance identifier
                   10283: 
                   10284: =item *
                   10285: 
                   10286: $namespace : the name of a .db file that contains the data needed or
                   10287: being set.
                   10288: 
                   10289: =back
                   10290: 
1.394     bowersj2 10291: =head1 OVERVIEW
1.191     harris41 10292: 
1.394     bowersj2 10293: lonnet provides subroutines which interact with the
                   10294: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10295: about classes, users, and resources.
1.243     albertel 10296: 
                   10297: For many of these objects you can also use this to store data about
                   10298: them or modify them in various ways.
1.191     harris41 10299: 
1.394     bowersj2 10300: =head2 Symbs
1.191     harris41 10301: 
1.394     bowersj2 10302: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10303: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10304: map, the resource number of the resource in the map, and the URL of
                   10305: the resource itself. The latter is somewhat redundant, but might help
                   10306: if maps change.
                   10307: 
                   10308: An example is
                   10309: 
                   10310:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10311: 
                   10312: The respective map entry is
                   10313: 
                   10314:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10315:   title="Problem 2">
                   10316:  </resource>
                   10317: 
                   10318: Symbs are used by the random number generator, as well as to store and
                   10319: restore data specific to a certain instance of for example a problem.
                   10320: 
                   10321: =head2 Storing And Retrieving Data
                   10322: 
                   10323: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10324: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10325: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10326: is is the non-critical message twin of cstore. These functions are for
                   10327: handlers to store a perl hash to a user's permanent data space in an
                   10328: easy manner, and to retrieve it again on another call. It is expected
                   10329: that a handler would use this once at the beginning to retrieve data,
                   10330: and then again once at the end to send only the new data back.
                   10331: 
                   10332: The data is stored in the user's data directory on the user's
                   10333: homeserver under the ID of the course.
                   10334: 
                   10335: The hash that is returned by restore will have all of the previous
                   10336: value for all of the elements of the hash.
                   10337: 
                   10338: Example:
                   10339: 
                   10340:  #creating a hash
                   10341:  my %hash;
                   10342:  $hash{'foo'}='bar';
                   10343: 
                   10344:  #storing it
                   10345:  &Apache::lonnet::cstore(\%hash);
                   10346: 
                   10347:  #changing a value
                   10348:  $hash{'foo'}='notbar';
                   10349: 
                   10350:  #adding a new value
                   10351:  $hash{'bar'}='foo';
                   10352:  &Apache::lonnet::cstore(\%hash);
                   10353: 
                   10354:  #retrieving the hash
                   10355:  my %history=&Apache::lonnet::restore();
                   10356: 
                   10357:  #print the hash
                   10358:  foreach my $key (sort(keys(%history))) {
                   10359:    print("\%history{$key} = $history{$key}");
                   10360:  }
                   10361: 
                   10362: Will print out:
1.191     harris41 10363: 
1.394     bowersj2 10364:  %history{1:foo} = bar
                   10365:  %history{1:keys} = foo:timestamp
                   10366:  %history{1:timestamp} = 990455579
                   10367:  %history{2:bar} = foo
                   10368:  %history{2:foo} = notbar
                   10369:  %history{2:keys} = foo:bar:timestamp
                   10370:  %history{2:timestamp} = 990455580
                   10371:  %history{bar} = foo
                   10372:  %history{foo} = notbar
                   10373:  %history{timestamp} = 990455580
                   10374:  %history{version} = 2
                   10375: 
                   10376: Note that the special hash entries C<keys>, C<version> and
                   10377: C<timestamp> were added to the hash. C<version> will be equal to the
                   10378: total number of versions of the data that have been stored. The
                   10379: C<timestamp> attribute will be the UNIX time the hash was
                   10380: stored. C<keys> is available in every historical section to list which
                   10381: keys were added or changed at a specific historical revision of a
                   10382: hash.
                   10383: 
                   10384: B<Warning>: do not store the hash that restore returns directly. This
                   10385: will cause a mess since it will restore the historical keys as if the
                   10386: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10387: 
1.394     bowersj2 10388: Calling convention:
1.191     harris41 10389: 
1.394     bowersj2 10390:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10391:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10392: 
1.394     bowersj2 10393: For more detailed information, see lonnet specific documentation.
1.191     harris41 10394: 
1.394     bowersj2 10395: =head1 RETURN MESSAGES
1.191     harris41 10396: 
1.394     bowersj2 10397: =over 4
1.191     harris41 10398: 
1.394     bowersj2 10399: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10400: 
1.394     bowersj2 10401: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10402: when the connection is brought back up
1.191     harris41 10403: 
1.394     bowersj2 10404: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10405: for later delivery
1.191     harris41 10406: 
1.967     bisitz   10407: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10408: 
1.394     bowersj2 10409: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10410: that was requested
1.191     harris41 10411: 
1.243     albertel 10412: =back
1.191     harris41 10413: 
1.243     albertel 10414: =head1 PUBLIC SUBROUTINES
1.191     harris41 10415: 
1.243     albertel 10416: =head2 Session Environment Functions
1.191     harris41 10417: 
1.243     albertel 10418: =over 4
1.191     harris41 10419: 
1.394     bowersj2 10420: =item * 
                   10421: X<appenv()>
1.949     raeburn  10422: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10423: the user envirnoment file, and will be restored for each access this
1.620     albertel 10424: user makes during this session, also modifies the %env for the current
1.949     raeburn  10425: process. Optional rolesarrayref - if defined contains a reference to an array
                   10426: of roles which are exempt from the restriction on modifying user.role entries 
                   10427: in the user's environment.db and in %env.    
1.191     harris41 10428: 
                   10429: =item *
1.394     bowersj2 10430: X<delenv()>
1.987     raeburn  10431: B<delenv($delthis,$regexp)>: removes all items from the session
                   10432: environment file that begin with $delthis. If the 
                   10433: optional second arg - $regexp - is true, $delthis is treated as a 
                   10434: regular expression, otherwise \Q$delthis\E is used. 
                   10435: The values are also deleted from the current processes %env.
1.191     harris41 10436: 
1.795     albertel 10437: =item * get_env_multiple($name) 
                   10438: 
                   10439: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10440: values may be defined and end up as an array ref.
                   10441: 
                   10442: returns an array of values
                   10443: 
1.243     albertel 10444: =back
                   10445: 
                   10446: =head2 User Information
1.191     harris41 10447: 
1.243     albertel 10448: =over 4
1.191     harris41 10449: 
                   10450: =item *
1.394     bowersj2 10451: X<queryauthenticate()>
                   10452: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10453: authentication scheme
                   10454: 
                   10455: =item *
1.394     bowersj2 10456: X<authenticate()>
1.1073    raeburn  10457: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10458: authenticate user from domain's lib servers (first use the current
                   10459: one). C<$upass> should be the users password.
1.1073    raeburn  10460: $checkdefauth is optional (value is 1 if a check should be made to
                   10461:    authenticate user using default authentication method, and allow
                   10462:    account creation if username does not have account in the domain).
                   10463: $clientcancheckhost is optional (value is 1 if checking whether the
                   10464:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10465: 
                   10466: =item *
1.394     bowersj2 10467: X<homeserver()>
                   10468: B<homeserver($uname,$udom)>: find the server which has
                   10469: the user's directory and files (there must be only one), this caches
                   10470: the answer, and also caches if there is a borken connection.
1.191     harris41 10471: 
                   10472: =item *
1.394     bowersj2 10473: X<idget()>
                   10474: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10475: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10476: username, and only 1 username per ID in a specific domain) (returns
                   10477: hash: id=>name,id=>name)
1.191     harris41 10478: 
                   10479: =item *
1.394     bowersj2 10480: X<idrget()>
                   10481: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10482: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10483: 
                   10484: =item *
1.394     bowersj2 10485: X<idput()>
                   10486: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10487: 
                   10488: =item *
1.394     bowersj2 10489: X<rolesinit()>
                   10490: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10491: 
                   10492: =item *
1.551     albertel 10493: X<getsection()>
                   10494: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10495: course $cname, return section name/number or '' for "not in course"
                   10496: and '-1' for "no section"
                   10497: 
                   10498: =item *
1.394     bowersj2 10499: X<userenvironment()>
                   10500: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10501: passed in @what from the requested user's environment, returns a hash
                   10502: 
1.858     raeburn  10503: =item * 
                   10504: X<userlog_query()>
1.859     albertel 10505: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10506: activity.log file. %filters defines filters applied when parsing the
                   10507: log file. These can be start or end timestamps, or the type of action
                   10508: - log to look for Login or Logout events, check for Checkin or
                   10509: Checkout, role for role selection. The response is in the form
                   10510: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10511: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10512: 
1.243     albertel 10513: =back
                   10514: 
                   10515: =head2 User Roles
                   10516: 
                   10517: =over 4
                   10518: 
                   10519: =item *
                   10520: 
1.810     raeburn  10521: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10522:  F: full access
                   10523:  U,I,K: authentication modes (cxx only)
                   10524:  '': forbidden
                   10525:  1: user needs to choose course
                   10526:  2: browse allowed
1.766     albertel 10527:  A: passphrase authentication needed
1.243     albertel 10528: 
                   10529: =item *
                   10530: 
                   10531: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10532: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10533: and course level
                   10534: 
                   10535: =item *
                   10536: 
1.988     raeburn  10537: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10538: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10539: $type is Course (default) or Community.
1.988     raeburn  10540: If $forcedefault evaluates to true, text returned will be default 
                   10541: text for $type. Otherwise, if this is a course, the text returned 
                   10542: will be a custom name for the role (if defined in the course's 
                   10543: environment).  If no custom name is defined the default is returned.
                   10544:    
1.832     raeburn  10545: =item *
                   10546: 
1.935     raeburn  10547: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10548: All arguments are optional. Returns a hash of a roles, either for
                   10549: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10550: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10551: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10552: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10553: For each key, value is set to colon-separated start and end times for
                   10554: the role.  If no username and domain are specified, will default to
1.934     raeburn  10555: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10556: of role statuses (active, future or previous), roles 
                   10557: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10558: to restrict the list of roles reported. If no array ref is 
                   10559: provided for types, will default to return only active roles.
1.834     albertel 10560: 
1.243     albertel 10561: =back
                   10562: 
                   10563: =head2 User Modification
                   10564: 
                   10565: =over 4
                   10566: 
                   10567: =item *
                   10568: 
1.957     raeburn  10569: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10570: user for the level given by URL.  Optional start and end dates (leave empty
                   10571: string or zero for "no date")
1.191     harris41 10572: 
                   10573: =item *
                   10574: 
1.243     albertel 10575: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10576: change a users, password, possible return values are: ok,
                   10577: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10578: refused
1.191     harris41 10579: 
                   10580: =item *
                   10581: 
1.243     albertel 10582: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10583: 
                   10584: =item *
                   10585: 
1.1058    raeburn  10586: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10587:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10588: 
                   10589: will update user information (firstname,middlename,lastname,generation,
                   10590: permanentemail), and if forceid is true, student/employee ID also.
                   10591: A user's institutional affiliation(s) can also be updated.
                   10592: User information fields will not be overwritten with empty entries 
                   10593: unless the field is included in the $candelete array reference.
                   10594: This array is included when a single user is modified via "Manage Users",
                   10595: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10596: 
                   10597: =item *
                   10598: 
1.286     matthew  10599: modifystudent
                   10600: 
1.957     raeburn  10601: modify a student's enrollment and identification information.
1.286     matthew  10602: The course id is resolved based on the current users environment.  
                   10603: This means the envoking user must be a course coordinator or otherwise
                   10604: associated with a course.
                   10605: 
1.297     matthew  10606: This call is essentially a wrapper for lonnet::modifyuser and
                   10607: lonnet::modify_student_enrollment
1.286     matthew  10608: 
                   10609: Inputs: 
                   10610: 
                   10611: =over 4
                   10612: 
1.957     raeburn  10613: =item B<$udom> Student's loncapa domain
1.286     matthew  10614: 
1.957     raeburn  10615: =item B<$uname> Student's loncapa login name
1.286     matthew  10616: 
1.964     bisitz   10617: =item B<$uid> Student/Employee ID
1.286     matthew  10618: 
1.957     raeburn  10619: =item B<$umode> Student's authentication mode
1.286     matthew  10620: 
1.957     raeburn  10621: =item B<$upass> Student's password
1.286     matthew  10622: 
1.957     raeburn  10623: =item B<$first> Student's first name
1.286     matthew  10624: 
1.957     raeburn  10625: =item B<$middle> Student's middle name
1.286     matthew  10626: 
1.957     raeburn  10627: =item B<$last> Student's last name
1.286     matthew  10628: 
1.957     raeburn  10629: =item B<$gene> Student's generation
1.286     matthew  10630: 
1.957     raeburn  10631: =item B<$usec> Student's section in course
1.286     matthew  10632: 
                   10633: =item B<$end> Unix time of the roles expiration
                   10634: 
                   10635: =item B<$start> Unix time of the roles start date
                   10636: 
                   10637: =item B<$forceid> If defined, allow $uid to be changed
                   10638: 
                   10639: =item B<$desiredhome> server to use as home server for student
                   10640: 
1.957     raeburn  10641: =item B<$email> Student's permanent e-mail address
                   10642: 
                   10643: =item B<$type> Type of enrollment (auto or manual)
                   10644: 
1.963     raeburn  10645: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10646: 
                   10647: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10648: 
1.963     raeburn  10649: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10650: 
1.963     raeburn  10651: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10652: 
1.963     raeburn  10653: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10654: 
1.286     matthew  10655: =back
1.297     matthew  10656: 
                   10657: =item *
                   10658: 
                   10659: modify_student_enrollment
                   10660: 
                   10661: Change a students enrollment status in a class.  The environment variable
                   10662: 'role.request.course' must be defined for this function to proceed.
                   10663: 
                   10664: Inputs:
                   10665: 
                   10666: =over 4
                   10667: 
                   10668: =item $udom, students domain
                   10669: 
                   10670: =item $uname, students name
                   10671: 
                   10672: =item $uid, students user id
                   10673: 
                   10674: =item $first, students first name
                   10675: 
                   10676: =item $middle
                   10677: 
                   10678: =item $last
                   10679: 
                   10680: =item $gene
                   10681: 
                   10682: =item $usec
                   10683: 
                   10684: =item $end
                   10685: 
                   10686: =item $start
                   10687: 
1.957     raeburn  10688: =item $type
                   10689: 
                   10690: =item $locktype
                   10691: 
                   10692: =item $cid
                   10693: 
                   10694: =item $selfenroll
                   10695: 
                   10696: =item $context
                   10697: 
1.297     matthew  10698: =back
                   10699: 
1.191     harris41 10700: 
                   10701: =item *
                   10702: 
1.243     albertel 10703: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10704: custom role; give a custom role to a user for the level given by URL.  Specify
                   10705: name and domain of role author, and role name
1.191     harris41 10706: 
                   10707: =item *
                   10708: 
1.243     albertel 10709: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10710: 
                   10711: =item *
                   10712: 
1.243     albertel 10713: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10714: 
                   10715: =back
                   10716: 
                   10717: =head2 Course Infomation
                   10718: 
                   10719: =over 4
1.191     harris41 10720: 
                   10721: =item *
                   10722: 
1.631     albertel 10723: coursedescription($courseid) : returns a hash of information about the
                   10724: specified course id, including all environment settings for the
                   10725: course, the description of the course will be in the hash under the
                   10726: key 'description'
1.191     harris41 10727: 
                   10728: =item *
                   10729: 
1.624     albertel 10730: resdata($name,$domain,$type,@which) : request for current parameter
                   10731: setting for a specific $type, where $type is either 'course' or 'user',
                   10732: @what should be a list of parameters to ask about. This routine caches
                   10733: answers for 5 minutes.
1.243     albertel 10734: 
1.877     foxr     10735: =item *
                   10736: 
                   10737: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10738: data base, returning a hash that is keyed by the resource name and has
                   10739: values that are the resource value.  I believe that the timestamps and
                   10740: versions are also returned.
                   10741: 
                   10742: 
1.243     albertel 10743: =back
                   10744: 
                   10745: =head2 Course Modification
                   10746: 
                   10747: =over 4
1.191     harris41 10748: 
                   10749: =item *
                   10750: 
1.243     albertel 10751: writecoursepref($courseid,%prefs) : write preferences (environment
                   10752: database) for a course
1.191     harris41 10753: 
                   10754: =item *
                   10755: 
1.1011    raeburn  10756: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10757: 
                   10758: =item *
                   10759: 
1.1038    raeburn  10760: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10761: 
                   10762: =back
                   10763: 
                   10764: =head2 Resource Subroutines
                   10765: 
                   10766: =over 4
1.191     harris41 10767: 
                   10768: =item *
                   10769: 
1.243     albertel 10770: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10771: 
                   10772: =item *
                   10773: 
1.243     albertel 10774: repcopy($filename) : subscribes to the requested file, and attempts to
                   10775: replicate from the owning library server, Might return
1.607     raeburn  10776: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10777: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10778: resource. Expects the local filesystem pathname
                   10779: (/home/httpd/html/res/....)
                   10780: 
                   10781: =back
                   10782: 
                   10783: =head2 Resource Information
                   10784: 
                   10785: =over 4
1.191     harris41 10786: 
                   10787: =item *
                   10788: 
1.243     albertel 10789: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10790: a vairety of different possible values, $varname should be a request
                   10791: string, and the other parameters can be used to specify who and what
                   10792: one is asking about.
                   10793: 
                   10794: Possible values for $varname are environment.lastname (or other item
                   10795: from the envirnment hash), user.name (or someother aspect about the
                   10796: user), resource.0.maxtries (or some other part and parameter of a
                   10797: resource)
1.204     albertel 10798: 
                   10799: =item *
                   10800: 
1.243     albertel 10801: directcondval($number) : get current value of a condition; reads from a state
                   10802: string
1.204     albertel 10803: 
                   10804: =item *
                   10805: 
1.243     albertel 10806: condval($condidx) : value of condition index based on state
1.204     albertel 10807: 
                   10808: =item *
                   10809: 
1.243     albertel 10810: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10811: resource's metadata, $what should be either a specific key, or either
                   10812: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10813: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10814: 
                   10815: this function automatically caches all requests
1.191     harris41 10816: 
                   10817: =item *
                   10818: 
1.243     albertel 10819: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10820: network of library servers; returns file handle of where SQL and regex results
                   10821: will be stored for query
1.191     harris41 10822: 
                   10823: =item *
                   10824: 
1.243     albertel 10825: symbread($filename) : return symbolic list entry (filename argument optional);
                   10826: returns the data handle
1.191     harris41 10827: 
                   10828: =item *
                   10829: 
1.243     albertel 10830: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10831: a possible symb for the URL in $thisfn, and if is an encryypted
                   10832: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10833: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10834: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10835: 
1.191     harris41 10836: 
                   10837: =item *
                   10838: 
1.243     albertel 10839: symbclean($symb) : removes versions numbers from a symb, returns the
                   10840: cleaned symb
1.191     harris41 10841: 
                   10842: =item *
                   10843: 
1.243     albertel 10844: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10845: course map, user must be in a course for it to work.
1.191     harris41 10846: 
                   10847: =item *
                   10848: 
1.243     albertel 10849: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10850: 
                   10851: =item *
                   10852: 
1.243     albertel 10853: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10854: a random seed, all arguments are optional, if they aren't sent it uses the
                   10855: environment to derive them. Note: if symb isn't sent and it can't get one
                   10856: from &symbread it will use the current time as its return value
1.191     harris41 10857: 
                   10858: =item *
                   10859: 
1.243     albertel 10860: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10861: unfakeable, receipt
1.191     harris41 10862: 
                   10863: =item *
                   10864: 
1.620     albertel 10865: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10866: 
                   10867: =item *
                   10868: 
1.243     albertel 10869: countacc($url) : count the number of accesses to a given URL
1.191     harris41 10870: 
                   10871: =item *
                   10872: 
1.243     albertel 10873: 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 10874: 
                   10875: =item *
                   10876: 
1.243     albertel 10877: 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 10878: 
                   10879: =item *
                   10880: 
1.243     albertel 10881: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 10882: 
                   10883: =item *
                   10884: 
1.243     albertel 10885: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10886: forcing spreadsheet to reevaluate the resource scores next time.
                   10887: 
                   10888: =back
                   10889: 
                   10890: =head2 Storing/Retreiving Data
                   10891: 
                   10892: =over 4
1.191     harris41 10893: 
                   10894: =item *
                   10895: 
1.243     albertel 10896: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   10897: for this url; hashref needs to be given and should be a \%hashname; the
                   10898: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 10899: be derived from the env
1.191     harris41 10900: 
                   10901: =item *
                   10902: 
1.243     albertel 10903: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   10904: uses critical subroutine
1.191     harris41 10905: 
                   10906: =item *
                   10907: 
1.243     albertel 10908: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   10909: all args are optional
1.191     harris41 10910: 
                   10911: =item *
                   10912: 
1.717     albertel 10913: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   10914: dumps the complete (or key matching regexp) namespace into a hash
                   10915: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   10916: normally &store()ed into
                   10917: 
                   10918: $range should be either an integer '100' (give me the first 100
                   10919:                                            matching records)
                   10920:               or be  two integers sperated by a - with no spaces
                   10921:                  '30-50' (give me the 30th through the 50th matching
                   10922:                           records)
                   10923: 
                   10924: 
                   10925: =item *
                   10926: 
                   10927: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   10928: replaces a &store() version of data with a replacement set of data
                   10929: for a particular resource in a namespace passed in the $storehash hash 
                   10930: reference
                   10931: 
                   10932: =item *
                   10933: 
1.243     albertel 10934: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   10935: works very similar to store/cstore, but all data is stored in a
                   10936: temporary location and can be reset using tmpreset, $storehash should
                   10937: be a hash reference, returns nothing on success
1.191     harris41 10938: 
                   10939: =item *
                   10940: 
1.243     albertel 10941: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   10942: similar to restore, but all data is stored in a temporary location and
                   10943: can be reset using tmpreset. Returns a hash of values on success,
                   10944: error string otherwise.
1.191     harris41 10945: 
                   10946: =item *
                   10947: 
1.243     albertel 10948: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   10949: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 10950: 
                   10951: =item *
                   10952: 
1.243     albertel 10953: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10954: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10955: 
                   10956: =item *
                   10957: 
1.243     albertel 10958: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10959: namesp ($udom and $uname are optional)
1.191     harris41 10960: 
                   10961: =item *
                   10962: 
1.702     albertel 10963: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10964: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10965: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10966: 
1.702     albertel 10967: $range should be either an integer '100' (give me the first 100
                   10968:                                            matching records)
                   10969:               or be  two integers sperated by a - with no spaces
                   10970:                  '30-50' (give me the 30th through the 50th matching
                   10971:                           records)
1.449     matthew  10972: =item *
                   10973: 
                   10974: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10975: $store can be a scalar, an array reference, or if the amount to be 
                   10976: incremented is > 1, a hash reference.
                   10977: 
                   10978: ($udom and $uname are optional)
1.191     harris41 10979: 
                   10980: =item *
                   10981: 
1.243     albertel 10982: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   10983: ($udom and $uname are optional)
1.191     harris41 10984: 
                   10985: =item *
                   10986: 
1.243     albertel 10987: cput($namespace,$storehash,$udom,$uname) : critical put
                   10988: ($udom and $uname are optional)
1.191     harris41 10989: 
                   10990: =item *
                   10991: 
1.748     albertel 10992: newput($namespace,$storehash,$udom,$uname) :
                   10993: 
                   10994: Attempts to store the items in the $storehash, but only if they don't
                   10995: currently exist, if this succeeds you can be certain that you have 
                   10996: successfully created a new key value pair in the $namespace db.
                   10997: 
                   10998: 
                   10999: Args:
                   11000:  $namespace: name of database to store values to
                   11001:  $storehash: hashref to store to the db
                   11002:  $udom: (optional) domain of user containing the db
                   11003:  $uname: (optional) name of user caontaining the db
                   11004: 
                   11005: Returns:
                   11006:  'ok' -> succeeded in storing all keys of $storehash
                   11007:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11008:                         least <key> already existed in the db (other
                   11009:                         requested keys may also already exist)
1.967     bisitz   11010:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11011:  'con_lost' -> unable to contact request server
                   11012:  'refused' -> action was not allowed by remote machine
                   11013: 
                   11014: 
                   11015: =item *
                   11016: 
1.243     albertel 11017: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11018: reference filled in from namesp (encrypts the return communication)
                   11019: ($udom and $uname are optional)
1.191     harris41 11020: 
                   11021: =item *
                   11022: 
1.243     albertel 11023: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11024: critical subroutine
                   11025: 
1.806     raeburn  11026: =item *
                   11027: 
1.860     raeburn  11028: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11029: array reference filled in from namespace found in domain level on either
                   11030: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11031: 
                   11032: =item *
                   11033: 
1.860     raeburn  11034: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11035: domain level either on specified domain server ($uhome) or primary domain 
                   11036: server ($udom and $uhome are optional)
1.806     raeburn  11037: 
1.943     raeburn  11038: =item * 
                   11039: 
                   11040: get_domain_defaults($target_domain) : returns hash with defaults for
                   11041: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11042: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11043: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11044: Values are retrieved from cache (if current), or from domain's configuration.db
                   11045: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11046: or lonTabs/domain.tab. 
                   11047: 
                   11048: %domdefaults = &get_auth_defaults($target_domain);
                   11049: 
1.243     albertel 11050: =back
                   11051: 
                   11052: =head2 Network Status Functions
                   11053: 
                   11054: =over 4
1.191     harris41 11055: 
                   11056: =item *
                   11057: 
                   11058: dirlist($uri) : return directory list based on URI
                   11059: 
                   11060: =item *
                   11061: 
1.243     albertel 11062: spareserver() : find server with least workload from spare.tab
                   11063: 
1.986     foxr     11064: 
                   11065: =item *
                   11066: 
                   11067: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11068: if there is no corresponding loncapa host.
                   11069: 
1.243     albertel 11070: =back
                   11071: 
1.986     foxr     11072: 
1.243     albertel 11073: =head2 Apache Request
                   11074: 
                   11075: =over 4
1.191     harris41 11076: 
                   11077: =item *
                   11078: 
1.243     albertel 11079: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11080: localhost, posts hash
                   11081: 
                   11082: =back
                   11083: 
                   11084: =head2 Data to String to Data
                   11085: 
                   11086: =over 4
1.191     harris41 11087: 
                   11088: =item *
                   11089: 
1.243     albertel 11090: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11091: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11092: 
                   11093: =item *
                   11094: 
1.243     albertel 11095: hashref2str($hashref) : convert a hashref into a string complete with
                   11096: escaping and '=' and '&' separators, supports elements that are
                   11097: arrayrefs and hashrefs
1.191     harris41 11098: 
                   11099: =item *
                   11100: 
1.243     albertel 11101: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11102: with escaping and '&' separators, supports elements that are arrayrefs
                   11103: and hashrefs
1.191     harris41 11104: 
                   11105: =item *
                   11106: 
1.243     albertel 11107: str2hash($string) : convert string to hash using unescaping and
                   11108: splitting on '=' and '&', supports elements that are arrayrefs and
                   11109: hashrefs
1.191     harris41 11110: 
                   11111: =item *
                   11112: 
1.243     albertel 11113: str2array($string) : convert string to hash using unescaping and
                   11114: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11115: 
                   11116: =back
                   11117: 
                   11118: =head2 Logging Routines
                   11119: 
                   11120: =over 4
                   11121: 
                   11122: These routines allow one to make log messages in the lonnet.log and
                   11123: lonnet.perm logfiles.
1.191     harris41 11124: 
                   11125: =item *
                   11126: 
1.243     albertel 11127: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11128: 
                   11129: =item *
                   11130: 
1.243     albertel 11131: logthis() : append message to the normal lonnet.log file, it gets
                   11132: preiodically rolled over and deleted.
1.191     harris41 11133: 
                   11134: =item *
                   11135: 
1.243     albertel 11136: logperm() : append a permanent message to lonnet.perm.log, this log
                   11137: file never gets deleted by any automated portion of the system, only
                   11138: messages of critical importance should go in here.
                   11139: 
                   11140: =back
                   11141: 
                   11142: =head2 General File Helper Routines
                   11143: 
                   11144: =over 4
1.191     harris41 11145: 
                   11146: =item *
                   11147: 
1.481     raeburn  11148: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11149: (a) files in /uploaded
                   11150:   (i) If a local copy of the file exists - 
                   11151:       compares modification date of local copy with last-modified date for 
                   11152:       definitive version stored on home server for course. If local copy is 
                   11153:       stale, requests a new version from the home server and stores it. 
                   11154:       If the original has been removed from the home server, then local copy 
                   11155:       is unlinked.
                   11156:   (ii) If local copy does not exist -
                   11157:       requests the file from the home server and stores it. 
                   11158:   
                   11159:   If $caller is 'uploadrep':  
                   11160:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11161:     for request for files originally uploaded via DOCS. 
                   11162:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11163:   
                   11164:   Otherwise:
                   11165:      This indicates a call from the content generation phase of the request.
                   11166:      -  returns the entire contents of the file or -1.
                   11167:      
                   11168: (b) files in /res
                   11169:    - returns the entire contents of a file or -1; 
                   11170:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11171: 
1.712     albertel 11172: 
                   11173: =item *
                   11174: 
                   11175: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11176:                   reference
                   11177: 
                   11178: returns either a stat() list of data about the file or an empty list
                   11179: if the file doesn't exist or couldn't find out about it (connection
                   11180: problems or user unknown)
                   11181: 
1.191     harris41 11182: =item *
                   11183: 
1.243     albertel 11184: filelocation($dir,$file) : returns file system location of a file
                   11185: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11186: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11187: and a file of ../bob will become /a/bob)
1.191     harris41 11188: 
                   11189: =item *
                   11190: 
                   11191: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11192: filelocation except for hrefs
                   11193: 
                   11194: =item *
                   11195: 
                   11196: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11197: 
1.243     albertel 11198: =back
                   11199: 
1.608     albertel 11200: =head2 Usererfile file routines (/uploaded*)
                   11201: 
                   11202: =over 4
                   11203: 
                   11204: =item *
                   11205: 
                   11206: userfileupload(): main rotine for putting a file in a user or course's
                   11207:                   filespace, arguments are,
                   11208: 
1.620     albertel 11209:  formname - required - this is the name of the element in $env where the
1.608     albertel 11210:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11211:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11212:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 11213:  coursedoc - if true, store the file in the course of the active role
                   11214:              of the current user
                   11215:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11216:          if undefined, it will be placed in "unknown"
                   11217: 
                   11218:  (This routine calls clean_filename() to remove any dangerous
                   11219:  characters from the filename, and then calls finuserfileupload() to
                   11220:  complete the transaction)
                   11221: 
                   11222:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11223:  and /adm/notfound.html if unsuccessful
                   11224: 
                   11225: =item *
                   11226: 
                   11227: clean_filename(): routine for cleaing a filename up for storage in
                   11228:                  userfile space, argument is:
                   11229: 
                   11230:  filename - proposed filename
                   11231: 
                   11232: returns: the new clean filename
                   11233: 
                   11234: =item *
                   11235: 
                   11236: finishuserfileupload(): routine that creaes and sends the file to
                   11237: userspace, probably shouldn't be called directly
                   11238: 
                   11239:   docuname: username or courseid of destination for the file
                   11240:   docudom: domain of user/course of destination for the file
                   11241:   formname: same as for userfileupload()
                   11242:   fname: filename (inculding subdirectories) for the file
                   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: renameuserfile(): renames an existing userfile to a new name
                   11250: 
                   11251:   Args:
                   11252:    docuname: username or courseid of destination for the file
                   11253:    docudom: domain of user/course of destination for the file
                   11254:    old: current file name (including any subdirs under userfiles)
                   11255:    new: desired file name (including any subdirs under userfiles)
                   11256: 
                   11257: =item *
                   11258: 
                   11259: mkdiruserfile(): creates a directory is a userfiles dir
                   11260: 
                   11261:   Args:
                   11262:    docuname: username or courseid of destination for the file
                   11263:    docudom: domain of user/course of destination for the file
                   11264:    dir: dir to create (including any subdirs under userfiles)
                   11265: 
                   11266: =item *
                   11267: 
                   11268: removeuserfile(): removes a file that exists in userfiles
                   11269: 
                   11270:   Args:
                   11271:    docuname: username or courseid of destination for the file
                   11272:    docudom: domain of user/course of destination for the file
                   11273:    fname: filname to delete (including any subdirs under userfiles)
                   11274: 
                   11275: =item *
                   11276: 
                   11277: removeuploadedurl(): convience function for removeuserfile()
                   11278: 
                   11279:   Args:
                   11280:    url:  a full /uploaded/... url to delete
                   11281: 
1.747     albertel 11282: =item * 
                   11283: 
                   11284: get_portfile_permissions():
                   11285:   Args:
                   11286:     domain: domain of user or course contain the portfolio files
                   11287:     user: name of user or num of course contain the portfolio files
                   11288:   Returns:
                   11289:     hashref of a dump of the proper file_permissions.db
                   11290:    
                   11291: 
                   11292: =item * 
                   11293: 
                   11294: get_access_controls():
                   11295: 
                   11296: Args:
                   11297:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11298:   group: (optional) the group you want the files associated with
                   11299:   file: (optional) the file you want access info on
                   11300: 
                   11301: Returns:
1.749     raeburn  11302:     a hash (keys are file names) of hashes containing
                   11303:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11304:         values are XML containing access control settings (see below) 
1.747     albertel 11305: 
                   11306: Internal notes:
                   11307: 
1.749     raeburn  11308:  access controls are stored in file_permissions.db as key=value pairs.
                   11309:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11310:         where scope -> public,guest,course,group,domains or users.
                   11311:               end -> UNIX time for end of access (0 -> no end date)
                   11312:               start -> UNIX time for start of access
                   11313: 
                   11314:     value -> XML description of access control
                   11315:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11316:             <start></start>
                   11317:             <end></end>
                   11318: 
                   11319:             <password></password>  for scope type = guest
                   11320: 
                   11321:             <domain></domain>     for scope type = course or group
                   11322:             <number></number>
                   11323:             <roles id="">
                   11324:              <role></role>
                   11325:              <access></access>
                   11326:              <section></section>
                   11327:              <group></group>
                   11328:             </roles>
                   11329: 
                   11330:             <dom></dom>         for scope type = domains
                   11331: 
                   11332:             <users>             for scope type = users
                   11333:              <user>
                   11334:               <uname></uname>
                   11335:               <udom></udom>
                   11336:              </user>
                   11337:             </users>
                   11338:            </scope> 
                   11339:               
                   11340:  Access data is also aggregated for each file in an additional key=value pair:
                   11341:  key -> path to file/file_name\0accesscontrol 
                   11342:  value -> reference to hash
                   11343:           hash contains key = value pairs
                   11344:           where key = uniqueID:scope_end_start
                   11345:                 value = UNIX time record was last updated
                   11346: 
                   11347:           Used to improve speed of look-ups of access controls for each file.  
                   11348:  
                   11349:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11350: 
                   11351: modify_access_controls():
                   11352: 
                   11353: Modifies access controls for a portfolio file
                   11354: Args
                   11355: 1. file name
                   11356: 2. reference to hash of required changes,
                   11357: 3. domain
                   11358: 4. username
                   11359:   where domain,username are the domain of the portfolio owner 
                   11360:   (either a user or a course) 
                   11361: 
                   11362: Returns:
                   11363: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11364: 2. result of deletions ('ok' or 'error', with error message).
                   11365: 3. reference to hash of any new or updated access controls.
                   11366: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11367:    key = integer (inbound ID)
                   11368:    value = uniqueID  
1.747     albertel 11369: 
1.608     albertel 11370: =back
                   11371: 
1.243     albertel 11372: =head2 HTTP Helper Routines
                   11373: 
                   11374: =over 4
                   11375: 
1.191     harris41 11376: =item *
                   11377: 
                   11378: escape() : unpack non-word characters into CGI-compatible hex codes
                   11379: 
                   11380: =item *
                   11381: 
                   11382: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11383: 
1.243     albertel 11384: =back
                   11385: 
                   11386: =head1 PRIVATE SUBROUTINES
                   11387: 
                   11388: =head2 Underlying communication routines (Shouldn't call)
                   11389: 
                   11390: =over 4
                   11391: 
                   11392: =item *
                   11393: 
                   11394: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11395: 
                   11396: =item *
                   11397: 
                   11398: reply() : uses subreply to send a message to remote machine, logs all failures
                   11399: 
                   11400: =item *
                   11401: 
                   11402: critical() : passes a critical message to another server; if cannot
                   11403: get through then place message in connection buffer directory and
                   11404: returns con_delayed, if incapable of saving message, returns
                   11405: con_failed
                   11406: 
                   11407: =item *
                   11408: 
                   11409: reconlonc() : tries to reconnect lonc client processes.
                   11410: 
                   11411: =back
                   11412: 
                   11413: =head2 Resource Access Logging
                   11414: 
                   11415: =over 4
                   11416: 
                   11417: =item *
                   11418: 
                   11419: flushcourselogs() : flush (save) buffer logs and access logs
                   11420: 
                   11421: =item *
                   11422: 
                   11423: courselog($what) : save message for course in hash
                   11424: 
                   11425: =item *
                   11426: 
                   11427: courseacclog($what) : save message for course using &courselog().  Perform
                   11428: special processing for specific resource types (problems, exams, quizzes, etc).
                   11429: 
1.191     harris41 11430: =item *
                   11431: 
                   11432: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11433: as a PerlChildExitHandler
1.243     albertel 11434: 
                   11435: =back
                   11436: 
                   11437: =head2 Other
                   11438: 
                   11439: =over 4
                   11440: 
                   11441: =item *
                   11442: 
                   11443: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11444: 
                   11445: =back
                   11446: 
                   11447: =cut
1.877     foxr     11448: 

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