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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.9! raeburn     4: # $Id: lonnet.pm,v 1.1056.4.8 2010/08/26 04:15:03 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.1056.4.5  raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
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.1056.4.3  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.1056.4.3  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'};
1.1056.4.7  raeburn   225:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   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;
1.1056.4.8  raeburn   233:                     $ua->timeout(4);
1.1056.4.3  raeburn   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;
1.1056.4.7  raeburn   241:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3  raeburn   242:                             $loncaparev = $1;
                    243:                         }
                    244:                     }
                    245:                 } else {
                    246:                     $loncaparev = $loncaparevs{$lonhost};
                    247:                 }
1.1056.4.7  raeburn   248:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   249:                 $loncaparev = $1;
                    250:             }
                    251:         }
                    252:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    253:     }
                    254: }
                    255: 
                    256: sub get_server_homeID {
                    257:     my ($hostname,$ignore_cache,$caller) = @_;
                    258:     unless ($ignore_cache) {
                    259:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993     raeburn   260:         if (defined($cached)) {
1.1056.4.3  raeburn   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:             }
1.993     raeburn   274:         }
1.1056.4.3  raeburn   275:         if ($serverhomeID eq '') {
                    276:             $serverhomeID = $machine_ids[-1];
                    277:         }
                    278:     } else {
                    279:         $serverhomeID = $serverhomeIDs{$hostname};
1.993     raeburn   280:     }
1.1056.4.3  raeburn   281:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993     raeburn   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: 
                    727: # ------------------------------------------ Fight off request when overloaded
                    728: 
                    729: sub overloaderror {
                    730:     my ($r,$checkserver)=@_;
                    731:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    732:     my $loadavg;
                    733:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  734:        open(my $loadfile,'/proc/loadavg');
1.283     www       735:        $loadavg=<$loadfile>;
                    736:        $loadavg =~ s/\s.*//g;
1.285     matthew   737:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  738:        close($loadfile);
1.283     www       739:     } else {
                    740:        $loadavg=&reply('load',$checkserver);
                    741:     }
1.285     matthew   742:     my $overload=$loadavg-100;
1.283     www       743:     if ($overload>0) {
1.285     matthew   744: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       745:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       746:         return 413;
1.283     www       747:     }    
                    748:     return '';
1.5       www       749: }
1.1       albertel  750: 
                    751: # ------------------------------ Find server with least workload from spare.tab
1.11      www       752: 
1.1       albertel  753: sub spareserver {
1.670     albertel  754:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  755:     my $spare_server;
1.370     albertel  756:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  757:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    758:                                                      :  $userloadpercent;
1.1056.4.8  raeburn   759:     my ($uint_dom,$remotesessions);
                    760:     if ($env{'user.domain'}) {
                    761:         my $uprimary_id = &Apache::lonnet::domain($env{'user.domain'},'primary');
                    762:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    763:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                    764:         $remotesessions = $udomdefaults{'remotesessions'};
                    765:     }
1.784     albertel  766:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8  raeburn   767:         if ($uint_dom) {
                    768:             next unless (&spare_can_host($env{'user.domain'},$uint_dom,
                    769:                                          $remotesessions,$try_server));
                    770:         }
1.784     albertel  771: 	($spare_server, $lowest_load) =
                    772: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    773:     }
                    774: 
                    775:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    776: 
                    777:     if (!$found_server) {
                    778: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8  raeburn   779:             if ($uint_dom) {
                    780:                 next unless (&spare_can_host($env{'user.domain'},$uint_dom,
                    781:                                              $remotesessions,$try_server));
                    782:             }
1.784     albertel  783: 	    ($spare_server, $lowest_load) =
                    784: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    785: 	}
                    786:     }
                    787: 
                    788:     if (!$want_server_name) {
1.968     raeburn   789:         my $protocol = 'http';
                    790:         if ($protocol{$spare_server} eq 'https') {
                    791:             $protocol = $protocol{$spare_server};
                    792:         }
1.1001    raeburn   793:         if (defined($spare_server)) {
                    794:             my $hostname = &hostname($spare_server);
1.1056.4.8  raeburn   795:             if (defined($hostname)) {
1.1001    raeburn   796: 	        $spare_server = $protocol.'://'.$hostname;
                    797:             }
                    798:         }
1.784     albertel  799:     }
                    800:     return $spare_server;
                    801: }
                    802: 
                    803: sub compare_server_load {
                    804:     my ($try_server, $spare_server, $lowest_load) = @_;
                    805: 
                    806:     my $loadans     = &reply('load',    $try_server);
                    807:     my $userloadans = &reply('userload',$try_server);
                    808: 
                    809:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3  raeburn   810:         return; #didn't get a number from the server
1.784     albertel  811:     }
                    812: 
                    813:     my $load;
                    814:     if ($loadans =~ /\d/) {
                    815: 	if ($userloadans =~ /\d/) {
                    816: 	    #both are numbers, pick the bigger one
                    817: 	    $load = ($loadans > $userloadans) ? $loadans 
                    818: 		                              : $userloadans;
1.411     albertel  819: 	} else {
1.784     albertel  820: 	    $load = $loadans;
1.411     albertel  821: 	}
1.784     albertel  822:     } else {
                    823: 	$load = $userloadans;
                    824:     }
                    825: 
                    826:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    827: 	$spare_server = $try_server;
                    828: 	$lowest_load  = $load;
1.370     albertel  829:     }
1.784     albertel  830:     return ($spare_server,$lowest_load);
1.202     matthew   831: }
1.914     albertel  832: 
                    833: # --------------------------- ask offload servers if user already has a session
                    834: sub find_existing_session {
                    835:     my ($udom,$uname) = @_;
                    836:     foreach my $try_server (@{ $spareid{'primary'} },
                    837: 			    @{ $spareid{'default'} }) {
                    838: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    839:     }
                    840:     return;
                    841: }
                    842: 
                    843: # -------------------------------- ask if server already has a session for user
                    844: sub has_user_session {
                    845:     my ($lonid,$udom,$uname) = @_;
                    846:     my $result = &reply(join(':','userhassession',
                    847: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    848:     return 1 if ($result eq 'ok');
                    849: 
                    850:     return 0;
                    851: }
                    852: 
1.1056.4.3  raeburn   853: # --------- determine least loaded server in a user's domain which allows login
                    854: 
                    855: sub choose_server {
                    856:     my ($udom) = @_;
                    857:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
                    858:     my %servers = &get_servers($udom);
                    859:     my $lowest_load = 30000;
                    860:     my ($login_host,$hostname);
                    861:     foreach my $lonhost (keys(%servers)) {
                    862:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    863:         if ($loginvia eq '') {
                    864:             ($login_host, $lowest_load) =
                    865:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    866:         }
                    867:     }
                    868:     if ($login_host ne '') {
                    869:         $hostname = $servers{$login_host};
                    870:     }
                    871:     return ($login_host,$hostname);
                    872: }
                    873: 
1.202     matthew   874: # --------------------------------------------- Try to change a user's password
                    875: 
                    876: sub changepass {
1.799     raeburn   877:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   878:     $currentpass = &escape($currentpass);
                    879:     $newpass     = &escape($newpass);
1.1030    raeburn   880:     my $lonhost = $perlvar{'lonHostID'};
                    881:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   882: 		       $server);
                    883:     if (! $answer) {
                    884: 	&logthis("No reply on password change request to $server ".
                    885: 		 "by $uname in domain $udom.");
                    886:     } elsif ($answer =~ "^ok") {
                    887:         &logthis("$uname in $udom successfully changed their password ".
                    888: 		 "on $server.");
                    889:     } elsif ($answer =~ "^pwchange_failure") {
                    890: 	&logthis("$uname in $udom was unable to change their password ".
                    891: 		 "on $server.  The action was blocked by either lcpasswd ".
                    892: 		 "or pwchange");
                    893:     } elsif ($answer =~ "^non_authorized") {
                    894:         &logthis("$uname in $udom did not get their password correct when ".
                    895: 		 "attempting to change it on $server.");
                    896:     } elsif ($answer =~ "^auth_mode_error") {
                    897:         &logthis("$uname in $udom attempted to change their password despite ".
                    898: 		 "not being locally or internally authenticated on $server.");
                    899:     } elsif ($answer =~ "^unknown_user") {
                    900:         &logthis("$uname in $udom attempted to change their password ".
                    901: 		 "on $server but were unable to because $server is not ".
                    902: 		 "their home server.");
                    903:     } elsif ($answer =~ "^refused") {
                    904: 	&logthis("$server refused to change $uname in $udom password because ".
                    905: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   906:     } elsif ($answer =~ "invalid_client") {
                    907:         &logthis("$server refused to change $uname in $udom password because ".
                    908:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   909:     }
                    910:     return $answer;
1.1       albertel  911: }
                    912: 
1.169     harris41  913: # ----------------------- Try to determine user's current authentication scheme
                    914: 
                    915: sub queryauthenticate {
                    916:     my ($uname,$udom)=@_;
1.456     albertel  917:     my $uhome=&homeserver($uname,$udom);
                    918:     if (!$uhome) {
                    919: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    920: 	return 'no_host';
                    921:     }
                    922:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    923:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    924: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  925:     }
1.456     albertel  926:     return $answer;
1.169     harris41  927: }
                    928: 
1.1       albertel  929: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       930: 
1.1       albertel  931: sub authenticate {
1.1056.4.3  raeburn   932:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  933:     $upass=&escape($upass);
                    934:     $uname= &LONCAPA::clean_username($uname);
1.836     www       935:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   936:     my $newhome;
1.836     www       937:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    938: # Maybe the machine was offline and only re-appeared again recently?
                    939:         &reconlonc();
                    940: # One more
1.952     raeburn   941: 	$uhome=&homeserver($uname,$udom,1);
                    942:         if (($uhome eq 'no_host') && $checkdefauth) {
                    943:             if (defined(&domain($udom,'primary'))) {
                    944:                 $newhome=&domain($udom,'primary');
                    945:             }
                    946:             if ($newhome ne '') {
                    947:                 $uhome = $newhome;
                    948:             }
                    949:         }
1.836     www       950: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    951: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   952: 	    return 'no_host';
                    953:         }
1.1       albertel  954:     }
1.1056.4.3  raeburn   955:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  956:     if ($answer eq 'authorized') {
1.952     raeburn   957:         if ($newhome) {
                    958:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    959:             return 'no_account_on_host'; 
                    960:         } else {
                    961:             &logthis("User $uname at $udom authorized by $uhome");
                    962:             return $uhome;
                    963:         }
1.471     albertel  964:     }
                    965:     if ($answer eq 'non_authorized') {
                    966: 	&logthis("User $uname at $udom rejected by $uhome");
                    967: 	return 'no_host'; 
1.9       www       968:     }
1.471     albertel  969:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  970:     return 'no_host';
                    971: }
                    972: 
1.1056.4.3  raeburn   973: sub can_host_session {
                    974:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
                    975:     my $canhost = 1;
                    976:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
                    977:     if (ref($remotesessions) eq 'HASH') {
                    978:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
                    979:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
                    980:                 $canhost = 0;
                    981:             } else {
                    982:                 $canhost = 1;
                    983:             }
                    984:         }
                    985:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
                    986:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
                    987:                 $canhost = 1;
                    988:             } else {
                    989:                 $canhost = 0;
                    990:             }
                    991:         }
                    992:         if ($canhost) {
                    993:             if ($remotesessions->{'version'} ne '') {
                    994:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                    995:                 if ($reqmajor ne '' && $reqminor ne '') {
                    996:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                    997:                         my $major = $1;
                    998:                         my $minor = $2;
                    999:                         if (($major < $reqmajor ) ||
                   1000:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1001:                             $canhost = 0;
                   1002:                         }
                   1003:                     } else {
                   1004:                         $canhost = 0;
                   1005:                     }
                   1006:                 }
                   1007:             }
                   1008:         }
                   1009:     }
                   1010:     if ($canhost) {
                   1011:         if (ref($hostedsessions) eq 'HASH') {
                   1012:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                   1013:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                   1014:                     $canhost = 0;
                   1015:                 } else {
                   1016:                     $canhost = 1;
                   1017:                 }
                   1018:             }
                   1019:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                   1020:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                   1021:                     $canhost = 1;
                   1022:                 } else {
                   1023:                     $canhost = 0;
                   1024:                 }
                   1025:             }
                   1026:         }
                   1027:     }
                   1028:     return $canhost;
                   1029: }
                   1030: 
1.1056.4.8  raeburn  1031: sub spare_can_host {
                   1032:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1033:     my $canhost=1;
                   1034:     my @intdoms;
                   1035:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1036:     if (ref($internet_names) eq 'ARRAY') {
                   1037:         @intdoms = @{$internet_names};
                   1038:     }
                   1039:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1040:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1041:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1042:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1043:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1044:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1045:                                      $remotesessions,
                   1046:                                      $defdomdefaults{'hostedsessions'});
                   1047:     }
                   1048:     return $canhost;
                   1049: }
                   1050: 
1.1       albertel 1051: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1052: 
1.599     albertel 1053: my %homecache;
1.1       albertel 1054: sub homeserver {
1.230     stredwic 1055:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1056:     my $index="$uname:$udom";
1.426     albertel 1057: 
1.599     albertel 1058:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1059: 
                   1060:     my %servers = &get_servers($udom,'library');
                   1061:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1062:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1063: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1064: 
                   1065: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1066: 	if ($answer eq 'found') {
                   1067: 	    delete($badServerCache{$tryserver}); 
                   1068: 	    return $homecache{$index}=$tryserver;
                   1069: 	} elsif ($answer eq 'no_host') {
                   1070: 	    $badServerCache{$tryserver}=1;
                   1071: 	}
1.1       albertel 1072:     }    
                   1073:     return 'no_host';
1.70      www      1074: }
                   1075: 
                   1076: # ------------------------------------- Find the usernames behind a list of IDs
                   1077: 
                   1078: sub idget {
                   1079:     my ($udom,@ids)=@_;
                   1080:     my %returnhash=();
                   1081:     
1.841     albertel 1082:     my %servers = &get_servers($udom,'library');
                   1083:     foreach my $tryserver (keys(%servers)) {
                   1084: 	my $idlist=join('&',@ids);
                   1085: 	$idlist=~tr/A-Z/a-z/; 
                   1086: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1087: 	my @answer=();
                   1088: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1089: 	    @answer=split(/\&/,$reply);
                   1090: 	}                    ;
                   1091: 	my $i;
                   1092: 	for ($i=0;$i<=$#ids;$i++) {
                   1093: 	    if ($answer[$i]) {
                   1094: 		$returnhash{$ids[$i]}=$answer[$i];
                   1095: 	    } 
                   1096: 	}
                   1097:     } 
1.70      www      1098:     return %returnhash;
                   1099: }
                   1100: 
                   1101: # ------------------------------------- Find the IDs behind a list of usernames
                   1102: 
                   1103: sub idrget {
                   1104:     my ($udom,@unames)=@_;
                   1105:     my %returnhash=();
1.800     albertel 1106:     foreach my $uname (@unames) {
                   1107:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1108:     }
1.70      www      1109:     return %returnhash;
                   1110: }
                   1111: 
                   1112: # ------------------------------- Store away a list of names and associated IDs
                   1113: 
                   1114: sub idput {
                   1115:     my ($udom,%ids)=@_;
                   1116:     my %servers=();
1.800     albertel 1117:     foreach my $uname (keys(%ids)) {
                   1118: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1119:         my $uhom=&homeserver($uname,$udom);
1.70      www      1120:         if ($uhom ne 'no_host') {
1.800     albertel 1121:             my $id=&escape($ids{$uname});
1.70      www      1122:             $id=~tr/A-Z/a-z/;
1.800     albertel 1123:             my $esc_unam=&escape($uname);
1.70      www      1124: 	    if ($servers{$uhom}) {
1.800     albertel 1125: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1126:             } else {
1.800     albertel 1127:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1128:             }
                   1129:         }
1.191     harris41 1130:     }
1.800     albertel 1131:     foreach my $server (keys(%servers)) {
                   1132:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1133:     }
1.344     www      1134: }
                   1135: 
1.1023    raeburn  1136: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1137: sub dump_dom {
1.1023    raeburn  1138:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1139:     if (!$udom) {
                   1140:         $udom=$env{'user.domain'};
                   1141:     }
                   1142:     my %returnhash;
1.1023    raeburn  1143:     if ($udom) {
                   1144:         my $uname = &get_domainconfiguser($udom);
                   1145:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1146:     }
                   1147:     return %returnhash;
                   1148: }
                   1149: 
1.1023    raeburn  1150: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1151: 
                   1152: sub get_dom {
1.860     raeburn  1153:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1154:     my $items='';
                   1155:     foreach my $item (@$storearr) {
                   1156:         $items.=&escape($item).'&';
                   1157:     }
                   1158:     $items=~s/\&$//;
1.860     raeburn  1159:     if (!$udom) {
                   1160:         $udom=$env{'user.domain'};
                   1161:         if (defined(&domain($udom,'primary'))) {
                   1162:             $uhome=&domain($udom,'primary');
                   1163:         } else {
1.874     albertel 1164:             undef($uhome);
1.860     raeburn  1165:         }
                   1166:     } else {
                   1167:         if (!$uhome) {
                   1168:             if (defined(&domain($udom,'primary'))) {
                   1169:                 $uhome=&domain($udom,'primary');
                   1170:             }
                   1171:         }
                   1172:     }
                   1173:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1174:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1175:         my %returnhash;
1.875     albertel 1176:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1177:             return %returnhash;
                   1178:         }
1.806     raeburn  1179:         my @pairs=split(/\&/,$rep);
                   1180:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1181:             return @pairs;
                   1182:         }
                   1183:         my $i=0;
                   1184:         foreach my $item (@$storearr) {
                   1185:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1186:             $i++;
                   1187:         }
                   1188:         return %returnhash;
                   1189:     } else {
1.880     banghart 1190:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1191:     }
                   1192: }
                   1193: 
                   1194: # -------------------------------------------- put items in domain db files 
                   1195: 
                   1196: sub put_dom {
1.860     raeburn  1197:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1198:     if (!$udom) {
                   1199:         $udom=$env{'user.domain'};
                   1200:         if (defined(&domain($udom,'primary'))) {
                   1201:             $uhome=&domain($udom,'primary');
                   1202:         } else {
1.874     albertel 1203:             undef($uhome);
1.860     raeburn  1204:         }
                   1205:     } else {
                   1206:         if (!$uhome) {
                   1207:             if (defined(&domain($udom,'primary'))) {
                   1208:                 $uhome=&domain($udom,'primary');
                   1209:             }
                   1210:         }
                   1211:     } 
                   1212:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1213:         my $items='';
                   1214:         foreach my $item (keys(%$storehash)) {
                   1215:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1216:         }
                   1217:         $items=~s/\&$//;
                   1218:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1219:     } else {
1.860     raeburn  1220:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1221:     }
                   1222: }
                   1223: 
1.1023    raeburn  1224: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1225: sub newput_dom {
1.1023    raeburn  1226:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1227:     my $result;
                   1228:     if (!$udom) {
                   1229:         $udom=$env{'user.domain'};
                   1230:     }
1.1023    raeburn  1231:     if ($udom) {
                   1232:         my $uname = &get_domainconfiguser($udom);
                   1233:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1234:     }
                   1235:     return $result;
                   1236: }
                   1237: 
1.1023    raeburn  1238: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1239: sub del_dom {
1.1023    raeburn  1240:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1241:     if (ref($storearr) eq 'ARRAY') {
                   1242:         if (!$udom) {
                   1243:             $udom=$env{'user.domain'};
                   1244:         }
1.1023    raeburn  1245:         if ($udom) {
                   1246:             my $uname = &get_domainconfiguser($udom); 
                   1247:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1248:         }
                   1249:     }
                   1250: }
                   1251: 
1.1023    raeburn  1252: # ----------------------------------construct domainconfig user for a domain 
                   1253: sub get_domainconfiguser {
                   1254:     my ($udom) = @_;
                   1255:     return $udom.'-domainconfig';
                   1256: }
                   1257: 
1.837     raeburn  1258: sub retrieve_inst_usertypes {
                   1259:     my ($udom) = @_;
                   1260:     my (%returnhash,@order);
1.989     raeburn  1261:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1262:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1263:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1264:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1265:         @order = @{$domdefs{'inststatusorder'}};
                   1266:     } else {
                   1267:         if (defined(&domain($udom,'primary'))) {
                   1268:             my $uhome=&domain($udom,'primary');
                   1269:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1270:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1271:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1272:                 return (\%returnhash,\@order);
                   1273:             }
                   1274:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1275:             my @pairs=split(/\&/,$hashitems);
                   1276:             foreach my $item (@pairs) {
                   1277:                 my ($key,$value)=split(/=/,$item,2);
                   1278:                 $key = &unescape($key);
                   1279:                 next if ($key =~ /^error: 2 /);
                   1280:                 $returnhash{$key}=&thaw_unescape($value);
                   1281:             }
                   1282:             my @esc_order = split(/\&/,$orderitems);
                   1283:             foreach my $item (@esc_order) {
                   1284:                 push(@order,&unescape($item));
                   1285:             }
                   1286:         } else {
                   1287:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1288:         }
                   1289:     }
                   1290:     return (\%returnhash,\@order);
                   1291: }
                   1292: 
1.868     raeburn  1293: sub is_domainimage {
                   1294:     my ($url) = @_;
                   1295:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1296:         if (&domain($1) ne '') {
                   1297:             return '1';
                   1298:         }
                   1299:     }
                   1300:     return;
                   1301: }
                   1302: 
1.899     raeburn  1303: sub inst_directory_query {
                   1304:     my ($srch) = @_;
                   1305:     my $udom = $srch->{'srchdomain'};
                   1306:     my %results;
                   1307:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1308:     my $outcome;
1.899     raeburn  1309:     if ($homeserver ne '') {
1.904     albertel 1310: 	my $queryid=&reply("querysend:instdirsearch:".
                   1311: 			   &escape($srch->{'srchby'}).':'.
                   1312: 			   &escape($srch->{'srchterm'}).':'.
                   1313: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1314: 	my $host=&hostname($homeserver);
                   1315: 	if ($queryid !~/^\Q$host\E\_/) {
                   1316: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1317: 	    return;
                   1318: 	}
                   1319: 	my $response = &get_query_reply($queryid);
                   1320: 	my $maxtries = 5;
                   1321: 	my $tries = 1;
                   1322: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1323: 	    $response = &get_query_reply($queryid);
                   1324: 	    $tries ++;
                   1325: 	}
                   1326: 
                   1327:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1328:             if ($response eq 'unavailable') {
                   1329:                 $outcome = $response;
                   1330:             } else {
                   1331:                 $outcome = 'ok';
                   1332:                 my @matches = split(/\n/,$response);
                   1333:                 foreach my $match (@matches) {
                   1334:                     my ($key,$value) = split(/=/,$match);
                   1335:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1336:                 }
1.899     raeburn  1337:             }
                   1338:         }
                   1339:     }
1.909     raeburn  1340:     return ($outcome,%results);
1.899     raeburn  1341: }
                   1342: 
                   1343: sub usersearch {
                   1344:     my ($srch) = @_;
                   1345:     my $dom = $srch->{'srchdomain'};
                   1346:     my %results;
                   1347:     my %libserv = &all_library();
                   1348:     my $query = 'usersearch';
                   1349:     foreach my $tryserver (keys(%libserv)) {
                   1350:         if (&host_domain($tryserver) eq $dom) {
                   1351:             my $host=&hostname($tryserver);
                   1352:             my $queryid=
1.911     raeburn  1353:                 &reply("querysend:".&escape($query).':'.
                   1354:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1355:                        &escape($srch->{'srchtype'}).':'.
                   1356:                        &escape($srch->{'srchterm'}),$tryserver);
                   1357:             if ($queryid !~/^\Q$host\E\_/) {
                   1358:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1359:                 next;
1.899     raeburn  1360:             }
                   1361:             my $reply = &get_query_reply($queryid);
                   1362:             my $maxtries = 1;
                   1363:             my $tries = 1;
                   1364:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1365:                 $reply = &get_query_reply($queryid);
                   1366:                 $tries ++;
                   1367:             }
                   1368:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1369:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1370:             } else {
1.911     raeburn  1371:                 my @matches;
                   1372:                 if ($reply =~ /\n/) {
                   1373:                     @matches = split(/\n/,$reply);
                   1374:                 } else {
                   1375:                     @matches = split(/\&/,$reply);
                   1376:                 }
1.899     raeburn  1377:                 foreach my $match (@matches) {
                   1378:                     my ($uname,$udom,%userhash);
1.911     raeburn  1379:                     foreach my $entry (split(/:/,$match)) {
                   1380:                         my ($key,$value) =
                   1381:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1382:                         $userhash{$key} = $value;
                   1383:                         if ($key eq 'username') {
                   1384:                             $uname = $value;
                   1385:                         } elsif ($key eq 'domain') {
                   1386:                             $udom = $value;
1.911     raeburn  1387:                         }
1.899     raeburn  1388:                     }
                   1389:                     $results{$uname.':'.$udom} = \%userhash;
                   1390:                 }
                   1391:             }
                   1392:         }
                   1393:     }
                   1394:     return %results;
                   1395: }
                   1396: 
1.912     raeburn  1397: sub get_instuser {
                   1398:     my ($udom,$uname,$id) = @_;
                   1399:     my $homeserver = &domain($udom,'primary');
                   1400:     my ($outcome,%results);
                   1401:     if ($homeserver ne '') {
                   1402:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1403:                            &escape($id).':'.&escape($udom),$homeserver);
                   1404:         my $host=&hostname($homeserver);
                   1405:         if ($queryid !~/^\Q$host\E\_/) {
                   1406:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1407:             return;
                   1408:         }
                   1409:         my $response = &get_query_reply($queryid);
                   1410:         my $maxtries = 5;
                   1411:         my $tries = 1;
                   1412:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1413:             $response = &get_query_reply($queryid);
                   1414:             $tries ++;
                   1415:         }
                   1416:         if (!&error($response) && $response ne 'refused') {
                   1417:             if ($response eq 'unavailable') {
                   1418:                 $outcome = $response;
                   1419:             } else {
                   1420:                 $outcome = 'ok';
                   1421:                 my @matches = split(/\n/,$response);
                   1422:                 foreach my $match (@matches) {
                   1423:                     my ($key,$value) = split(/=/,$match);
                   1424:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1425:                 }
                   1426:             }
                   1427:         }
                   1428:     }
                   1429:     my %userinfo;
                   1430:     if (ref($results{$uname}) eq 'HASH') {
                   1431:         %userinfo = %{$results{$uname}};
                   1432:     } 
                   1433:     return ($outcome,%userinfo);
                   1434: }
                   1435: 
                   1436: sub inst_rulecheck {
1.923     raeburn  1437:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1438:     my %returnhash;
                   1439:     if ($udom ne '') {
                   1440:         if (ref($rules) eq 'ARRAY') {
                   1441:             @{$rules} = map {&escape($_);} (@{$rules});
                   1442:             my $rulestr = join(':',@{$rules});
                   1443:             my $homeserver=&domain($udom,'primary');
                   1444:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1445:                 my $response;
                   1446:                 if ($item eq 'username') {                
                   1447:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1448:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1449:                                               $homeserver));
1.923     raeburn  1450:                 } elsif ($item eq 'id') {
                   1451:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1452:                                               ':'.&escape($id).':'.$rulestr,
                   1453:                                               $homeserver));
1.945     raeburn  1454:                 } elsif ($item eq 'selfcreate') {
                   1455:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1456:                                                &escape($udom).':'.&escape($uname).
                   1457:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1458:                 }
1.912     raeburn  1459:                 if ($response ne 'refused') {
                   1460:                     my @pairs=split(/\&/,$response);
                   1461:                     foreach my $item (@pairs) {
                   1462:                         my ($key,$value)=split(/=/,$item,2);
                   1463:                         $key = &unescape($key);
                   1464:                         next if ($key =~ /^error: 2 /);
                   1465:                         $returnhash{$key}=&thaw_unescape($value);
                   1466:                     }
                   1467:                 }
                   1468:             }
                   1469:         }
                   1470:     }
                   1471:     return %returnhash;
                   1472: }
                   1473: 
                   1474: sub inst_userrules {
1.923     raeburn  1475:     my ($udom,$check) = @_;
1.912     raeburn  1476:     my (%ruleshash,@ruleorder);
                   1477:     if ($udom ne '') {
                   1478:         my $homeserver=&domain($udom,'primary');
                   1479:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1480:             my $response;
                   1481:             if ($check eq 'id') {
                   1482:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1483:                                  $homeserver);
1.943     raeburn  1484:             } elsif ($check eq 'email') {
                   1485:                 $response=&reply('instemailrules:'.&escape($udom),
                   1486:                                  $homeserver);
1.923     raeburn  1487:             } else {
                   1488:                 $response=&reply('instuserrules:'.&escape($udom),
                   1489:                                  $homeserver);
                   1490:             }
1.912     raeburn  1491:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1492:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1493:                 ($response ne 'no_such_host')) {
                   1494:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1495:                 my @pairs=split(/\&/,$hashitems);
                   1496:                 foreach my $item (@pairs) {
                   1497:                     my ($key,$value)=split(/=/,$item,2);
                   1498:                     $key = &unescape($key);
                   1499:                     next if ($key =~ /^error: 2 /);
                   1500:                     $ruleshash{$key}=&thaw_unescape($value);
                   1501:                 }
                   1502:                 my @esc_order = split(/\&/,$orderitems);
                   1503:                 foreach my $item (@esc_order) {
                   1504:                     push(@ruleorder,&unescape($item));
                   1505:                 }
                   1506:             }
                   1507:         }
                   1508:     }
                   1509:     return (\%ruleshash,\@ruleorder);
                   1510: }
                   1511: 
1.976     raeburn  1512: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1513: 
                   1514: sub get_domain_defaults {
                   1515:     my ($domain) = @_;
                   1516:     my $cachetime = 60*60*24;
                   1517:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1518:     if (defined($cached)) {
                   1519:         if (ref($result) eq 'HASH') {
                   1520:             return %{$result};
                   1521:         }
                   1522:     }
                   1523:     my %domdefaults;
                   1524:     my %domconfig =
1.989     raeburn  1525:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1526:                                   'requestcourses','inststatus',
1.1056.4.3  raeburn  1527:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1528:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1529:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1530:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1531:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1532:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1533:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1534:     } else {
                   1535:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1536:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1537:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1538:     }
1.976     raeburn  1539:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1540:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1541:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1542:         } else {
                   1543:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1544:         } 
                   1545:         my @usertools = ('aboutme','blog','portfolio');
                   1546:         foreach my $item (@usertools) {
                   1547:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1548:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1549:             }
                   1550:         }
                   1551:     }
1.985     raeburn  1552:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1553:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1554:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1555:         }
                   1556:     }
1.989     raeburn  1557:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1558:         foreach my $item ('inststatustypes','inststatusorder') {
                   1559:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1560:         }
                   1561:     }
1.1047    raeburn  1562:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1563:         foreach my $item ('canuse_pdfforms') {
                   1564:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1565:         }
                   1566:     }
1.1056.4.3  raeburn  1567:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1568:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1569:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1570:         }
                   1571:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1572:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1573:         }
                   1574:     }
1.943     raeburn  1575:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1576:                                   $cachetime);
                   1577:     return %domdefaults;
                   1578: }
                   1579: 
1.344     www      1580: # --------------------------------------------------- Assign a key to a student
                   1581: 
                   1582: sub assign_access_key {
1.364     www      1583: #
                   1584: # a valid key looks like uname:udom#comments
                   1585: # comments are being appended
                   1586: #
1.498     www      1587:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1588:     $kdom=
1.620     albertel 1589:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1590:     $knum=
1.620     albertel 1591:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1592:     $cdom=
1.620     albertel 1593:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1594:     $cnum=
1.620     albertel 1595:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1596:     $udom=$env{'user.name'} unless (defined($udom));
                   1597:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1598:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1599:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1600:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1601:                                                   # assigned to this person
                   1602:                                                   # - this should not happen,
1.345     www      1603:                                                   # unless something went wrong
                   1604:                                                   # the first time around
                   1605: # ready to assign
1.364     www      1606:         $logentry=$1.'; '.$logentry;
1.496     www      1607:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1608:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1609: # key now belongs to user
1.346     www      1610: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1611:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1612:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1613:                 return 'ok';
                   1614:             } else {
                   1615:                 return 
                   1616:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1617: 	    }
                   1618:         } else {
                   1619:             return 'error: Could not assign key, try again later.';
                   1620:         }
1.364     www      1621:     } elsif (!$existing{$ckey}) {
1.345     www      1622: # the key does not exist
                   1623: 	return 'error: The key does not exist';
                   1624:     } else {
                   1625: # the key is somebody else's
                   1626: 	return 'error: The key is already in use';
                   1627:     }
1.344     www      1628: }
                   1629: 
1.364     www      1630: # ------------------------------------------ put an additional comment on a key
                   1631: 
                   1632: sub comment_access_key {
                   1633: #
                   1634: # a valid key looks like uname:udom#comments
                   1635: # comments are being appended
                   1636: #
                   1637:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1638:     $cdom=
1.620     albertel 1639:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1640:     $cnum=
1.620     albertel 1641:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1642:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1643:     if ($existing{$ckey}) {
                   1644:         $existing{$ckey}.='; '.$logentry;
                   1645: # ready to assign
1.367     www      1646:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1647:                                                  $cdom,$cnum) eq 'ok') {
                   1648: 	    return 'ok';
                   1649:         } else {
                   1650: 	    return 'error: Count not store comment.';
                   1651:         }
                   1652:     } else {
                   1653: # the key does not exist
                   1654: 	return 'error: The key does not exist';
                   1655:     }
                   1656: }
                   1657: 
1.344     www      1658: # ------------------------------------------------------ Generate a set of keys
                   1659: 
                   1660: sub generate_access_keys {
1.364     www      1661:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1662:     $cdom=
1.620     albertel 1663:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1664:     $cnum=
1.620     albertel 1665:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1666:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1667:     unless (($cdom) && ($cnum)) { return 0; }
                   1668:     if ($number>10000) { return 0; }
                   1669:     sleep(2); # make sure don't get same seed twice
                   1670:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1671:     my $total=0;
                   1672:     for (my $i=1;$i<=$number;$i++) {
                   1673:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1674:                   sprintf("%lx",int(100000*rand)).'-'.
                   1675:                   sprintf("%lx",int(100000*rand));
                   1676:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1677:        $newkey=~s/0/h/g; # and also 0 and O
                   1678:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1679:        if ($existing{$newkey}) {
                   1680:            $i--;
                   1681:        } else {
1.364     www      1682: 	  if (&put('accesskeys',
                   1683:               { $newkey => '# generated '.localtime().
1.620     albertel 1684:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1685:                            '; '.$logentry },
                   1686: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1687:               $total++;
                   1688: 	  }
                   1689:        }
                   1690:     }
1.620     albertel 1691:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1692:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1693:     return $total;
                   1694: }
                   1695: 
                   1696: # ------------------------------------------------------- Validate an accesskey
                   1697: 
                   1698: sub validate_access_key {
                   1699:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1700:     $cdom=
1.620     albertel 1701:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1702:     $cnum=
1.620     albertel 1703:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1704:     $udom=$env{'user.domain'} unless (defined($udom));
                   1705:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1706:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1707:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1708: }
                   1709: 
                   1710: # ------------------------------------- Find the section of student in a course
1.652     albertel 1711: sub devalidate_getsection_cache {
                   1712:     my ($udom,$unam,$courseid)=@_;
                   1713:     my $hashid="$udom:$unam:$courseid";
                   1714:     &devalidate_cache_new('getsection',$hashid);
                   1715: }
1.298     matthew  1716: 
1.815     albertel 1717: sub courseid_to_courseurl {
                   1718:     my ($courseid) = @_;
                   1719:     #already url style courseid
                   1720:     return $courseid if ($courseid =~ m{^/});
                   1721: 
                   1722:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1723: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1724: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1725: 	return "/$cdom/$cnum";
                   1726:     }
                   1727: 
                   1728:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1729:     if (exists($courseinfo{'num'})) {
                   1730: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1731:     }
                   1732: 
                   1733:     return undef;
                   1734: }
                   1735: 
1.298     matthew  1736: sub getsection {
                   1737:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1738:     my $cachetime=1800;
1.551     albertel 1739: 
                   1740:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1741:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1742:     if (defined($cached)) { return $result; }
                   1743: 
1.298     matthew  1744:     my %Pending; 
                   1745:     my %Expired;
                   1746:     #
                   1747:     # Each role can either have not started yet (pending), be active, 
                   1748:     #    or have expired.
                   1749:     #
                   1750:     # If there is an active role, we are done.
                   1751:     #
                   1752:     # If there is more than one role which has not started yet, 
                   1753:     #     choose the one which will start sooner
                   1754:     # If there is one role which has not started yet, return it.
                   1755:     #
                   1756:     # If there is more than one expired role, choose the one which ended last.
                   1757:     # If there is a role which has expired, return it.
                   1758:     #
1.815     albertel 1759:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1760:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1761:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1762:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1763:         my $section=$1;
                   1764:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1765:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1766:         my $now=time;
1.548     albertel 1767:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1768:             $Expired{$end}=$section;
                   1769:             next;
                   1770:         }
1.548     albertel 1771:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1772:             $Pending{$start}=$section;
                   1773:             next;
                   1774:         }
1.599     albertel 1775:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1776:     }
                   1777:     #
                   1778:     # Presumedly there will be few matching roles from the above
                   1779:     # loop and the sorting time will be negligible.
                   1780:     if (scalar(keys(%Pending))) {
                   1781:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1782:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1783:     } 
                   1784:     if (scalar(keys(%Expired))) {
                   1785:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1786:         my $time = pop(@sorted);
1.599     albertel 1787:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1788:     }
1.599     albertel 1789:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1790: }
1.70      www      1791: 
1.599     albertel 1792: sub save_cache {
                   1793:     &purge_remembered();
1.722     albertel 1794:     #&Apache::loncommon::validate_page();
1.620     albertel 1795:     undef(%env);
1.780     albertel 1796:     undef($env_loaded);
1.599     albertel 1797: }
1.452     albertel 1798: 
1.599     albertel 1799: my $to_remember=-1;
                   1800: my %remembered;
                   1801: my %accessed;
                   1802: my $kicks=0;
                   1803: my $hits=0;
1.849     albertel 1804: sub make_key {
                   1805:     my ($name,$id) = @_;
1.872     albertel 1806:     if (length($id) > 65 
                   1807: 	&& length(&escape($id)) > 200) {
                   1808: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1809:     }
1.849     albertel 1810:     return &escape($name.':'.$id);
                   1811: }
                   1812: 
1.599     albertel 1813: sub devalidate_cache_new {
                   1814:     my ($name,$id,$debug) = @_;
                   1815:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1816:     $id=&make_key($name,$id);
1.599     albertel 1817:     $memcache->delete($id);
                   1818:     delete($remembered{$id});
                   1819:     delete($accessed{$id});
                   1820: }
                   1821: 
                   1822: sub is_cached_new {
                   1823:     my ($name,$id,$debug) = @_;
1.849     albertel 1824:     $id=&make_key($name,$id);
1.599     albertel 1825:     if (exists($remembered{$id})) {
                   1826: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1827: 	$accessed{$id}=[&gettimeofday()];
                   1828: 	$hits++;
                   1829: 	return ($remembered{$id},1);
                   1830:     }
                   1831:     my $value = $memcache->get($id);
                   1832:     if (!(defined($value))) {
                   1833: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1834: 	return (undef,undef);
1.416     albertel 1835:     }
1.599     albertel 1836:     if ($value eq '__undef__') {
                   1837: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1838: 	$value=undef;
                   1839:     }
                   1840:     &make_room($id,$value,$debug);
                   1841:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1842:     return ($value,1);
                   1843: }
                   1844: 
                   1845: sub do_cache_new {
                   1846:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1847:     $id=&make_key($name,$id);
1.599     albertel 1848:     my $setvalue=$value;
                   1849:     if (!defined($setvalue)) {
                   1850: 	$setvalue='__undef__';
                   1851:     }
1.623     albertel 1852:     if (!defined($time) ) {
                   1853: 	$time=600;
                   1854:     }
1.599     albertel 1855:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1856:     my $result = $memcache->set($id,$setvalue,$time);
                   1857:     if (! $result) {
1.872     albertel 1858: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1859: 	$memcache->disconnect_all();
1.872     albertel 1860:     }
1.600     albertel 1861:     # need to make a copy of $value
1.919     albertel 1862:     &make_room($id,$value,$debug);
1.599     albertel 1863:     return $value;
                   1864: }
                   1865: 
                   1866: sub make_room {
                   1867:     my ($id,$value,$debug)=@_;
1.919     albertel 1868: 
                   1869:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1870:                                     : $value;
1.599     albertel 1871:     if ($to_remember<0) { return; }
                   1872:     $accessed{$id}=[&gettimeofday()];
                   1873:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1874:     my $to_kick;
                   1875:     my $max_time=0;
                   1876:     foreach my $other (keys(%accessed)) {
                   1877: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1878: 	    $to_kick=$other;
                   1879: 	    $max_time=&tv_interval($accessed{$other});
                   1880: 	}
                   1881:     }
                   1882:     delete($remembered{$to_kick});
                   1883:     delete($accessed{$to_kick});
                   1884:     $kicks++;
                   1885:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1886:     return;
                   1887: }
                   1888: 
1.599     albertel 1889: sub purge_remembered {
1.604     albertel 1890:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1891:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1892:     undef(%remembered);
                   1893:     undef(%accessed);
1.428     albertel 1894: }
1.70      www      1895: # ------------------------------------- Read an entry from a user's environment
                   1896: 
                   1897: sub userenvironment {
                   1898:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1899:     my $items;
                   1900:     foreach my $item (@what) {
                   1901:         $items.=&escape($item).'&';
                   1902:     }
                   1903:     $items=~s/\&$//;
1.70      www      1904:     my %returnhash=();
1.1009    raeburn  1905:     my $uhome = &homeserver($unam,$udom);
                   1906:     unless ($uhome eq 'no_host') {
                   1907:         my @answer=split(/\&/, 
                   1908:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1909:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1910:             return %returnhash;
                   1911:         }
1.1009    raeburn  1912:         my $i;
                   1913:         for ($i=0;$i<=$#what;$i++) {
                   1914: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1915:         }
1.70      www      1916:     }
                   1917:     return %returnhash;
1.1       albertel 1918: }
                   1919: 
1.617     albertel 1920: # ---------------------------------------------------------- Get a studentphoto
                   1921: sub studentphoto {
                   1922:     my ($udom,$unam,$ext) = @_;
                   1923:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1924:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1925:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1926:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1927:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1928:             } else {
                   1929:                 my ($result,$perm_reqd)=
1.707     albertel 1930: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1931:                 if ($result eq 'ok') {
                   1932:                     if (!($perm_reqd eq 'yes')) {
                   1933:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1934:                     }
                   1935:                 }
                   1936:             }
                   1937:         }
                   1938:     } else {
                   1939:         my ($result,$perm_reqd) = 
1.707     albertel 1940: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1941:         if ($result eq 'ok') {
                   1942:             if (!($perm_reqd eq 'yes')) {
                   1943:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1944:             }
                   1945:         }
                   1946:     }
                   1947:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1948: }
                   1949: 
                   1950: sub retrievestudentphoto {
                   1951:     my ($udom,$unam,$ext,$type) = @_;
                   1952:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1953:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1954:     if ($ret eq 'ok') {
                   1955:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1956:         if ($type eq 'thumbnail') {
                   1957:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1958:         }
                   1959:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1960:         return $tokenurl;
                   1961:     } else {
                   1962:         if ($type eq 'thumbnail') {
                   1963:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1964:         } else { 
                   1965:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1966:         }
1.617     albertel 1967:     }
                   1968: }
                   1969: 
1.263     www      1970: # -------------------------------------------------------------------- New chat
                   1971: 
                   1972: sub chatsend {
1.724     raeburn  1973:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1974:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1975:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1976:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1977:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1978: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1979: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1980: }
                   1981: 
                   1982: # ------------------------------------------ Find current version of a resource
                   1983: 
                   1984: sub getversion {
                   1985:     my $fname=&clutter(shift);
                   1986:     unless ($fname=~/^\/res\//) { return -1; }
                   1987:     return &currentversion(&filelocation('',$fname));
                   1988: }
                   1989: 
                   1990: sub currentversion {
                   1991:     my $fname=shift;
1.599     albertel 1992:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1993:     if (defined($cached)) { return $result; }
1.292     www      1994:     my $author=$fname;
                   1995:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1996:     my ($udom,$uname)=split(/\//,$author);
                   1997:     my $home=homeserver($uname,$udom);
                   1998:     if ($home eq 'no_host') { 
                   1999:         return -1; 
                   2000:     }
                   2001:     my $answer=reply("currentversion:$fname",$home);
                   2002:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2003: 	return -1;
                   2004:     }
1.599     albertel 2005:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      2006: }
                   2007: 
1.1       albertel 2008: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2009: 
1.1       albertel 2010: sub subscribe {
                   2011:     my $fname=shift;
1.761     raeburn  2012:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2013:     $fname=~s/[\n\r]//g;
1.1       albertel 2014:     my $author=$fname;
                   2015:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2016:     my ($udom,$uname)=split(/\//,$author);
                   2017:     my $home=homeserver($uname,$udom);
1.335     albertel 2018:     if ($home eq 'no_host') {
                   2019:         return 'not_found';
1.1       albertel 2020:     }
                   2021:     my $answer=reply("sub:$fname",$home);
1.64      www      2022:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2023: 	$answer.=' by '.$home;
                   2024:     }
1.1       albertel 2025:     return $answer;
                   2026: }
                   2027:     
1.8       www      2028: # -------------------------------------------------------------- Replicate file
                   2029: 
                   2030: sub repcopy {
                   2031:     my $filename=shift;
1.23      www      2032:     $filename=~s/\/+/\//g;
1.607     raeburn  2033:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2034:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2035:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2036: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2037: 	return &repcopy_userfile($filename);
                   2038:     }
1.532     albertel 2039:     $filename=~s/[\n\r]//g;
1.8       www      2040:     my $transname="$filename.in.transfer";
1.828     www      2041: # FIXME: this should flock
1.607     raeburn  2042:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2043:     my $remoteurl=subscribe($filename);
1.64      www      2044:     if ($remoteurl =~ /^con_lost by/) {
                   2045: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2046:            return 'unavailable';
1.8       www      2047:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2048: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2049: 	   return 'not_found';
1.64      www      2050:     } elsif ($remoteurl =~ /^rejected by/) {
                   2051: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2052:            return 'forbidden';
1.20      www      2053:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2054:            return 'ok';
1.8       www      2055:     } else {
1.290     www      2056:         my $author=$filename;
                   2057:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2058:         my ($udom,$uname)=split(/\//,$author);
                   2059:         my $home=homeserver($uname,$udom);
                   2060:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2061:            my @parts=split(/\//,$filename);
                   2062:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2063:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2064:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2065: 	       return 'bad_request';
1.8       www      2066:            }
                   2067:            my $count;
                   2068:            for ($count=5;$count<$#parts;$count++) {
                   2069:                $path.="/$parts[$count]";
                   2070:                if ((-e $path)!=1) {
                   2071: 		   mkdir($path,0777);
                   2072:                }
                   2073:            }
                   2074:            my $ua=new LWP::UserAgent;
                   2075:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2076:            my $response=$ua->request($request,$transname);
                   2077:            if ($response->is_error()) {
                   2078: 	       unlink($transname);
                   2079:                my $message=$response->status_line;
1.672     albertel 2080:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2081:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2082:                return 'unavailable';
1.8       www      2083:            } else {
1.16      www      2084: 	       if ($remoteurl!~/\.meta$/) {
                   2085:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2086:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2087:                   if ($mresponse->is_error()) {
                   2088: 		      unlink($filename.'.meta');
                   2089:                       &logthis(
1.672     albertel 2090:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2091:                   }
                   2092: 	       }
1.8       www      2093:                rename($transname,$filename);
1.607     raeburn  2094:                return 'ok';
1.8       www      2095:            }
1.290     www      2096:        }
1.8       www      2097:     }
1.330     www      2098: }
                   2099: 
                   2100: # ------------------------------------------------ Get server side include body
                   2101: sub ssi_body {
1.381     albertel 2102:     my ($filelink,%form)=@_;
1.606     matthew  2103:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2104:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2105:     }
1.953     www      2106:     my $output='';
                   2107:     my $response;
1.980     raeburn  2108:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2109:        ($output,$response)=&externalssi($filelink);
1.953     www      2110:     } else {
1.1004    droeschl 2111:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2112:        $filelink .= 'inhibitmenu=yes';
1.953     www      2113:        ($output,$response)=&ssi($filelink,%form);
                   2114:     }
1.778     albertel 2115:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2116:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2117:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2118:     if (wantarray) {
                   2119:         return ($output, $response);
                   2120:     } else {
                   2121:         return $output;
                   2122:     }
1.8       www      2123: }
                   2124: 
1.15      www      2125: # --------------------------------------------------------- Server Side Include
                   2126: 
1.782     albertel 2127: sub absolute_url {
                   2128:     my ($host_name) = @_;
                   2129:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2130:     if ($host_name eq '') {
                   2131: 	$host_name = $ENV{'SERVER_NAME'};
                   2132:     }
                   2133:     return $protocol.$host_name;
                   2134: }
                   2135: 
1.942     foxr     2136: #
                   2137: #   Server side include.
                   2138: # Parameters:
                   2139: #  fn     Possibly encrypted resource name/id.
                   2140: #  form   Hash that describes how the rendering should be done
                   2141: #         and other things.
1.944     foxr     2142: # Returns:
1.950     raeburn  2143: #   Scalar context: The content of the response.
                   2144: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2145: #     
1.15      www      2146: sub ssi {
                   2147: 
1.944     foxr     2148:     my ($fn,%form)=@_;
1.15      www      2149:     my $ua=new LWP::UserAgent;
1.23      www      2150:     my $request;
1.711     albertel 2151: 
                   2152:     $form{'no_update_last_known'}=1;
1.895     albertel 2153:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2154:     if (%form) {
1.782     albertel 2155:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2156:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2157:     } else {
1.782     albertel 2158:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2159:     }
                   2160: 
1.15      www      2161:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2162:     my $response=$ua->request($request);
                   2163: 
1.944     foxr     2164:     if (wantarray) {
                   2165: 	return ($response->content, $response);
                   2166:     } else {
                   2167: 	return $response->content;
1.942     foxr     2168:     }
1.324     www      2169: }
                   2170: 
                   2171: sub externalssi {
                   2172:     my ($url)=@_;
                   2173:     my $ua=new LWP::UserAgent;
                   2174:     my $request=new HTTP::Request('GET',$url);
                   2175:     my $response=$ua->request($request);
1.954     raeburn  2176:     if (wantarray) {
                   2177:         return ($response->content, $response);
                   2178:     } else {
                   2179:         return $response->content;
                   2180:     }
1.15      www      2181: }
1.254     www      2182: 
1.492     albertel 2183: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2184: 
                   2185: sub allowuploaded {
                   2186:     my ($srcurl,$url)=@_;
                   2187:     $url=&clutter(&declutter($url));
                   2188:     my $dir=$url;
                   2189:     $dir=~s/\/[^\/]+$//;
                   2190:     my %httpref=();
                   2191:     my $httpurl=&hreflocation('',$url);
                   2192:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2193:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2194: }
1.477     raeburn  2195: 
1.478     albertel 2196: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2197: # input: action, courseID, current domain, intended
1.637     raeburn  2198: #        path to file, source of file, instruction to parse file for objects,
                   2199: #        ref to hash for embedded objects,
                   2200: #        ref to hash for codebase of java objects.
                   2201: #
1.485     raeburn  2202: # output: url to file (if action was uploaddoc), 
                   2203: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2204: #
1.478     albertel 2205: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2206: # course.
1.477     raeburn  2207: #
1.478     albertel 2208: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2209: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2210: #          course's home server.
1.477     raeburn  2211: #
1.478     albertel 2212: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2213: #          be copied from $source (current location) to 
                   2214: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2215: #         and will then be copied to
                   2216: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2217: #         course's home server.
1.485     raeburn  2218: #
1.481     raeburn  2219: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2220: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2221: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2222: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2223: #         in course's home server.
1.637     raeburn  2224: #
1.477     raeburn  2225: 
                   2226: sub process_coursefile {
1.638     albertel 2227:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2228:     my $fetchresult;
1.638     albertel 2229:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2230:     if ($action eq 'propagate') {
1.638     albertel 2231:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2232: 			     $home);
1.481     raeburn  2233:     } else {
1.477     raeburn  2234:         my $fpath = '';
                   2235:         my $fname = $file;
1.478     albertel 2236:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2237:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2238:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2239:         if ($action eq 'copy') {
                   2240:             if ($source eq '') {
                   2241:                 $fetchresult = 'no source file';
                   2242:                 return $fetchresult;
                   2243:             } else {
                   2244:                 my $destination = $filepath.'/'.$fname;
                   2245:                 rename($source,$destination);
                   2246:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2247:                                  $home);
1.481     raeburn  2248:             }
                   2249:         } elsif ($action eq 'uploaddoc') {
                   2250:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2251:             print $fh $env{'form.'.$source};
1.481     raeburn  2252:             close($fh);
1.637     raeburn  2253:             if ($parser eq 'parse') {
1.1024    raeburn  2254:                 my $mm = new File::MMagic;
                   2255:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2256:                 if ($mime_type eq 'text/html') {
                   2257:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2258:                     unless ($parse_result eq 'ok') {
                   2259:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2260:                     }
1.637     raeburn  2261:                 }
                   2262:             }
1.477     raeburn  2263:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2264:                                  $home);
1.481     raeburn  2265:             if ($fetchresult eq 'ok') {
                   2266:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2267:             } else {
                   2268:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2269:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2270:                 return '/adm/notfound.html';
                   2271:             }
1.477     raeburn  2272:         }
                   2273:     }
1.485     raeburn  2274:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2275:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2276:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2277:     }
                   2278:     return $fetchresult;
                   2279: }
                   2280: 
1.637     raeburn  2281: sub build_filepath {
                   2282:     my ($fpath) = @_;
                   2283:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2284:     unless ($fpath eq '') {
                   2285:         my @parts=split('/',$fpath);
                   2286:         foreach my $part (@parts) {
                   2287:             $filepath.= '/'.$part;
                   2288:             if ((-e $filepath)!=1) {
                   2289:                 mkdir($filepath,0777);
                   2290:             }
                   2291:         }
                   2292:     }
                   2293:     return $filepath;
                   2294: }
                   2295: 
                   2296: sub store_edited_file {
1.638     albertel 2297:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2298:     my $file = $primary_url;
                   2299:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2300:     my $fpath = '';
                   2301:     my $fname = $file;
                   2302:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2303:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2304:     my $filepath = &build_filepath($fpath);
                   2305:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2306:     print $fh $content;
                   2307:     close($fh);
1.638     albertel 2308:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2309:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2310: 			  $home);
1.637     raeburn  2311:     if ($$fetchresult eq 'ok') {
                   2312:         return '/uploaded/'.$fpath.'/'.$fname;
                   2313:     } else {
1.638     albertel 2314:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2315: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2316:         return '/adm/notfound.html';
                   2317:     }
                   2318: }
                   2319: 
1.531     albertel 2320: sub clean_filename {
1.831     albertel 2321:     my ($fname,$args)=@_;
1.315     www      2322: # Replace Windows backslashes by forward slashes
1.257     www      2323:     $fname=~s/\\/\//g;
1.831     albertel 2324:     if (!$args->{'keep_path'}) {
                   2325:         # Get rid of everything but the actual filename
                   2326: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2327:     }
1.315     www      2328: # Replace spaces by underscores
                   2329:     $fname=~s/\s+/\_/g;
                   2330: # Replace all other weird characters by nothing
1.831     albertel 2331:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2332: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2333: # numbers
                   2334:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2335:     return $fname;
                   2336: }
1.1051    raeburn  2337: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2338: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2339: # image with the same aspect ratio as the original, but with dimensions which do 
                   2340: # not exceed $resizewidth and $resizeheight.
                   2341:  
1.984     neumanie 2342: sub resizeImage {
1.1051    raeburn  2343:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2344:     my $ima = Image::Magick->new;
                   2345:     my $resized;
                   2346:     if (-e $img_path) {
                   2347:         $ima->Read($img_path);
                   2348:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2349:             my $width = $ima->Get('width');
                   2350:             my $height = $ima->Get('height');
                   2351:             if ($width > $resizewidth) {
                   2352: 	        my $factor = $width/$resizewidth;
                   2353:                 my $newheight = $height/$factor;
                   2354:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2355:                 $resized = 1;
                   2356:             }
                   2357:         }
                   2358:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2359:             my $width = $ima->Get('width');
                   2360:             my $height = $ima->Get('height');
                   2361:             if ($height > $resizeheight) {
                   2362:                 my $factor = $height/$resizeheight;
                   2363:                 my $newwidth = $width/$factor;
                   2364:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2365:                 $resized = 1;
                   2366:             }
                   2367:         }
                   2368:         if ($resized) {
                   2369:             $ima->Write($img_path);
                   2370:         }
                   2371:     }
                   2372:     return;
1.977     amueller 2373: }
                   2374: 
1.608     albertel 2375: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2376: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2377: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2378: #        $coursedoc - if true up to the current course
                   2379: #                     if false
                   2380: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2381: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2382: #        $allfiles - reference to hash for embedded objects
                   2383: #        $codebase - reference to hash for codebase of java objects
                   2384: #        $desuname - username for permanent storage of uploaded file
                   2385: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2386: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2387: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2388: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2389: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2390: # 
1.686     albertel 2391: # output: url of file in userspace, or error: <message> 
                   2392: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2393: 
1.531     albertel 2394: sub userfileupload {
1.860     raeburn  2395:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2396:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2397:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2398:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2399:     $fname=&clean_filename($fname);
1.315     www      2400: # See if there is anything left
1.257     www      2401:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2402:     chop($env{'form.'.$formname});
1.523     raeburn  2403:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2404:         my $now = time;
                   2405:         my $filepath = 'tmp/helprequests/'.$now;
                   2406:         my @parts=split(/\//,$filepath);
                   2407:         my $fullpath = $perlvar{'lonDaemons'};
                   2408:         for (my $i=0;$i<@parts;$i++) {
                   2409:             $fullpath .= '/'.$parts[$i];
                   2410:             if ((-e $fullpath)!=1) {
                   2411:                 mkdir($fullpath,0777);
                   2412:             }
                   2413:         }
                   2414:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2415:         print $fh $env{'form.'.$formname};
1.523     raeburn  2416:         close($fh);
1.741     raeburn  2417:         return $fullpath.'/'.$fname;
                   2418:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2419:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2420:                        '_'.$env{'user.domain'}.'/pending';
                   2421:         my @parts=split(/\//,$filepath);
                   2422:         my $fullpath = $perlvar{'lonDaemons'};
                   2423:         for (my $i=0;$i<@parts;$i++) {
                   2424:             $fullpath .= '/'.$parts[$i];
                   2425:             if ((-e $fullpath)!=1) {
                   2426:                 mkdir($fullpath,0777);
                   2427:             }
                   2428:         }
                   2429:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2430:         print $fh $env{'form.'.$formname};
                   2431:         close($fh);
                   2432:         return $fullpath.'/'.$fname;
1.523     raeburn  2433:     }
1.995     raeburn  2434:     if ($subdir eq 'scantron') {
                   2435:         $fname = 'scantron_orig_'.$fname;
                   2436:     } else {   
1.258     www      2437: # Create the directory if not present
1.995     raeburn  2438:         $fname="$subdir/$fname";
                   2439:     }
1.259     www      2440:     if ($coursedoc) {
1.638     albertel 2441: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2442: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2443:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2444:             return &finishuserfileupload($docuname,$docudom,
                   2445: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2446: 					 $codebase,$thumbwidth,$thumbheight,
                   2447:                                          $resizewidth,$resizeheight);
1.481     raeburn  2448:         } else {
1.620     albertel 2449:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2450:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2451: 				       $fname,$formname,$parser,
                   2452: 				       $allfiles,$codebase);
1.481     raeburn  2453:         }
1.719     banghart 2454:     } elsif (defined($destuname)) {
                   2455:         my $docuname=$destuname;
                   2456:         my $docudom=$destudom;
1.860     raeburn  2457: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2458: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2459:                                      $thumbwidth,$thumbheight,
                   2460:                                      $resizewidth,$resizeheight);
1.719     banghart 2461:         
1.259     www      2462:     } else {
1.638     albertel 2463:         my $docuname=$env{'user.name'};
                   2464:         my $docudom=$env{'user.domain'};
1.714     raeburn  2465:         if (exists($env{'form.group'})) {
                   2466:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2467:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2468:         }
1.860     raeburn  2469: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2470: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2471:                                      $thumbwidth,$thumbheight,
                   2472:                                      $resizewidth,$resizeheight);
1.259     www      2473:     }
1.271     www      2474: }
                   2475: 
                   2476: sub finishuserfileupload {
1.860     raeburn  2477:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051    raeburn  2478:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477     raeburn  2479:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2480:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2481:   
1.860     raeburn  2482:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2483:     $file=$fname;
                   2484:     if ($fname=~m|/|) {
                   2485:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2486: 	$path.=$fnamepath.'/';
                   2487:     }
1.259     www      2488:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2489:     my $count;
                   2490:     for ($count=4;$count<=$#parts;$count++) {
                   2491:         $filepath.="/$parts[$count]";
                   2492:         if ((-e $filepath)!=1) {
                   2493: 	    mkdir($filepath,0777);
                   2494:         }
                   2495:     }
1.984     neumanie 2496: 
1.258     www      2497: # Save the file
                   2498:     {
1.701     albertel 2499: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2500: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2501: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2502: 	    return '/adm/notfound.html';
                   2503: 	}
                   2504: 	if (!print FH ($env{'form.'.$formname})) {
                   2505: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2506: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2507: 	    return '/adm/notfound.html';
                   2508: 	}
1.570     albertel 2509: 	close(FH);
1.1051    raeburn  2510:         if ($resizewidth && $resizeheight) {
                   2511:             my $mm = new File::MMagic;
                   2512:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2513:             if ($mime_type =~ m{^image/}) {
                   2514: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2515:             }  
1.977     amueller 2516: 	}
1.258     www      2517:     }
1.637     raeburn  2518:     if ($parser eq 'parse') {
1.1024    raeburn  2519:         my $mm = new File::MMagic;
                   2520:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2521:         if ($mime_type eq 'text/html') {
                   2522:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2523:                                                        $allfiles,$codebase);
                   2524:             unless ($parse_result eq 'ok') {
                   2525:                 &logthis('Failed to parse '.$filepath.$file.
                   2526: 	   	         ' for embedded media: '.$parse_result); 
                   2527:             }
1.637     raeburn  2528:         }
                   2529:     }
1.860     raeburn  2530:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2531:         my $input = $filepath.'/'.$file;
                   2532:         my $output = $filepath.'/'.'tn-'.$file;
                   2533:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2534:         system("convert -sample $thumbsize $input $output");
                   2535:         if (-e $filepath.'/'.'tn-'.$file) {
                   2536:             $fetchthumb  = 1; 
                   2537:         }
                   2538:     }
1.858     raeburn  2539:  
1.259     www      2540: # Notify homeserver to grep it
                   2541: #
1.984     neumanie 2542:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2543:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2544:     if ($fetchresult eq 'ok') {
1.860     raeburn  2545:         if ($fetchthumb) {
                   2546:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2547:             if ($thumbresult ne 'ok') {
                   2548:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2549:                          $docuhome.': '.$thumbresult);
                   2550:             }
                   2551:         }
1.259     www      2552: #
1.258     www      2553: # Return the URL to it
1.494     albertel 2554:         return '/uploaded/'.$path.$file;
1.263     www      2555:     } else {
1.494     albertel 2556:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2557: 		 ': '.$fetchresult);
1.263     www      2558:         return '/adm/notfound.html';
1.858     raeburn  2559:     }
1.493     albertel 2560: }
                   2561: 
1.637     raeburn  2562: sub extract_embedded_items {
1.961     raeburn  2563:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2564:     my @state = ();
                   2565:     my %javafiles = (
                   2566:                       codebase => '',
                   2567:                       code => '',
                   2568:                       archive => ''
                   2569:                     );
                   2570:     my %mediafiles = (
                   2571:                       src => '',
                   2572:                       movie => '',
                   2573:                      );
1.648     raeburn  2574:     my $p;
                   2575:     if ($content) {
                   2576:         $p = HTML::LCParser->new($content);
                   2577:     } else {
1.961     raeburn  2578:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2579:     }
1.641     albertel 2580:     while (my $t=$p->get_token()) {
1.640     albertel 2581: 	if ($t->[0] eq 'S') {
                   2582: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2583: 	    push(@state, $tagname);
1.648     raeburn  2584:             if (lc($tagname) eq 'allow') {
                   2585:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2586:             }
1.640     albertel 2587: 	    if (lc($tagname) eq 'img') {
                   2588: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2589: 	    }
1.886     albertel 2590: 	    if (lc($tagname) eq 'a') {
                   2591: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2592: 	    }
1.645     raeburn  2593:             if (lc($tagname) eq 'script') {
                   2594:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2595:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2596:                 } else {
                   2597:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2598:                 }
                   2599:             }
                   2600:             if (lc($tagname) eq 'link') {
                   2601:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2602:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2603:                 }
                   2604:             }
1.640     albertel 2605: 	    if (lc($tagname) eq 'object' ||
                   2606: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2607: 		foreach my $item (keys(%javafiles)) {
                   2608: 		    $javafiles{$item} = '';
                   2609: 		}
                   2610: 	    }
                   2611: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2612: 		my $name = lc($attr->{'name'});
                   2613: 		foreach my $item (keys(%javafiles)) {
                   2614: 		    if ($name eq $item) {
                   2615: 			$javafiles{$item} = $attr->{'value'};
                   2616: 			last;
                   2617: 		    }
                   2618: 		}
                   2619: 		foreach my $item (keys(%mediafiles)) {
                   2620: 		    if ($name eq $item) {
                   2621: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2622: 			last;
                   2623: 		    }
                   2624: 		}
                   2625: 	    }
                   2626: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2627: 		foreach my $item (keys(%javafiles)) {
                   2628: 		    if ($attr->{$item}) {
                   2629: 			$javafiles{$item} = $attr->{$item};
                   2630: 			last;
                   2631: 		    }
                   2632: 		}
                   2633: 		foreach my $item (keys(%mediafiles)) {
                   2634: 		    if ($attr->{$item}) {
                   2635: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2636: 			last;
                   2637: 		    }
                   2638: 		}
                   2639: 	    }
                   2640: 	} elsif ($t->[0] eq 'E') {
                   2641: 	    my ($tagname) = ($t->[1]);
                   2642: 	    if ($javafiles{'codebase'} ne '') {
                   2643: 		$javafiles{'codebase'} .= '/';
                   2644: 	    }  
                   2645: 	    if (lc($tagname) eq 'applet' ||
                   2646: 		lc($tagname) eq 'object' ||
                   2647: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2648: 		) {
                   2649: 		foreach my $item (keys(%javafiles)) {
                   2650: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2651: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2652: 			&add_filetype($allfiles,$file,$item);
                   2653: 		    }
                   2654: 		}
                   2655: 	    } 
                   2656: 	    pop @state;
                   2657: 	}
                   2658:     }
1.637     raeburn  2659:     return 'ok';
                   2660: }
                   2661: 
1.639     albertel 2662: sub add_filetype {
                   2663:     my ($allfiles,$file,$type)=@_;
                   2664:     if (exists($allfiles->{$file})) {
                   2665: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2666: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2667: 	}
                   2668:     } else {
                   2669: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2670:     }
                   2671: }
                   2672: 
1.493     albertel 2673: sub removeuploadedurl {
1.984     neumanie 2674:     my ($url)=@_;	
                   2675:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2676:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2677: }
                   2678: 
                   2679: sub removeuserfile {
                   2680:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2681:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2682:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2683:     if ($result eq 'ok') {	
1.798     raeburn  2684:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2685:             my $metafile = $fname.'.meta';
                   2686:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2687: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2688:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2689:             my $sqlresult = 
1.823     albertel 2690:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2691:                                         'portfolio_metadata',$group,
                   2692:                                         'delete');
1.798     raeburn  2693:         }
                   2694:     }
                   2695:     return $result;
1.257     www      2696: }
1.15      www      2697: 
1.530     albertel 2698: sub mkdiruserfile {
                   2699:     my ($docuname,$docudom,$dir)=@_;
                   2700:     my $home=&homeserver($docuname,$docudom);
                   2701:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2702: }
                   2703: 
1.531     albertel 2704: sub renameuserfile {
                   2705:     my ($docuname,$docudom,$old,$new)=@_;
                   2706:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2707:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2708:                         &escape("$old").':'.&escape("$new"),$home);
                   2709:     if ($result eq 'ok') {
                   2710:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2711:             my $oldmeta = $old.'.meta';
                   2712:             my $newmeta = $new.'.meta';
                   2713:             my $metaresult = 
                   2714:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2715: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2716:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2717:             my $sqlresult = 
1.823     albertel 2718:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2719:                                         'portfolio_metadata',$group,
                   2720:                                         'delete');
1.798     raeburn  2721:         }
                   2722:     }
                   2723:     return $result;
1.531     albertel 2724: }
                   2725: 
1.14      www      2726: # ------------------------------------------------------------------------- Log
                   2727: 
                   2728: sub log {
                   2729:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2730:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2731: }
                   2732: 
                   2733: # ------------------------------------------------------------------ Course Log
1.352     www      2734: #
                   2735: # This routine flushes several buffers of non-mission-critical nature
                   2736: #
1.157     www      2737: 
                   2738: sub flushcourselogs {
1.352     www      2739:     &logthis('Flushing log buffers');
                   2740: #
                   2741: # course logs
                   2742: # This is a log of all transactions in a course, which can be used
                   2743: # for data mining purposes
                   2744: #
                   2745: # It also collects the courseid database, which lists last transaction
                   2746: # times and course titles for all courseids
                   2747: #
                   2748:     my %courseidbuffer=();
1.921     raeburn  2749:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2750:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2751: 		          &escape($courselogs{$crsid}),
                   2752: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2753: 	    delete $courselogs{$crsid};
                   2754:         } else {
                   2755:             &logthis('Failed to flush log buffer for '.$crsid);
                   2756:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2757:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2758:                         " exceeded maximum size, deleting.</font>");
                   2759:                delete $courselogs{$crsid};
                   2760:             }
1.352     www      2761:         }
1.920     raeburn  2762:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2763:             'description' => $coursedescrbuf{$crsid},
                   2764:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2765:             'type'        => $coursetypebuf{$crsid},
                   2766:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2767:         };
1.191     harris41 2768:     }
1.352     www      2769: #
                   2770: # Write course id database (reverse lookup) to homeserver of courses 
                   2771: # Is used in pickcourse
                   2772: #
1.840     albertel 2773:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2774:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2775:                                     $courseidbuffer{$crs_home},
                   2776:                                     $crs_home,'timeonly');
1.352     www      2777:     }
                   2778: #
                   2779: # File accesses
                   2780: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2781: #
1.449     matthew  2782:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2783:         if ($entry =~ /___count$/) {
                   2784:             my ($dom,$name);
1.807     albertel 2785:             ($dom,$name,undef)=
1.811     albertel 2786: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2787:             if (! defined($dom) || $dom eq '' || 
                   2788:                 ! defined($name) || $name eq '') {
1.620     albertel 2789:                 my $cid = $env{'request.course.id'};
                   2790:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2791:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2792:             }
1.450     matthew  2793:             my $value = $accesshash{$entry};
                   2794:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2795:             my %temphash=($url => $value);
1.449     matthew  2796:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2797:             if ($result eq 'ok') {
                   2798:                 delete $accesshash{$entry};
                   2799:             } elsif ($result eq 'unknown_cmd') {
                   2800:                 # Target server has old code running on it.
1.450     matthew  2801:                 my %temphash=($entry => $value);
1.449     matthew  2802:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2803:                     delete $accesshash{$entry};
                   2804:                 }
                   2805:             }
                   2806:         } else {
1.811     albertel 2807:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2808:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2809:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2810:                 delete $accesshash{$entry};
                   2811:             }
1.185     www      2812:         }
1.191     harris41 2813:     }
1.352     www      2814: #
                   2815: # Roles
                   2816: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2817: #
1.800     albertel 2818:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2819:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2820: 	    split(/\:/,$entry);
                   2821:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2822:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2823:                 $rudom,$runame) eq 'ok') {
                   2824: 	    delete $userrolehash{$entry};
                   2825:         }
                   2826:     }
1.662     raeburn  2827: #
                   2828: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2829: #
                   2830:     my %domrolebuffer = ();
1.1000    raeburn  2831:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2832:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2833:         if ($domrolebuffer{$rudom}) {
                   2834:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2835:                       '='.&escape($domainrolehash{$entry});
                   2836:         } else {
                   2837:             $domrolebuffer{$rudom}.=&escape($entry).
                   2838:                       '='.&escape($domainrolehash{$entry});
                   2839:         }
                   2840:         delete $domainrolehash{$entry};
                   2841:     }
                   2842:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2843: 	my %servers = &get_servers($dom,'library');
                   2844: 	foreach my $tryserver (keys(%servers)) {
                   2845: 	    unless (&reply('domroleput:'.$dom.':'.
                   2846: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2847: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2848: 	    }
1.662     raeburn  2849:         }
                   2850:     }
1.186     www      2851:     $dumpcount++;
1.157     www      2852: }
                   2853: 
                   2854: sub courselog {
                   2855:     my $what=shift;
1.158     www      2856:     $what=time.':'.$what;
1.620     albertel 2857:     unless ($env{'request.course.id'}) { return ''; }
                   2858:     $coursedombuf{$env{'request.course.id'}}=
                   2859:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2860:     $coursenumbuf{$env{'request.course.id'}}=
                   2861:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2862:     $coursehombuf{$env{'request.course.id'}}=
                   2863:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2864:     $coursedescrbuf{$env{'request.course.id'}}=
                   2865:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2866:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2867:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2868:     $courseownerbuf{$env{'request.course.id'}}=
                   2869:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2870:     $coursetypebuf{$env{'request.course.id'}}=
                   2871:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2872:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2873: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2874:     } else {
1.620     albertel 2875: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2876:     }
1.620     albertel 2877:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2878: 	&flushcourselogs();
                   2879:     }
1.158     www      2880: }
                   2881: 
                   2882: sub courseacclog {
                   2883:     my $fnsymb=shift;
1.620     albertel 2884:     unless ($env{'request.course.id'}) { return ''; }
                   2885:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2886:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2887:         $what.=':POST';
1.583     matthew  2888:         # FIXME: Probably ought to escape things....
1.800     albertel 2889: 	foreach my $key (keys(%env)) {
                   2890:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2891:                 my $formitem = $1;
                   2892:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2893:                     $what.=':'.$formitem.'='.$env{$key};
                   2894:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2895:                     $what.=':'.$formitem.'='.$env{$key};
                   2896:                 }
1.158     www      2897:             }
1.191     harris41 2898:         }
1.583     matthew  2899:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2900:         # FIXME: We should not be depending on a form parameter that someone
                   2901:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2902:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2903:             $what.= ':POST';
                   2904:             # FIXME: Probably ought to escape things....
                   2905:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2906:                                  'crsdiscuss') {
1.620     albertel 2907:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2908:             }
                   2909:         }
1.158     www      2910:     }
                   2911:     &courselog($what);
1.149     www      2912: }
                   2913: 
1.185     www      2914: sub countacc {
                   2915:     my $url=&declutter(shift);
1.458     matthew  2916:     return if (! defined($url) || $url eq '');
1.620     albertel 2917:     unless ($env{'request.course.id'}) { return ''; }
                   2918:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2919:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2920:     $accesshash{$key}++;
1.185     www      2921: }
1.349     www      2922: 
1.361     www      2923: sub linklog {
                   2924:     my ($from,$to)=@_;
                   2925:     $from=&declutter($from);
                   2926:     $to=&declutter($to);
                   2927:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2928:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2929: }
                   2930:   
1.349     www      2931: sub userrolelog {
                   2932:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2933:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2934:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2935:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2936:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2937:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2938:        $userrolehash
                   2939:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2940:                     =$tend.':'.$tstart;
1.662     raeburn  2941:     }
1.898     albertel 2942:     if (($env{'request.role'} =~ /dc\./) &&
                   2943: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2944: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2945: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2946:          ($trole=~/^co/))) {
1.898     albertel 2947:        $userrolehash
                   2948:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2949:                     =$tend.':'.$tstart;
                   2950:     }
1.662     raeburn  2951:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2952:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2953:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2954:         ($trole=~/^sc/)) {
                   2955:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2956:        $domainrolehash
                   2957:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2958:                     = $tend.':'.$tstart;
                   2959:     }
1.351     www      2960: }
                   2961: 
1.957     raeburn  2962: sub courserolelog {
                   2963:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2964:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2965:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2966:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2967:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2968:         ($trole eq 'co')) {
1.957     raeburn  2969:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2970:             my $cdom = $1;
                   2971:             my $cnum = $2;
                   2972:             my $sec = $3;
                   2973:             my $namespace = 'rolelog';
                   2974:             my %storehash = (
                   2975:                                role    => $trole,
                   2976:                                start   => $tstart,
                   2977:                                end     => $tend,
                   2978:                                selfenroll => $selfenroll,
                   2979:                                context    => $context,
                   2980:                             );
                   2981:             if ($trole eq 'gr') {
                   2982:                 $namespace = 'groupslog';
                   2983:                 $storehash{'group'} = $sec;
                   2984:             } else {
                   2985:                 $storehash{'section'} = $sec;
                   2986:             }
                   2987:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2988:             if (($trole ne 'st') || ($sec ne '')) {
                   2989:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2990:             }
1.957     raeburn  2991:         }
                   2992:     }
                   2993:     return;
                   2994: }
                   2995: 
1.351     www      2996: sub get_course_adv_roles {
1.948     raeburn  2997:     my ($cid,$codes) = @_;
1.620     albertel 2998:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2999:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3000:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3001:     my %nothide=();
1.800     albertel 3002:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3003:         if ($user !~ /:/) {
                   3004: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3005:         } else {
                   3006:             $nothide{$user}=1;
                   3007:         }
1.470     www      3008:     }
1.351     www      3009:     my %returnhash=();
                   3010:     my %dumphash=
                   3011:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3012:     my $now=time;
1.997     raeburn  3013:     my %privileged;
1.1000    raeburn  3014:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3015: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3016:         if (($tstart) && ($tstart<0)) { next; }
                   3017:         if (($tend) && ($tend<$now)) { next; }
                   3018:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3019:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3020: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3021:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3022:             my %dompersonnel =
1.998     raeburn  3023:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3024:             $privileged{$domain} = {};
                   3025:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3026:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3027:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3028:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3029:                         $privileged{$udom}{$uname} = 1;
                   3030:                     }
                   3031:                 }
                   3032:             }
                   3033:         }
                   3034:         if ((exists($privileged{$domain}{$username})) && 
                   3035:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3036: 	if ($role eq 'cr') { next; }
1.948     raeburn  3037:         if ($codes) {
                   3038:             if ($section) { $role .= ':'.$section; }
                   3039:             if ($returnhash{$role}) {
                   3040:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3041:             } else {
                   3042:                 $returnhash{$role}=$username.':'.$domain;
                   3043:             }
1.351     www      3044:         } else {
1.988     raeburn  3045:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3046:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3047:             if ($returnhash{$key}) {
                   3048: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3049:             } else {
                   3050:                 $returnhash{$key}=$username.':'.$domain;
                   3051:             }
1.351     www      3052:         }
1.948     raeburn  3053:     }
1.400     www      3054:     return %returnhash;
                   3055: }
                   3056: 
                   3057: sub get_my_roles {
1.937     raeburn  3058:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3059:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3060:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3061:     my (%dumphash,%nothide);
1.858     raeburn  3062:     if ($context eq 'userroles') { 
                   3063:         %dumphash = &dump('roles',$udom,$uname);
                   3064:     } else {
                   3065:         %dumphash=
1.400     www      3066:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3067:         if ($hidepriv) {
                   3068:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3069:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3070:                 if ($user !~ /:/) {
                   3071:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3072:                 } else {
                   3073:                     $nothide{$user} = 1;
                   3074:                 }
                   3075:             }
                   3076:         }
1.858     raeburn  3077:     }
1.400     www      3078:     my %returnhash=();
                   3079:     my $now=time;
1.999     raeburn  3080:     my %privileged;
1.800     albertel 3081:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3082:         my ($role,$tend,$tstart);
                   3083:         if ($context eq 'userroles') {
                   3084: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3085:         } else {
                   3086:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3087:         }
1.400     www      3088:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3089:         my $status = 'active';
1.939     raeburn  3090:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3091:             $status = 'previous';
                   3092:         } 
                   3093:         if (($tstart) && ($now<$tstart)) {
                   3094:             $status = 'future';
                   3095:         }
                   3096:         if (ref($types) eq 'ARRAY') {
                   3097:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3098:                 next;
                   3099:             } 
                   3100:         } else {
                   3101:             if ($status ne 'active') {
                   3102:                 next;
                   3103:             }
                   3104:         }
1.867     raeburn  3105:         my ($rolecode,$username,$domain,$section,$area);
                   3106:         if ($context eq 'userroles') {
                   3107:             ($area,$rolecode) = split(/_/,$entry);
                   3108:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3109:         } else {
                   3110:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3111:         }
1.832     raeburn  3112:         if (ref($roledoms) eq 'ARRAY') {
                   3113:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3114:                 next;
                   3115:             }
                   3116:         }
                   3117:         if (ref($roles) eq 'ARRAY') {
                   3118:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3119:                 if ($role =~ /^cr\//) {
                   3120:                     if (!grep(/^cr$/,@{$roles})) {
                   3121:                         next;
                   3122:                     }
                   3123:                 } else {
                   3124:                     next;
                   3125:                 }
1.832     raeburn  3126:             }
1.867     raeburn  3127:         }
1.937     raeburn  3128:         if ($hidepriv) {
1.999     raeburn  3129:             if ($context eq 'userroles') {
                   3130:                 if ((&privileged($username,$domain)) &&
                   3131:                     (!$nothide{$username.':'.$domain})) {
                   3132:                     next;
                   3133:                 }
                   3134:             } else {
                   3135:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3136:                     my %dompersonnel =
                   3137:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3138:                     $privileged{$domain} = {};
                   3139:                     if (keys(%dompersonnel)) {
                   3140:                         foreach my $server (keys(%dompersonnel)) {
                   3141:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3142:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3143:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3144:                                     $privileged{$udom}{$uname} = $trole;
                   3145:                                 }
                   3146:                             }
                   3147:                         }
                   3148:                     }
                   3149:                 }
                   3150:                 if (exists($privileged{$domain}{$username})) {
                   3151:                     if (!$nothide{$username.':'.$domain}) {
                   3152:                         next;
                   3153:                     }
                   3154:                 }
1.937     raeburn  3155:             }
                   3156:         }
1.933     raeburn  3157:         if ($withsec) {
                   3158:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3159:                 $tstart.':'.$tend;
                   3160:         } else {
                   3161:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3162:         }
1.832     raeburn  3163:     }
1.373     www      3164:     return %returnhash;
1.399     www      3165: }
                   3166: 
                   3167: # ----------------------------------------------------- Frontpage Announcements
                   3168: #
                   3169: #
                   3170: 
                   3171: sub postannounce {
                   3172:     my ($server,$text)=@_;
1.844     albertel 3173:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3174:     unless ($text=~/\w/) { $text=''; }
                   3175:     return &reply('setannounce:'.&escape($text),$server);
                   3176: }
                   3177: 
                   3178: sub getannounce {
1.448     albertel 3179: 
                   3180:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3181: 	my $announcement='';
1.800     albertel 3182: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3183: 	close($fh);
1.399     www      3184: 	if ($announcement=~/\w/) { 
                   3185: 	    return 
                   3186:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3187:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3188: 	} else {
                   3189: 	    return '';
                   3190: 	}
                   3191:     } else {
                   3192: 	return '';
                   3193:     }
1.351     www      3194: }
1.353     www      3195: 
                   3196: # ---------------------------------------------------------- Course ID routines
                   3197: # Deal with domain's nohist_courseid.db files
                   3198: #
                   3199: 
                   3200: sub courseidput {
1.921     raeburn  3201:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3202:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3203:     my $outcome;
                   3204:     if ($caller eq 'timeonly') {
                   3205:         my $cids = '';
                   3206:         foreach my $item (keys(%$storehash)) {
                   3207:             $cids.=&escape($item).'&';
                   3208:         }
                   3209:         $cids=~s/\&$//;
                   3210:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3211:                           $coursehome);       
                   3212:     } else {
                   3213:         my $items = '';
                   3214:         foreach my $item (keys(%$storehash)) {
                   3215:             $items.= &escape($item).'='.
                   3216:                      &freeze_escape($$storehash{$item}).'&';
                   3217:         }
                   3218:         $items=~s/\&$//;
                   3219:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3220:                           $coursehome);
1.918     raeburn  3221:     }
                   3222:     if ($outcome eq 'unknown_cmd') {
                   3223:         my $what;
                   3224:         foreach my $cid (keys(%$storehash)) {
                   3225:             $what .= &escape($cid).'=';
1.921     raeburn  3226:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3227:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3228:             }
                   3229:             $what =~ s/\:$/&/;
                   3230:         }
                   3231:         $what =~ s/\&$//;  
                   3232:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3233:     } else {
                   3234:         return $outcome;
                   3235:     }
1.353     www      3236: }
                   3237: 
                   3238: sub courseiddump {
1.921     raeburn  3239:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3240:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3241:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3242:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3243:     my $as_hash = 1;
                   3244:     my %returnhash;
                   3245:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3246:     my %libserv = &all_library();
                   3247:     foreach my $tryserver (keys(%libserv)) {
                   3248:         if ( (  $hostidflag == 1 
                   3249: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3250: 	     || (!defined($hostidflag)) ) {
                   3251: 
1.918     raeburn  3252: 	    if (($domfilter eq '') ||
                   3253: 		(&host_domain($tryserver) eq $domfilter)) {
                   3254:                 my $rep = 
                   3255:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3256:                          $sincefilter.':'.&escape($descfilter).':'.
                   3257:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3258:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3259:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3260:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3261:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3262:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3263:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3264:                          &escape($creationcontext).':'.$domcloner,
                   3265:                          $tryserver);
1.918     raeburn  3266:                 my @pairs=split(/\&/,$rep);
                   3267:                 foreach my $item (@pairs) {
                   3268:                     my ($key,$value)=split(/\=/,$item,2);
                   3269:                     $key = &unescape($key);
                   3270:                     next if ($key =~ /^error: 2 /);
                   3271:                     my $result = &thaw_unescape($value);
                   3272:                     if (ref($result) eq 'HASH') {
                   3273:                         $returnhash{$key}=$result;
                   3274:                     } else {
1.921     raeburn  3275:                         my @responses = split(/:/,$value);
                   3276:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3277:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3278:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3279:                         }
1.1008    raeburn  3280:                     }
1.353     www      3281:                 }
                   3282:             }
                   3283:         }
                   3284:     }
                   3285:     return %returnhash;
                   3286: }
                   3287: 
1.1055    raeburn  3288: sub courselastaccess {
                   3289:     my ($cdom,$cnum,$hostidref) = @_;
                   3290:     my %returnhash;
                   3291:     if ($cdom && $cnum) {
                   3292:         my $chome = &homeserver($cnum,$cdom);
                   3293:         if ($chome ne 'no_host') {
                   3294:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3295:             &extract_lastaccess(\%returnhash,$rep);
                   3296:         }
                   3297:     } else {
                   3298:         if (!$cdom) { $cdom=''; }
                   3299:         my %libserv = &all_library();
                   3300:         foreach my $tryserver (keys(%libserv)) {
                   3301:             if (ref($hostidref) eq 'ARRAY') {
                   3302:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3303:             } 
                   3304:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3305:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3306:                 &extract_lastaccess(\%returnhash,$rep);
                   3307:             }
                   3308:         }
                   3309:     }
                   3310:     return %returnhash;
                   3311: }
                   3312: 
                   3313: sub extract_lastaccess {
                   3314:     my ($returnhash,$rep) = @_;
                   3315:     if (ref($returnhash) eq 'HASH') {
                   3316:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3317:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3318:                  $rep eq '') {
                   3319:             my @pairs=split(/\&/,$rep);
                   3320:             foreach my $item (@pairs) {
                   3321:                 my ($key,$value)=split(/\=/,$item,2);
                   3322:                 $key = &unescape($key);
                   3323:                 next if ($key =~ /^error: 2 /);
                   3324:                 $returnhash->{$key} = &thaw_unescape($value);
                   3325:             }
                   3326:         }
                   3327:     }
                   3328:     return;
                   3329: }
                   3330: 
1.658     raeburn  3331: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3332: 
                   3333: sub dcmailput {
1.685     raeburn  3334:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3335:     my $status = &Apache::lonnet::critical(
1.740     www      3336:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3337:        &escape($message),$server);
1.662     raeburn  3338:     return $status;
                   3339: }
                   3340: 
1.658     raeburn  3341: sub dcmaildump {
                   3342:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3343:     my %returnhash=();
1.846     albertel 3344: 
                   3345:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3346:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3347:                                                          &escape($enddate).':';
                   3348: 	my @esc_senders=map { &escape($_)} @$senders;
                   3349: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3350: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3351:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3352:             if (($key) && ($value)) {
                   3353:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3354:             }
                   3355:         }
                   3356:     }
                   3357:     return %returnhash;
                   3358: }
1.662     raeburn  3359: # ---------------------------------------------------------- Domain roles
                   3360: 
                   3361: sub get_domain_roles {
                   3362:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3363:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3364:         $startdate = '.';
                   3365:     }
1.1018    raeburn  3366:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3367:         $enddate = '.';
                   3368:     }
1.922     raeburn  3369:     my $rolelist;
                   3370:     if (ref($roles) eq 'ARRAY') {
                   3371:         $rolelist = join(':',@{$roles});
                   3372:     }
1.662     raeburn  3373:     my %personnel = ();
1.841     albertel 3374: 
                   3375:     my %servers = &get_servers($dom,'library');
                   3376:     foreach my $tryserver (keys(%servers)) {
                   3377: 	%{$personnel{$tryserver}}=();
                   3378: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3379: 					    &escape($startdate).':'.
                   3380: 					    &escape($enddate).':'.
                   3381: 					    &escape($rolelist), $tryserver))) {
                   3382: 	    my ($key,$value) = split(/\=/,$line,2);
                   3383: 	    if (($key) && ($value)) {
                   3384: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3385: 	    }
                   3386: 	}
1.662     raeburn  3387:     }
                   3388:     return %personnel;
                   3389: }
1.658     raeburn  3390: 
1.149     www      3391: # ----------------------------------------------------------- Check out an item
                   3392: 
1.504     albertel 3393: sub get_first_access {
                   3394:     my ($type,$argsymb)=@_;
1.790     albertel 3395:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3396:     if ($argsymb) { $symb=$argsymb; }
                   3397:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3398:     if ($type eq 'course') {
                   3399: 	$res='course';
                   3400:     } elsif ($type eq 'map') {
1.588     albertel 3401: 	$res=&symbread($map);
                   3402:     } else {
                   3403: 	$res=$symb;
                   3404:     }
                   3405:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3406:     return $times{"$courseid\0$res"};
1.504     albertel 3407: }
                   3408: 
                   3409: sub set_first_access {
                   3410:     my ($type)=@_;
1.790     albertel 3411:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3412:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3413:     if ($type eq 'course') {
                   3414: 	$res='course';
                   3415:     } elsif ($type eq 'map') {
1.588     albertel 3416: 	$res=&symbread($map);
                   3417:     } else {
                   3418: 	$res=$symb;
                   3419:     }
                   3420:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3421:     if (!$firstaccess) {
1.588     albertel 3422: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3423:     }
                   3424:     return 'already_set';
1.504     albertel 3425: }
                   3426: 
1.149     www      3427: sub checkout {
                   3428:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3429:     my $now=time;
                   3430:     my $lonhost=$perlvar{'lonHostID'};
                   3431:     my $infostr=&escape(
1.234     www      3432:                  'CHECKOUTTOKEN&'.
1.149     www      3433:                  $tuname.'&'.
                   3434:                  $tudom.'&'.
                   3435:                  $tcrsid.'&'.
                   3436:                  $symb.'&'.
                   3437: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3438:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3439:     if ($token=~/^error\:/) { 
1.672     albertel 3440:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3441:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3442:                  "</font>");
                   3443:         return ''; 
                   3444:     }
                   3445: 
1.149     www      3446:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3447:     $token=~tr/a-z/A-Z/;
                   3448: 
1.153     www      3449:     my %infohash=('resource.0.outtoken' => $token,
                   3450:                   'resource.0.checkouttime' => $now,
                   3451:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3452: 
                   3453:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3454:        return '';
1.151     www      3455:     } else {
1.672     albertel 3456:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3457:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3458:                  "</font>");
1.149     www      3459:     }    
                   3460: 
                   3461:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3462:                          &escape('Checkout '.$infostr.' - '.
                   3463:                                                  $token)) ne 'ok') {
                   3464: 	return '';
1.151     www      3465:     } else {
1.672     albertel 3466:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3467:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3468:                  "</font>");
1.149     www      3469:     }
1.151     www      3470:     return $token;
1.149     www      3471: }
                   3472: 
                   3473: # ------------------------------------------------------------ Check in an item
                   3474: 
                   3475: sub checkin {
                   3476:     my $token=shift;
1.150     www      3477:     my $now=time;
                   3478:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3479:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3480:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3481:     $dtoken=~s/\W/\_/g;
1.234     www      3482:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3483:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3484: 
1.154     www      3485:     unless (($tuname) && ($tudom)) {
                   3486:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3487:         return '';
                   3488:     }
                   3489:     
                   3490:     unless (&allowed('mgr',$tcrsid)) {
                   3491:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3492:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3493:         return '';
                   3494:     }
                   3495: 
1.153     www      3496:     my %infohash=('resource.0.intoken' => $token,
                   3497:                   'resource.0.checkintime' => $now,
                   3498:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3499: 
                   3500:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3501:        return '';
                   3502:     }    
                   3503: 
                   3504:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3505:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3506: 	return '';
                   3507:     }
                   3508: 
                   3509:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3510: }
                   3511: 
                   3512: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3513: 
                   3514: sub expirespread {
                   3515:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3516:     my $cid=$env{'request.course.id'}; 
1.110     www      3517:     if ($cid) {
                   3518:        my $now=time;
                   3519:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3520:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3521:                             $env{'course.'.$cid.'.num'}.
1.110     www      3522: 	        	    ':nohist_expirationdates:'.
                   3523:                             &escape($key).'='.$now,
1.620     albertel 3524:                             $env{'course.'.$cid.'.home'})
1.110     www      3525:     }
                   3526:     return 'ok';
1.14      www      3527: }
                   3528: 
1.109     www      3529: # ----------------------------------------------------- Devalidate Spreadsheets
                   3530: 
                   3531: sub devalidate {
1.325     www      3532:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3533:     my $cid=$env{'request.course.id'}; 
1.109     www      3534:     if ($cid) {
1.391     matthew  3535:         # delete the stored spreadsheets for
                   3536:         # - the student level sheet of this user in course's homespace
                   3537:         # - the assessment level sheet for this resource 
                   3538:         #   for this user in user's homespace
1.553     albertel 3539: 	# - current conditional state info
1.325     www      3540: 	my $key=$uname.':'.$udom.':';
1.109     www      3541:         my $status=
1.299     matthew  3542: 	    &del('nohist_calculatedsheets',
1.391     matthew  3543: 		 [$key.'studentcalc:'],
1.620     albertel 3544: 		 $env{'course.'.$cid.'.domain'},
                   3545: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3546: 		.' '.
                   3547: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3548: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3549:         unless ($status eq 'ok ok') {
                   3550:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3551:                     $uname.' at '.$udom.' for '.
1.109     www      3552: 		    $symb.': '.$status);
1.133     albertel 3553:         }
1.553     albertel 3554: 	&delenv('user.state.'.$cid);
1.109     www      3555:     }
                   3556: }
                   3557: 
1.265     albertel 3558: sub get_scalar {
                   3559:     my ($string,$end) = @_;
                   3560:     my $value;
                   3561:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3562: 	$value = $1;
                   3563:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3564: 	$value = $1;
                   3565:     }
                   3566:     return &unescape($value);
                   3567: }
                   3568: 
                   3569: sub array2str {
                   3570:   my (@array) = @_;
                   3571:   my $result=&arrayref2str(\@array);
                   3572:   $result=~s/^__ARRAY_REF__//;
                   3573:   $result=~s/__END_ARRAY_REF__$//;
                   3574:   return $result;
                   3575: }
                   3576: 
1.204     albertel 3577: sub arrayref2str {
                   3578:   my ($arrayref) = @_;
1.265     albertel 3579:   my $result='__ARRAY_REF__';
1.204     albertel 3580:   foreach my $elem (@$arrayref) {
1.265     albertel 3581:     if(ref($elem) eq 'ARRAY') {
                   3582:       $result.=&arrayref2str($elem).'&';
                   3583:     } elsif(ref($elem) eq 'HASH') {
                   3584:       $result.=&hashref2str($elem).'&';
                   3585:     } elsif(ref($elem)) {
                   3586:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3587:     } else {
                   3588:       $result.=&escape($elem).'&';
                   3589:     }
                   3590:   }
                   3591:   $result=~s/\&$//;
1.265     albertel 3592:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3593:   return $result;
                   3594: }
                   3595: 
1.168     albertel 3596: sub hash2str {
1.204     albertel 3597:   my (%hash) = @_;
                   3598:   my $result=&hashref2str(\%hash);
1.265     albertel 3599:   $result=~s/^__HASH_REF__//;
                   3600:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3601:   return $result;
                   3602: }
                   3603: 
                   3604: sub hashref2str {
                   3605:   my ($hashref)=@_;
1.265     albertel 3606:   my $result='__HASH_REF__';
1.800     albertel 3607:   foreach my $key (sort(keys(%$hashref))) {
                   3608:     if (ref($key) eq 'ARRAY') {
                   3609:       $result.=&arrayref2str($key).'=';
                   3610:     } elsif (ref($key) eq 'HASH') {
                   3611:       $result.=&hashref2str($key).'=';
                   3612:     } elsif (ref($key)) {
1.265     albertel 3613:       $result.='=';
1.800     albertel 3614:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3615:     } else {
1.800     albertel 3616: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3617:     }
                   3618: 
1.800     albertel 3619:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3620:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3621:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3622:       $result.=&hashref2str($hashref->{$key}).'&';
                   3623:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3624:        $result.='&';
1.800     albertel 3625:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3626:     } else {
1.800     albertel 3627:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3628:     }
                   3629:   }
1.168     albertel 3630:   $result=~s/\&$//;
1.265     albertel 3631:   $result .= '__END_HASH_REF__';
1.168     albertel 3632:   return $result;
                   3633: }
                   3634: 
                   3635: sub str2hash {
1.265     albertel 3636:     my ($string)=@_;
                   3637:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3638:     return %$hash;
                   3639: }
                   3640: 
                   3641: sub str2hashref {
1.168     albertel 3642:   my ($string) = @_;
1.265     albertel 3643: 
                   3644:   my %hash;
                   3645: 
                   3646:   if($string !~ /^__HASH_REF__/) {
                   3647:       if (! ($string eq '' || !defined($string))) {
                   3648: 	  $hash{'error'}='Not hash reference';
                   3649:       }
                   3650:       return (\%hash, $string);
                   3651:   }
                   3652: 
                   3653:   $string =~ s/^__HASH_REF__//;
                   3654: 
                   3655:   while($string !~ /^__END_HASH_REF__/) {
                   3656:       #key
                   3657:       my $key='';
                   3658:       if($string =~ /^__HASH_REF__/) {
                   3659:           ($key, $string)=&str2hashref($string);
                   3660:           if(defined($key->{'error'})) {
                   3661:               $hash{'error'}='Bad data';
                   3662:               return (\%hash, $string);
                   3663:           }
                   3664:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3665:           ($key, $string)=&str2arrayref($string);
                   3666:           if($key->[0] eq 'Array reference error') {
                   3667:               $hash{'error'}='Bad data';
                   3668:               return (\%hash, $string);
                   3669:           }
                   3670:       } else {
                   3671:           $string =~ s/^(.*?)=//;
1.267     albertel 3672: 	  $key=&unescape($1);
1.265     albertel 3673:       }
                   3674:       $string =~ s/^=//;
                   3675: 
                   3676:       #value
                   3677:       my $value='';
                   3678:       if($string =~ /^__HASH_REF__/) {
                   3679:           ($value, $string)=&str2hashref($string);
                   3680:           if(defined($value->{'error'})) {
                   3681:               $hash{'error'}='Bad data';
                   3682:               return (\%hash, $string);
                   3683:           }
                   3684:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3685:           ($value, $string)=&str2arrayref($string);
                   3686:           if($value->[0] eq 'Array reference error') {
                   3687:               $hash{'error'}='Bad data';
                   3688:               return (\%hash, $string);
                   3689:           }
                   3690:       } else {
                   3691: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3692:       }
                   3693:       $string =~ s/^&//;
                   3694: 
                   3695:       $hash{$key}=$value;
1.204     albertel 3696:   }
1.265     albertel 3697: 
                   3698:   $string =~ s/^__END_HASH_REF__//;
                   3699: 
                   3700:   return (\%hash, $string);
1.204     albertel 3701: }
                   3702: 
                   3703: sub str2array {
1.265     albertel 3704:     my ($string)=@_;
                   3705:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3706:     return @$array;
                   3707: }
                   3708: 
                   3709: sub str2arrayref {
1.204     albertel 3710:   my ($string) = @_;
1.265     albertel 3711:   my @array;
                   3712: 
                   3713:   if($string !~ /^__ARRAY_REF__/) {
                   3714:       if (! ($string eq '' || !defined($string))) {
                   3715: 	  $array[0]='Array reference error';
                   3716:       }
                   3717:       return (\@array, $string);
                   3718:   }
                   3719: 
                   3720:   $string =~ s/^__ARRAY_REF__//;
                   3721: 
                   3722:   while($string !~ /^__END_ARRAY_REF__/) {
                   3723:       my $value='';
                   3724:       if($string =~ /^__HASH_REF__/) {
                   3725:           ($value, $string)=&str2hashref($string);
                   3726:           if(defined($value->{'error'})) {
                   3727:               $array[0] ='Array reference error';
                   3728:               return (\@array, $string);
                   3729:           }
                   3730:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3731:           ($value, $string)=&str2arrayref($string);
                   3732:           if($value->[0] eq 'Array reference error') {
                   3733:               $array[0] ='Array reference error';
                   3734:               return (\@array, $string);
                   3735:           }
                   3736:       } else {
                   3737: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3738:       }
                   3739:       $string =~ s/^&//;
                   3740: 
                   3741:       push(@array, $value);
1.191     harris41 3742:   }
1.265     albertel 3743: 
                   3744:   $string =~ s/^__END_ARRAY_REF__//;
                   3745: 
                   3746:   return (\@array, $string);
1.168     albertel 3747: }
                   3748: 
1.167     albertel 3749: # -------------------------------------------------------------------Temp Store
                   3750: 
1.168     albertel 3751: sub tmpreset {
                   3752:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3753:   if (!$symb) {
                   3754:     $symb=&symbread();
1.620     albertel 3755:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3756:   }
                   3757:   $symb=escape($symb);
                   3758: 
1.620     albertel 3759:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3760:   $namespace=~s/\//\_/g;
                   3761:   $namespace=~s/\W//g;
                   3762: 
1.620     albertel 3763:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3764:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3765:   if ($domain eq 'public' && $stuname eq 'public') {
                   3766:       $stuname=$ENV{'REMOTE_ADDR'};
                   3767:   }
1.168     albertel 3768:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3769:   my %hash;
                   3770:   if (tie(%hash,'GDBM_File',
                   3771: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3772: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3773:     foreach my $key (keys(%hash)) {
1.180     albertel 3774:       if ($key=~ /:$symb/) {
1.168     albertel 3775: 	delete($hash{$key});
                   3776:       }
                   3777:     }
                   3778:   }
                   3779: }
                   3780: 
1.167     albertel 3781: sub tmpstore {
1.168     albertel 3782:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3783: 
                   3784:   if (!$symb) {
                   3785:     $symb=&symbread();
1.620     albertel 3786:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3787:   }
                   3788:   $symb=escape($symb);
                   3789: 
                   3790:   if (!$namespace) {
                   3791:     # I don't think we would ever want to store this for a course.
                   3792:     # it seems this will only be used if we don't have a course.
1.620     albertel 3793:     #$namespace=$env{'request.course.id'};
1.168     albertel 3794:     #if (!$namespace) {
1.620     albertel 3795:       $namespace=$env{'request.state'};
1.168     albertel 3796:     #}
                   3797:   }
                   3798:   $namespace=~s/\//\_/g;
                   3799:   $namespace=~s/\W//g;
1.620     albertel 3800:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3801:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3802:   if ($domain eq 'public' && $stuname eq 'public') {
                   3803:       $stuname=$ENV{'REMOTE_ADDR'};
                   3804:   }
1.168     albertel 3805:   my $now=time;
                   3806:   my %hash;
                   3807:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3808:   if (tie(%hash,'GDBM_File',
                   3809: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3810: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3811:     $hash{"version:$symb"}++;
                   3812:     my $version=$hash{"version:$symb"};
                   3813:     my $allkeys=''; 
                   3814:     foreach my $key (keys(%$storehash)) {
                   3815:       $allkeys.=$key.':';
1.591     albertel 3816:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3817:     }
                   3818:     $hash{"$version:$symb:timestamp"}=$now;
                   3819:     $allkeys.='timestamp';
                   3820:     $hash{"$version:keys:$symb"}=$allkeys;
                   3821:     if (untie(%hash)) {
                   3822:       return 'ok';
                   3823:     } else {
                   3824:       return "error:$!";
                   3825:     }
                   3826:   } else {
                   3827:     return "error:$!";
                   3828:   }
                   3829: }
1.167     albertel 3830: 
1.168     albertel 3831: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3832: 
1.168     albertel 3833: sub tmprestore {
                   3834:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3835: 
1.168     albertel 3836:   if (!$symb) {
                   3837:     $symb=&symbread();
1.620     albertel 3838:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3839:   }
                   3840:   $symb=escape($symb);
                   3841: 
1.620     albertel 3842:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3843: 
1.620     albertel 3844:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3845:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3846:   if ($domain eq 'public' && $stuname eq 'public') {
                   3847:       $stuname=$ENV{'REMOTE_ADDR'};
                   3848:   }
1.168     albertel 3849:   my %returnhash;
                   3850:   $namespace=~s/\//\_/g;
                   3851:   $namespace=~s/\W//g;
                   3852:   my %hash;
                   3853:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3854:   if (tie(%hash,'GDBM_File',
                   3855: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3856: 	  &GDBM_READER(),0640)) {
1.168     albertel 3857:     my $version=$hash{"version:$symb"};
                   3858:     $returnhash{'version'}=$version;
                   3859:     my $scope;
                   3860:     for ($scope=1;$scope<=$version;$scope++) {
                   3861:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3862:       my @keys=split(/:/,$vkeys);
                   3863:       my $key;
                   3864:       $returnhash{"$scope:keys"}=$vkeys;
                   3865:       foreach $key (@keys) {
1.591     albertel 3866: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3867: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3868:       }
                   3869:     }
1.168     albertel 3870:     if (!(untie(%hash))) {
                   3871:       return "error:$!";
                   3872:     }
                   3873:   } else {
                   3874:     return "error:$!";
                   3875:   }
                   3876:   return %returnhash;
1.167     albertel 3877: }
                   3878: 
1.9       www      3879: # ----------------------------------------------------------------------- Store
                   3880: 
                   3881: sub store {
1.124     www      3882:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3883:     my $home='';
                   3884: 
1.168     albertel 3885:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3886: 
1.213     www      3887:     $symb=&symbclean($symb);
1.122     albertel 3888:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3889: 
1.620     albertel 3890:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3891:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3892: 
                   3893:     &devalidate($symb,$stuname,$domain);
1.109     www      3894: 
                   3895:     $symb=escape($symb);
1.187     www      3896:     if (!$namespace) { 
1.620     albertel 3897:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3898:           return ''; 
                   3899:        } 
                   3900:     }
1.620     albertel 3901:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3902: 
                   3903:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3904:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3905: 
1.12      www      3906:     my $namevalue='';
1.800     albertel 3907:     foreach my $key (keys(%$storehash)) {
                   3908:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3909:     }
1.12      www      3910:     $namevalue=~s/\&$//;
1.187     www      3911:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3912:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3913: }
                   3914: 
1.47      www      3915: # -------------------------------------------------------------- Critical Store
                   3916: 
                   3917: sub cstore {
1.124     www      3918:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3919:     my $home='';
                   3920: 
1.168     albertel 3921:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3922: 
1.213     www      3923:     $symb=&symbclean($symb);
1.122     albertel 3924:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3925: 
1.620     albertel 3926:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3927:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3928: 
                   3929:     &devalidate($symb,$stuname,$domain);
1.109     www      3930: 
                   3931:     $symb=escape($symb);
1.187     www      3932:     if (!$namespace) { 
1.620     albertel 3933:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3934:           return ''; 
                   3935:        } 
                   3936:     }
1.620     albertel 3937:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3938: 
                   3939:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3940:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3941: 
1.47      www      3942:     my $namevalue='';
1.800     albertel 3943:     foreach my $key (keys(%$storehash)) {
                   3944:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3945:     }
1.47      www      3946:     $namevalue=~s/\&$//;
1.187     www      3947:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3948:     return critical
                   3949:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3950: }
                   3951: 
1.9       www      3952: # --------------------------------------------------------------------- Restore
                   3953: 
                   3954: sub restore {
1.124     www      3955:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3956:     my $home='';
                   3957: 
1.168     albertel 3958:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3959: 
1.122     albertel 3960:     if (!$symb) {
                   3961:       unless ($symb=escape(&symbread())) { return ''; }
                   3962:     } else {
1.213     www      3963:       $symb=&escape(&symbclean($symb));
1.122     albertel 3964:     }
1.188     www      3965:     if (!$namespace) { 
1.620     albertel 3966:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3967:           return ''; 
                   3968:        } 
                   3969:     }
1.620     albertel 3970:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3971:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3972:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3973:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3974: 
1.12      www      3975:     my %returnhash=();
1.800     albertel 3976:     foreach my $line (split(/\&/,$answer)) {
                   3977: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3978:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3979:     }
1.75      www      3980:     my $version;
                   3981:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3982:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3983:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3984:        }
1.75      www      3985:     }
1.13      www      3986:     return %returnhash;
1.34      www      3987: }
                   3988: 
                   3989: # ---------------------------------------------------------- Course Description
                   3990: 
                   3991: sub coursedescription {
1.731     albertel 3992:     my ($courseid,$args)=@_;
1.34      www      3993:     $courseid=~s/^\///;
1.49      www      3994:     $courseid=~s/\_/\//g;
1.34      www      3995:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3996:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3997:     my $normalid=$cdomain.'_'.$cnum;
                   3998:     # need to always cache even if we get errors otherwise we keep 
                   3999:     # trying and trying and trying to get the course description.
                   4000:     my %envhash=();
                   4001:     my %returnhash=();
1.731     albertel 4002:     
                   4003:     my $expiretime=600;
                   4004:     if ($env{'request.course.id'} eq $normalid) {
                   4005: 	$expiretime=120;
                   4006:     }
                   4007: 
                   4008:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4009:     if (!$args->{'freshen_cache'}
                   4010: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4011: 	foreach my $key (keys(%env)) {
                   4012: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4013: 	    my ($setting) = $1;
                   4014: 	    $returnhash{$setting} = $env{$key};
                   4015: 	}
                   4016: 	return %returnhash;
                   4017:     }
                   4018: 
                   4019:     # get the data agin
                   4020:     if (!$args->{'one_time'}) {
                   4021: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4022:     }
1.811     albertel 4023: 
1.34      www      4024:     if ($chome ne 'no_host') {
1.302     albertel 4025:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4026:        if (!exists($returnhash{'con_lost'})) {
                   4027:            $returnhash{'home'}= $chome;
                   4028: 	   $returnhash{'domain'} = $cdomain;
                   4029: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4030:            if (!defined($returnhash{'type'})) {
                   4031:                $returnhash{'type'} = 'Course';
                   4032:            }
1.130     albertel 4033:            while (my ($name,$value) = each %returnhash) {
1.53      www      4034:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4035:            }
1.270     www      4036:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4037:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4038: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4039:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4040:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4041:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4042:        }
                   4043:     }
1.731     albertel 4044:     if (!$args->{'one_time'}) {
1.949     raeburn  4045: 	&appenv(\%envhash);
1.731     albertel 4046:     }
1.302     albertel 4047:     return %returnhash;
1.461     www      4048: }
                   4049: 
1.1056.4.5  raeburn  4050: sub update_released_required {
                   4051:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4052:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4053:         $cid = $env{'request.course.id'};
                   4054:         $cdom = $env{'course.'.$cid.'.domain'};
                   4055:         $cnum = $env{'course.'.$cid.'.num'};
                   4056:         $chome = $env{'course.'.$cid.'.home'};
                   4057:     }
                   4058:     if ($needsrelease) {
                   4059:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4060:         my $needsupdate;
                   4061:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4062:             $needsupdate = 1;
                   4063:         } else {
                   4064:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4065:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4066:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4067:                 $needsupdate = 1;
                   4068:             }
                   4069:         }
                   4070:         if ($needsupdate) {
                   4071:             my %needshash = (
                   4072:                              'internal.releaserequired' => $needsrelease,
                   4073:                             );
                   4074:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4075:             if ($putresult eq 'ok') {
                   4076:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4077:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4078:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4079:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4080:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4081:                 }
                   4082:             }
                   4083:         }
                   4084:     }
                   4085:     return;
                   4086: }
                   4087: 
1.461     www      4088: # -------------------------------------------------See if a user is privileged
                   4089: 
                   4090: sub privileged {
                   4091:     my ($username,$domain)=@_;
                   4092:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4093: 			&homeserver($username,$domain));
1.1033    raeburn  4094:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4095:         ($rolesdump =~ /^error:/)) {
                   4096:         return 0;
                   4097:     }
1.461     www      4098:     my $now=time;
                   4099:     if ($rolesdump ne '') {
1.800     albertel 4100:         foreach my $entry (split(/&/,$rolesdump)) {
                   4101: 	    if ($entry!~/^rolesdef_/) {
                   4102: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4103: 		$area=~s/\_\w\w$//;
                   4104: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4105: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4106: 		    my $active=1;
                   4107: 		    if ($tend) {
                   4108: 			if ($tend<$now) { $active=0; }
                   4109: 		    }
                   4110: 		    if ($tstart) {
                   4111: 			if ($tstart>$now) { $active=0; }
                   4112: 		    }
                   4113: 		    if ($active) { return 1; }
                   4114: 		}
                   4115: 	    }
                   4116: 	}
                   4117:     }
                   4118:     return 0;
1.9       www      4119: }
1.1       albertel 4120: 
1.103     harris41 4121: # -------------------------------------------------------- Get user privileges
1.11      www      4122: 
                   4123: sub rolesinit {
                   4124:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4125:     my $now=time;
                   4126:     my %userroles = ('user.login.time' => $now);
1.1056.4.3  raeburn  4127:     my $extra = &freeze_escape({'clientcheckrole' => 1});
                   4128:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4129:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4130:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4131:         return \%userroles;
                   4132:     }
1.11      www      4133:     my %allroles=();
1.678     raeburn  4134:     my %allgroups=();   
                   4135:     my $group_privs;
1.11      www      4136: 
                   4137:     if ($rolesdump ne '') {
1.800     albertel 4138:         foreach my $entry (split(/&/,$rolesdump)) {
                   4139: 	  if ($entry!~/^rolesdef_/) {
                   4140:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4141: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4142:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4143: 	    if ($role=~/^cr/) { 
1.807     albertel 4144: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4145: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4146: 		    ($tend,$tstart)=split('_',$trest);
                   4147: 		} else {
                   4148: 		    $trole=$role;
                   4149: 		}
1.678     raeburn  4150:             } elsif ($role =~ m|^gr/|) {
                   4151:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4152:                 ($trole,$group_privs) = split(/\//,$trole);
                   4153:                 $group_privs = &unescape($group_privs);
1.587     albertel 4154: 	    } else {
                   4155: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4156: 	    }
1.743     albertel 4157: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4158: 					 $username);
                   4159: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4160:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4161:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4162:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4163: 		my $spec=$trole.'.'.$area;
                   4164: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4165: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4166:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4167:                 } elsif ($trole eq 'gr') {
                   4168:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4169: 		} else {
1.567     raeburn  4170:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4171: 		}
1.12      www      4172:             }
1.662     raeburn  4173:           }
1.191     harris41 4174:         }
1.743     albertel 4175:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4176:         $userroles{'user.adv'}    = $adv;
                   4177: 	$userroles{'user.author'} = $author;
1.620     albertel 4178:         $env{'user.adv'}=$adv;
1.11      www      4179:     }
1.743     albertel 4180:     return \%userroles;  
1.11      www      4181: }
                   4182: 
1.567     raeburn  4183: sub set_arearole {
                   4184:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4185: # log the associated role with the area
                   4186:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4187:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4188: }
                   4189: 
                   4190: sub custom_roleprivs {
                   4191:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4192:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4193:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4194:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4195:         my ($rdummy,$roledef)=
                   4196:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4197:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4198:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4199:             if (defined($syspriv)) {
1.1043    raeburn  4200:                 if ($trest =~ /^$match_community$/) {
                   4201:                     $syspriv =~ s/bre\&S//; 
                   4202:                 }
1.567     raeburn  4203:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4204:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4205:             }
                   4206:             if ($tdomain ne '') {
                   4207:                 if (defined($dompriv)) {
                   4208:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4209:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4210:                 }
                   4211:                 if (($trest ne '') && (defined($coursepriv))) {
                   4212:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4213:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4214:                 }
                   4215:             }
                   4216:         }
                   4217:     }
                   4218: }
                   4219: 
1.678     raeburn  4220: sub group_roleprivs {
                   4221:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4222:     my $access = 1;
                   4223:     my $now = time;
                   4224:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4225:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4226:     if ($access) {
1.811     albertel 4227:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4228:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4229:     }
                   4230: }
1.567     raeburn  4231: 
                   4232: sub standard_roleprivs {
                   4233:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4234:     if (defined($pr{$trole.':s'})) {
                   4235:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4236:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4237:     }
                   4238:     if ($tdomain ne '') {
                   4239:         if (defined($pr{$trole.':d'})) {
                   4240:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4241:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4242:         }
                   4243:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4244:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4245:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4246:         }
                   4247:     }
                   4248: }
                   4249: 
                   4250: sub set_userprivs {
1.1056.4.2  raeburn  4251:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4252:     my $author=0;
                   4253:     my $adv=0;
1.678     raeburn  4254:     my %grouproles = ();
                   4255:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4256:         my @groupkeys;
1.1000    raeburn  4257:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4258:             push(@groupkeys,$role);
                   4259:         }
                   4260:         if (ref($groups_roles) eq 'HASH') {
                   4261:             foreach my $key (keys(%{$groups_roles})) {
                   4262:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4263:                     push(@groupkeys,$key);
                   4264:                 }
                   4265:             }
                   4266:         }
                   4267:         if (@groupkeys > 0) {
                   4268:             foreach my $role (@groupkeys) {
                   4269:                 my ($trole,$area,$sec,$extendedarea);
                   4270:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4271:                     $trole = $1;
                   4272:                     $area = $2;
                   4273:                     $sec = $3;
                   4274:                     $extendedarea = $area.$sec;
                   4275:                     if (exists($$allgroups{$area})) {
                   4276:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4277:                             my $spec = $trole.'.'.$extendedarea;
                   4278:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4279:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4280:                         }
1.678     raeburn  4281:                     }
                   4282:                 }
                   4283:             }
                   4284:         }
                   4285:     }
1.800     albertel 4286:     foreach my $group (keys(%grouproles)) {
                   4287:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4288:     }
1.800     albertel 4289:     foreach my $role (keys(%{$allroles})) {
                   4290:         my %thesepriv;
1.941     raeburn  4291:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4292:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4293:             if ($item ne '') {
                   4294:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4295:                 if ($restrictions eq '') {
                   4296:                     $thesepriv{$privilege}='F';
                   4297:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4298:                     $thesepriv{$privilege}.=$restrictions;
                   4299:                 }
                   4300:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4301:             }
                   4302:         }
                   4303:         my $thesestr='';
1.800     albertel 4304:         foreach my $priv (keys(%thesepriv)) {
                   4305: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4306: 	}
                   4307:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4308:     }
                   4309:     return ($author,$adv);
                   4310: }
                   4311: 
1.994     raeburn  4312: sub role_status {
1.1002    raeburn  4313:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4314:     my @pwhere = ();
                   4315:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4316:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4317:         unless (!defined($$role) || $$role eq '') {
                   4318:             $$where=join('.',@pwhere);
                   4319:             $$trolecode=$$role.'.'.$$where;
                   4320:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4321:             $$tstatus='is';
                   4322:             if ($$tstart && $$tstart>$then) {
                   4323:                 $$tstatus='future';
1.1034    raeburn  4324:                 if ($$tstart<$now) {
                   4325:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4326:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4327:                             my (%allroles,%allgroups,$group_privs,
                   4328:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4329:                             my %userroles = (
                   4330:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4331:                             );
1.1056.4.2  raeburn  4332:                             @rolecodes = ('cm');
1.1002    raeburn  4333:                             my $spec=$$role.'.'.$$where;
                   4334:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4335:                             if ($$role =~ /^cr\//) {
                   4336:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4337:                                 push(@rolecodes,'cr');
1.1002    raeburn  4338:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4339:                                 push(@rolecodes,$$role);
1.1002    raeburn  4340:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4341:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4342:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4343:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4344:                                 $group_privs = &unescape($group_privs);
                   4345:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4346:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4347:                                 if (keys(%course_roles) > 0) {
                   4348:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4349:                                     if ($tdomain ne '' && $tnum ne '') {
                   4350:                                         foreach my $key (keys(%course_roles)) {
                   4351:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4352:                                                 my $crsrole = $1;
                   4353:                                                 my $crssec = $2;
                   4354:                                                 if ($crsrole =~ /^cr/) {
                   4355:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4356:                                                         push(@rolecodes,'cr');
                   4357:                                                     }
                   4358:                                                 } else {
                   4359:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4360:                                                         push(@rolecodes,$crsrole);
                   4361:                                                     }
                   4362:                                                 }
                   4363:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4364:                                                 if ($crssec ne '') {
                   4365:                                                     $rolekey .= '/'.$crssec;
                   4366:                                                 }
                   4367:                                                 $rolekey .= './';
                   4368:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4369:                                             }
                   4370:                                         }
                   4371:                                     }
                   4372:                                 }
1.1002    raeburn  4373:                             } else {
1.1056.4.2  raeburn  4374:                                 push(@rolecodes,$$role);
1.1002    raeburn  4375:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4376:                             }
1.1056.4.2  raeburn  4377:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4378:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4379:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4380:                         }
                   4381:                     }
1.1034    raeburn  4382:                     $$tstatus = 'is';
1.1002    raeburn  4383:                 }
1.994     raeburn  4384:             }
                   4385:             if ($$tend) {
                   4386:                 if ($$tend<$then) {
                   4387:                     $$tstatus='expired';
                   4388:                 } elsif ($$tend<$now) {
                   4389:                     $$tstatus='will_not';
                   4390:                 }
                   4391:             }
                   4392:         }
                   4393:     }
                   4394: }
                   4395: 
                   4396: sub check_adhoc_privs {
1.1002    raeburn  4397:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4398:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4399:     if ($env{$cckey}) {
                   4400:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4401:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4402:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4403:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4404:         }
                   4405:     } else {
                   4406:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4407:     }
                   4408: }
                   4409: 
                   4410: sub set_adhoc_privileges {
                   4411: # role can be cc or ca
                   4412:     my ($dcdom,$pickedcourse,$role) = @_;
                   4413:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4414:     my $spec = $role.'.'.$area;
                   4415:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4416:                                   $env{'user.name'});
                   4417:     my %ccrole = ();
                   4418:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4419:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4420:     &appenv(\%userroles,[$role,'cm']);
                   4421:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4422:     &appenv( {'request.role'        => $spec,
                   4423:               'request.role.domain' => $dcdom,
                   4424:               'request.course.sec'  => ''
                   4425:              }
                   4426:            );
                   4427:     my $tadv=0;
                   4428:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4429:     &appenv({'request.role.adv'    => $tadv});
                   4430: }
                   4431: 
1.12      www      4432: # --------------------------------------------------------------- get interface
                   4433: 
                   4434: sub get {
1.131     albertel 4435:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4436:    my $items='';
1.800     albertel 4437:    foreach my $item (@$storearr) {
                   4438:        $items.=&escape($item).'&';
1.191     harris41 4439:    }
1.12      www      4440:    $items=~s/\&$//;
1.620     albertel 4441:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4442:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4443:    my $uhome=&homeserver($uname,$udomain);
                   4444: 
1.133     albertel 4445:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4446:    my @pairs=split(/\&/,$rep);
1.273     albertel 4447:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4448:      return @pairs;
                   4449:    }
1.15      www      4450:    my %returnhash=();
1.42      www      4451:    my $i=0;
1.800     albertel 4452:    foreach my $item (@$storearr) {
                   4453:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4454:       $i++;
1.191     harris41 4455:    }
1.15      www      4456:    return %returnhash;
1.27      www      4457: }
                   4458: 
                   4459: # --------------------------------------------------------------- del interface
                   4460: 
                   4461: sub del {
1.133     albertel 4462:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4463:    my $items='';
1.800     albertel 4464:    foreach my $item (@$storearr) {
                   4465:        $items.=&escape($item).'&';
1.191     harris41 4466:    }
1.984     neumanie 4467: 
1.27      www      4468:    $items=~s/\&$//;
1.620     albertel 4469:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4470:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4471:    my $uhome=&homeserver($uname,$udomain);
                   4472:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4473: }
                   4474: 
                   4475: # -------------------------------------------------------------- dump interface
                   4476: 
                   4477: sub dump {
1.755     albertel 4478:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4479:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4480:     if (!$uname) { $uname=$env{'user.name'}; }
                   4481:     my $uhome=&homeserver($uname,$udomain);
                   4482:     if ($regexp) {
                   4483: 	$regexp=&escape($regexp);
                   4484:     } else {
                   4485: 	$regexp='.';
                   4486:     }
                   4487:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4488:     my @pairs=split(/\&/,$rep);
                   4489:     my %returnhash=();
                   4490:     foreach my $item (@pairs) {
                   4491: 	my ($key,$value)=split(/=/,$item,2);
                   4492: 	$key = &unescape($key);
                   4493: 	next if ($key =~ /^error: 2 /);
                   4494: 	$returnhash{$key}=&thaw_unescape($value);
                   4495:     }
                   4496:     return %returnhash;
1.407     www      4497: }
                   4498: 
1.717     albertel 4499: # --------------------------------------------------------- dumpstore interface
                   4500: 
                   4501: sub dumpstore {
                   4502:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4503:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4504:    if (!$uname) { $uname=$env{'user.name'}; }
                   4505:    my $uhome=&homeserver($uname,$udomain);
                   4506:    if ($regexp) {
                   4507:        $regexp=&escape($regexp);
                   4508:    } else {
                   4509:        $regexp='.';
                   4510:    }
                   4511:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4512:    my @pairs=split(/\&/,$rep);
                   4513:    my %returnhash=();
                   4514:    foreach my $item (@pairs) {
                   4515:        my ($key,$value)=split(/=/,$item,2);
                   4516:        next if ($key =~ /^error: 2 /);
                   4517:        $returnhash{$key}=&thaw_unescape($value);
                   4518:    }
                   4519:    return %returnhash;
1.717     albertel 4520: }
                   4521: 
1.407     www      4522: # -------------------------------------------------------------- keys interface
                   4523: 
                   4524: sub getkeys {
                   4525:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4526:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4527:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4528:    my $uhome=&homeserver($uname,$udomain);
                   4529:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4530:    my @keyarray=();
1.800     albertel 4531:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4532:       next if ($key =~ /^error: 2 /);
1.800     albertel 4533:       push(@keyarray,&unescape($key));
1.407     www      4534:    }
                   4535:    return @keyarray;
1.318     matthew  4536: }
                   4537: 
1.319     matthew  4538: # --------------------------------------------------------------- currentdump
                   4539: sub currentdump {
1.328     matthew  4540:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4541:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4542:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4543:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4544:    my $uhome = &homeserver($sname,$sdom);
                   4545:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4546:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4547:    #
1.318     matthew  4548:    my %returnhash=();
1.319     matthew  4549:    #
                   4550:    if ($rep eq "unknown_cmd") { 
                   4551:        # an old lond will not know currentdump
                   4552:        # Do a dump and make it look like a currentdump
1.822     albertel 4553:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4554:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4555:        my %hash = @tmp;
                   4556:        @tmp=();
1.424     matthew  4557:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4558:    } else {
                   4559:        my @pairs=split(/\&/,$rep);
1.800     albertel 4560:        foreach my $pair (@pairs) {
                   4561:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4562:            my ($symb,$param) = split(/:/,$key);
                   4563:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4564:                                                         &thaw_unescape($value);
1.319     matthew  4565:        }
1.191     harris41 4566:    }
1.12      www      4567:    return %returnhash;
1.424     matthew  4568: }
                   4569: 
                   4570: sub convert_dump_to_currentdump{
                   4571:     my %hash = %{shift()};
                   4572:     my %returnhash;
                   4573:     # Code ripped from lond, essentially.  The only difference
                   4574:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4575:     # we might run in to problems with parameter names =~ /^v\./
                   4576:     while (my ($key,$value) = each(%hash)) {
                   4577:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4578: 	$symb  = &unescape($symb);
                   4579: 	$param = &unescape($param);
1.424     matthew  4580:         next if ($v eq 'version' || $symb eq 'keys');
                   4581:         next if (exists($returnhash{$symb}) &&
                   4582:                  exists($returnhash{$symb}->{$param}) &&
                   4583:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4584:         $returnhash{$symb}->{$param}=$value;
                   4585:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4586:     }
                   4587:     #
                   4588:     # Remove all of the keys in the hashes which keep track of
                   4589:     # the version of the parameter.
                   4590:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4591:         # use a foreach because we are going to delete from the hash.
                   4592:         foreach my $key (keys(%$param_hash)) {
                   4593:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4594:         }
                   4595:     }
                   4596:     return \%returnhash;
1.12      www      4597: }
                   4598: 
1.627     albertel 4599: # ------------------------------------------------------ critical inc interface
                   4600: 
                   4601: sub cinc {
                   4602:     return &inc(@_,'critical');
                   4603: }
                   4604: 
1.449     matthew  4605: # --------------------------------------------------------------- inc interface
                   4606: 
                   4607: sub inc {
1.627     albertel 4608:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4609:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4610:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4611:     my $uhome=&homeserver($uname,$udomain);
                   4612:     my $items='';
                   4613:     if (! ref($store)) {
                   4614:         # got a single value, so use that instead
                   4615:         $items = &escape($store).'=&';
                   4616:     } elsif (ref($store) eq 'SCALAR') {
                   4617:         $items = &escape($$store).'=&';        
                   4618:     } elsif (ref($store) eq 'ARRAY') {
                   4619:         $items = join('=&',map {&escape($_);} @{$store});
                   4620:     } elsif (ref($store) eq 'HASH') {
                   4621:         while (my($key,$value) = each(%{$store})) {
                   4622:             $items.= &escape($key).'='.&escape($value).'&';
                   4623:         }
                   4624:     }
                   4625:     $items=~s/\&$//;
1.627     albertel 4626:     if ($critical) {
                   4627: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4628:     } else {
                   4629: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4630:     }
1.449     matthew  4631: }
                   4632: 
1.12      www      4633: # --------------------------------------------------------------- put interface
                   4634: 
                   4635: sub put {
1.134     albertel 4636:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4637:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4638:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4639:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4640:    my $items='';
1.800     albertel 4641:    foreach my $item (keys(%$storehash)) {
                   4642:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4643:    }
1.12      www      4644:    $items=~s/\&$//;
1.134     albertel 4645:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4646: }
                   4647: 
1.631     albertel 4648: # ------------------------------------------------------------ newput interface
                   4649: 
                   4650: sub newput {
                   4651:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4652:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4653:    if (!$uname) { $uname=$env{'user.name'}; }
                   4654:    my $uhome=&homeserver($uname,$udomain);
                   4655:    my $items='';
                   4656:    foreach my $key (keys(%$storehash)) {
                   4657:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4658:    }
                   4659:    $items=~s/\&$//;
                   4660:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4661: }
                   4662: 
                   4663: # ---------------------------------------------------------  putstore interface
                   4664: 
1.524     raeburn  4665: sub putstore {
1.715     albertel 4666:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4667:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4668:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4669:    my $uhome=&homeserver($uname,$udomain);
                   4670:    my $items='';
1.715     albertel 4671:    foreach my $key (keys(%$storehash)) {
                   4672:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4673:    }
1.715     albertel 4674:    $items=~s/\&$//;
1.716     albertel 4675:    my $esc_symb=&escape($symb);
                   4676:    my $esc_v=&escape($version);
1.715     albertel 4677:    my $reply =
1.716     albertel 4678:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4679: 	      $uhome);
                   4680:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4681:        # gfall back to way things use to be done
1.715     albertel 4682:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4683: 			    $uname);
1.524     raeburn  4684:    }
1.715     albertel 4685:    return $reply;
                   4686: }
                   4687: 
                   4688: sub old_putstore {
1.716     albertel 4689:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4690:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4691:     if (!$uname) { $uname=$env{'user.name'}; }
                   4692:     my $uhome=&homeserver($uname,$udomain);
                   4693:     my %newstorehash;
1.800     albertel 4694:     foreach my $item (keys(%$storehash)) {
                   4695: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4696: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4697:     }
                   4698:     my $items='';
                   4699:     my %allitems = ();
1.800     albertel 4700:     foreach my $item (keys(%newstorehash)) {
                   4701: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4702: 	    my $key = $1.':keys:'.$2;
                   4703: 	    $allitems{$key} .= $3.':';
                   4704: 	}
1.800     albertel 4705: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4706:     }
1.800     albertel 4707:     foreach my $item (keys(%allitems)) {
                   4708: 	$allitems{$item} =~ s/\:$//;
                   4709: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4710:     }
                   4711:     $items=~s/\&$//;
                   4712:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4713: }
                   4714: 
1.47      www      4715: # ------------------------------------------------------ critical put interface
                   4716: 
                   4717: sub cput {
1.134     albertel 4718:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4719:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4720:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4721:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4722:    my $items='';
1.800     albertel 4723:    foreach my $item (keys(%$storehash)) {
                   4724:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4725:    }
1.47      www      4726:    $items=~s/\&$//;
1.134     albertel 4727:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4728: }
                   4729: 
                   4730: # -------------------------------------------------------------- eget interface
                   4731: 
                   4732: sub eget {
1.133     albertel 4733:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4734:    my $items='';
1.800     albertel 4735:    foreach my $item (@$storearr) {
                   4736:        $items.=&escape($item).'&';
1.191     harris41 4737:    }
1.12      www      4738:    $items=~s/\&$//;
1.620     albertel 4739:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4740:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4741:    my $uhome=&homeserver($uname,$udomain);
                   4742:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4743:    my @pairs=split(/\&/,$rep);
                   4744:    my %returnhash=();
1.42      www      4745:    my $i=0;
1.800     albertel 4746:    foreach my $item (@$storearr) {
                   4747:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4748:       $i++;
1.191     harris41 4749:    }
1.12      www      4750:    return %returnhash;
                   4751: }
                   4752: 
1.667     albertel 4753: # ------------------------------------------------------------ tmpput interface
                   4754: sub tmpput {
1.802     raeburn  4755:     my ($storehash,$server,$context)=@_;
1.667     albertel 4756:     my $items='';
1.800     albertel 4757:     foreach my $item (keys(%$storehash)) {
                   4758: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4759:     }
                   4760:     $items=~s/\&$//;
1.802     raeburn  4761:     if (defined($context)) {
                   4762:         $items .= ':'.&escape($context);
                   4763:     }
1.667     albertel 4764:     return &reply("tmpput:$items",$server);
                   4765: }
                   4766: 
                   4767: # ------------------------------------------------------------ tmpget interface
                   4768: sub tmpget {
1.688     albertel 4769:     my ($token,$server)=@_;
                   4770:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4771:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4772:     my %returnhash;
                   4773:     foreach my $item (split(/\&/,$rep)) {
                   4774: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4775:         next if ($key =~ /^error: 2 /);
1.667     albertel 4776: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4777:     }
                   4778:     return %returnhash;
                   4779: }
                   4780: 
1.688     albertel 4781: # ------------------------------------------------------------ tmpget interface
                   4782: sub tmpdel {
                   4783:     my ($token,$server)=@_;
                   4784:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4785:     return &reply("tmpdel:$token",$server);
                   4786: }
                   4787: 
1.765     albertel 4788: # -------------------------------------------------- portfolio access checking
                   4789: 
                   4790: sub portfolio_access {
1.766     albertel 4791:     my ($requrl) = @_;
1.765     albertel 4792:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4793:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4794:     if ($result) {
                   4795:         my %setters;
                   4796:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4797:             my ($startblock,$endblock) =
                   4798:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4799:             if ($startblock && $endblock) {
                   4800:                 return 'B';
                   4801:             }
                   4802:         } else {
                   4803:             my ($startblock,$endblock) =
                   4804:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4805:             if ($startblock && $endblock) {
                   4806:                 return 'B';
                   4807:             }
                   4808:         }
                   4809:     }
1.765     albertel 4810:     if ($result eq 'ok') {
1.766     albertel 4811:        return 'F';
1.765     albertel 4812:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4813:        return 'A';
1.765     albertel 4814:     }
1.766     albertel 4815:     return '';
1.765     albertel 4816: }
                   4817: 
                   4818: sub get_portfolio_access {
1.767     albertel 4819:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4820: 
                   4821:     if (!ref($access_hash)) {
                   4822: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4823: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4824: 						   $file_name);
                   4825: 	$access_hash = $access_controls{$file_name};
                   4826:     }
                   4827: 
1.765     albertel 4828:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4829:     my $now = time;
                   4830:     if (ref($access_hash) eq 'HASH') {
                   4831:         foreach my $key (keys(%{$access_hash})) {
                   4832:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4833:             if ($start > $now) {
                   4834:                 next;
                   4835:             }
                   4836:             if ($end && $end<$now) {
                   4837:                 next;
                   4838:             }
                   4839:             if ($scope eq 'public') {
                   4840:                 $public = $key;
                   4841:                 last;
                   4842:             } elsif ($scope eq 'guest') {
                   4843:                 $guest = $key;
                   4844:             } elsif ($scope eq 'domains') {
                   4845:                 push(@domains,$key);
                   4846:             } elsif ($scope eq 'users') {
                   4847:                 push(@users,$key);
                   4848:             } elsif ($scope eq 'course') {
                   4849:                 push(@courses,$key);
                   4850:             } elsif ($scope eq 'group') {
                   4851:                 push(@groups,$key);
                   4852:             }
                   4853:         }
                   4854:         if ($public) {
                   4855:             return 'ok';
                   4856:         }
                   4857:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4858:             if ($guest) {
                   4859:                 return $guest;
                   4860:             }
                   4861:         } else {
                   4862:             if (@domains > 0) {
                   4863:                 foreach my $domkey (@domains) {
                   4864:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4865:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4866:                             return 'ok';
                   4867:                         }
                   4868:                     }
                   4869:                 }
                   4870:             }
                   4871:             if (@users > 0) {
                   4872:                 foreach my $userkey (@users) {
1.865     raeburn  4873:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4874:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4875:                             if (ref($item) eq 'HASH') {
                   4876:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4877:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4878:                                     return 'ok';
                   4879:                                 }
                   4880:                             }
                   4881:                         }
                   4882:                     } 
1.765     albertel 4883:                 }
                   4884:             }
                   4885:             my %roleshash;
                   4886:             my @courses_and_groups = @courses;
                   4887:             push(@courses_and_groups,@groups); 
                   4888:             if (@courses_and_groups > 0) {
                   4889:                 my (%allgroups,%allroles); 
                   4890:                 my ($start,$end,$role,$sec,$group);
                   4891:                 foreach my $envkey (%env) {
1.1056.4.1  raeburn  4892:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4893:                         my $cid = $2.'_'.$3; 
                   4894:                         if ($1 eq 'gr') {
                   4895:                             $group = $4;
                   4896:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4897:                         } else {
                   4898:                             if ($4 eq '') {
                   4899:                                 $sec = 'none';
                   4900:                             } else {
                   4901:                                 $sec = $4;
                   4902:                             }
                   4903:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4904:                         }
1.811     albertel 4905:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4906:                         my $cid = $2.'_'.$3;
                   4907:                         if ($4 eq '') {
                   4908:                             $sec = 'none';
                   4909:                         } else {
                   4910:                             $sec = $4;
                   4911:                         }
                   4912:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4913:                     }
                   4914:                 }
                   4915:                 if (keys(%allroles) == 0) {
                   4916:                     return;
                   4917:                 }
                   4918:                 foreach my $key (@courses_and_groups) {
                   4919:                     my %content = %{$$access_hash{$key}};
                   4920:                     my $cnum = $content{'number'};
                   4921:                     my $cdom = $content{'domain'};
                   4922:                     my $cid = $cdom.'_'.$cnum;
                   4923:                     if (!exists($allroles{$cid})) {
                   4924:                         next;
                   4925:                     }    
                   4926:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4927:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4928:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4929:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4930:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4931:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4932:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4933:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4934:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4935:                                         if (grep/^all$/,@sections) {
                   4936:                                             return 'ok';
                   4937:                                         } else {
                   4938:                                             if (grep/^$sec$/,@sections) {
                   4939:                                                 return 'ok';
                   4940:                                             }
                   4941:                                         }
                   4942:                                     }
                   4943:                                 }
                   4944:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4945:                                     if (grep/^none$/,@groups) {
                   4946:                                         return 'ok';
                   4947:                                     }
                   4948:                                 } else {
                   4949:                                     if (grep/^all$/,@groups) {
                   4950:                                         return 'ok';
                   4951:                                     } 
                   4952:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4953:                                         if (grep/^$group$/,@groups) {
                   4954:                                             return 'ok';
                   4955:                                         }
                   4956:                                     }
                   4957:                                 } 
                   4958:                             }
                   4959:                         }
                   4960:                     }
                   4961:                 }
                   4962:             }
                   4963:             if ($guest) {
                   4964:                 return $guest;
                   4965:             }
                   4966:         }
                   4967:     }
                   4968:     return;
                   4969: }
                   4970: 
                   4971: sub course_group_datechecker {
                   4972:     my ($dates,$now,$status) = @_;
                   4973:     my ($start,$end) = split(/\./,$dates);
                   4974:     if (!$start && !$end) {
                   4975:         return 'ok';
                   4976:     }
                   4977:     if (grep/^active$/,@{$status}) {
                   4978:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4979:             return 'ok';
                   4980:         }
                   4981:     }
                   4982:     if (grep/^previous$/,@{$status}) {
                   4983:         if ($end > $now ) {
                   4984:             return 'ok';
                   4985:         }
                   4986:     }
                   4987:     if (grep/^future$/,@{$status}) {
                   4988:         if ($start > $now) {
                   4989:             return 'ok';
                   4990:         }
                   4991:     }
                   4992:     return; 
                   4993: }
                   4994: 
                   4995: sub parse_portfolio_url {
                   4996:     my ($url) = @_;
                   4997: 
                   4998:     my ($type,$udom,$unum,$group,$file_name);
                   4999:     
1.823     albertel 5000:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5001: 	$type = 1;
                   5002:         $udom = $1;
                   5003:         $unum = $2;
                   5004:         $file_name = $3;
1.823     albertel 5005:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5006: 	$type = 2;
                   5007:         $udom = $1;
                   5008:         $unum = $2;
                   5009:         $group = $3;
                   5010:         $file_name = $3.'/'.$4;
                   5011:     }
                   5012:     if (wantarray) {
                   5013: 	return ($type,$udom,$unum,$file_name,$group);
                   5014:     }
                   5015:     return $type;
                   5016: }
                   5017: 
                   5018: sub is_portfolio_url {
                   5019:     my ($url) = @_;
                   5020:     return scalar(&parse_portfolio_url($url));
                   5021: }
                   5022: 
1.798     raeburn  5023: sub is_portfolio_file {
                   5024:     my ($file) = @_;
1.820     raeburn  5025:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5026:         return 1;
                   5027:     }
                   5028:     return;
                   5029: }
                   5030: 
1.976     raeburn  5031: sub usertools_access {
1.1056.4.9! raeburn  5032:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985     raeburn  5033:     my ($access,%tools);
                   5034:     if ($context eq '') {
                   5035:         $context = 'tools';
                   5036:     }
                   5037:     if ($context eq 'requestcourses') {
                   5038:         %tools = (
                   5039:                       official   => 1,
                   5040:                       unofficial => 1,
1.1006    raeburn  5041:                       community  => 1,
1.985     raeburn  5042:                  );
                   5043:     } else {
                   5044:         %tools = (
                   5045:                       aboutme   => 1,
                   5046:                       blog      => 1,
                   5047:                       portfolio => 1,
                   5048:                  );
                   5049:     }
1.976     raeburn  5050:     return if (!defined($tools{$tool}));
                   5051: 
                   5052:     if ((!defined($udom)) || (!defined($uname))) {
                   5053:         $udom = $env{'user.domain'};
                   5054:         $uname = $env{'user.name'};
                   5055:     }
                   5056: 
1.978     raeburn  5057:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5058:         if ($action ne 'reload') {
1.985     raeburn  5059:             if ($context eq 'requestcourses') {
                   5060:                 return $env{'environment.canrequest.'.$tool};
                   5061:             } else {
                   5062:                 return $env{'environment.availabletools.'.$tool};
                   5063:             }
                   5064:         }
1.976     raeburn  5065:     }
                   5066: 
                   5067:     my ($toolstatus,$inststatus);
                   5068: 
1.985     raeburn  5069:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5070:          ($action ne 'reload')) {
                   5071:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5072:         $inststatus = $env{'environment.inststatus'};
                   5073:     } else {
1.1056.4.9! raeburn  5074:         if (ref($userenvref) eq 'HASH') {
        !          5075:             $toolstatus = $userenvref->{$context.'.'.$tool};
        !          5076:             $inststatus = $userenvref->{'inststatus'};
        !          5077:         } else {
        !          5078:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
        !          5079:             $toolstatus = $userenv{$context.'.'.$tool};
        !          5080:             $inststatus = $userenv{'inststatus'};
        !          5081:         }
1.976     raeburn  5082:     }
                   5083: 
                   5084:     if ($toolstatus ne '') {
                   5085:         if ($toolstatus) {
                   5086:             $access = 1;
                   5087:         } else {
                   5088:             $access = 0;
                   5089:         }
                   5090:         return $access;
                   5091:     }
                   5092: 
1.1056.4.9! raeburn  5093:     my ($is_adv,%domdef);
        !          5094:     if (ref($is_advref) eq 'HASH') {
        !          5095:         $is_adv = $is_advref->{'is_adv'};
        !          5096:     } else {
        !          5097:         $is_adv = &is_advanced_user($udom,$uname);
        !          5098:     }
        !          5099:     if (ref($domdefref) eq 'HASH') {
        !          5100:         %domdef = %{$domdefref};
        !          5101:     } else {
        !          5102:         %domdef = &get_domain_defaults($udom);
        !          5103:     }
1.976     raeburn  5104:     if (ref($domdef{$tool}) eq 'HASH') {
                   5105:         if ($is_adv) {
                   5106:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5107:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5108:                     $access = 1;
                   5109:                 } else {
                   5110:                     $access = 0;
                   5111:                 }
                   5112:                 return $access;
                   5113:             }
                   5114:         }
                   5115:         if ($inststatus ne '') {
                   5116:             my ($hasaccess,$hasnoaccess);
                   5117:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5118:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5119:                     if ($domdef{$tool}{$affiliation}) {
                   5120:                         $hasaccess = 1;
                   5121:                     } else {
                   5122:                         $hasnoaccess = 1;
                   5123:                     }
                   5124:                 }
                   5125:             }
                   5126:             if ($hasaccess || $hasnoaccess) {
                   5127:                 if ($hasaccess) {
                   5128:                     $access = 1;
                   5129:                 } elsif ($hasnoaccess) {
                   5130:                     $access = 0; 
                   5131:                 }
                   5132:                 return $access;
                   5133:             }
                   5134:         } else {
                   5135:             if ($domdef{$tool}{'default'} ne '') {
                   5136:                 if ($domdef{$tool}{'default'}) {
                   5137:                     $access = 1;
                   5138:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5139:                     $access = 0;
                   5140:                 }
                   5141:                 return $access;
                   5142:             }
                   5143:         }
                   5144:     } else {
1.985     raeburn  5145:         if ($context eq 'tools') {
                   5146:             $access = 1;
                   5147:         } else {
                   5148:             $access = 0;
                   5149:         }
1.976     raeburn  5150:         return $access;
                   5151:     }
                   5152: }
                   5153: 
1.1050    raeburn  5154: sub is_course_owner {
                   5155:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5156:     if (($udom eq '') || ($uname eq '')) {
                   5157:         $udom = $env{'user.domain'};
                   5158:         $uname = $env{'user.name'};
                   5159:     }
                   5160:     unless (($udom eq '') || ($uname eq '')) {
                   5161:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5162:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5163:                 return 1;
                   5164:             } else {
                   5165:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5166:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5167:                     return 1;
                   5168:                 }
                   5169:             }
                   5170:         }
                   5171:     }
                   5172:     return;
                   5173: }
                   5174: 
1.976     raeburn  5175: sub is_advanced_user {
                   5176:     my ($udom,$uname) = @_;
                   5177:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5178:     my %allroles;
                   5179:     my $is_adv;
                   5180:     foreach my $role (keys(%roleshash)) {
                   5181:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5182:         my $area = '/'.$tdomain.'/'.$trest;
                   5183:         if ($sec ne '') {
                   5184:             $area .= '/'.$sec;
                   5185:         }
                   5186:         if (($area ne '') && ($trole ne '')) {
                   5187:             my $spec=$trole.'.'.$area;
                   5188:             if ($trole =~ /^cr\//) {
                   5189:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5190:             } elsif ($trole ne 'gr') {
                   5191:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5192:             }
                   5193:         }
                   5194:     }
                   5195:     foreach my $role (keys(%allroles)) {
                   5196:         last if ($is_adv);
                   5197:         foreach my $item (split(/:/,$allroles{$role})) {
                   5198:             if ($item ne '') {
                   5199:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5200:                 if ($privilege eq 'adv') {
                   5201:                     $is_adv = 1;
                   5202:                     last;
                   5203:                 }
                   5204:             }
                   5205:         }
                   5206:     }
                   5207:     return $is_adv;
                   5208: }
1.798     raeburn  5209: 
1.1035    raeburn  5210: sub check_can_request {
1.1036    raeburn  5211:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5212:     my $canreq = 0;
                   5213:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5214:     my @options = ('approval','validate','autolimit');
                   5215:     my $optregex = join('|',@options);
                   5216:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5217:         foreach my $type (@{$types}) {
                   5218:             if (&usertools_access($env{'user.name'},
                   5219:                                   $env{'user.domain'},
                   5220:                                   $type,undef,'requestcourses')) {
                   5221:                 $canreq ++;
1.1036    raeburn  5222:                 if (ref($request_domains) eq 'HASH') {
                   5223:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5224:                 }
1.1035    raeburn  5225:                 if ($dom eq $env{'user.domain'}) {
                   5226:                     $can_request->{$type} = 1;
                   5227:                 }
                   5228:             }
                   5229:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5230:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5231:                 if (@curr > 0) {
1.1036    raeburn  5232:                     foreach my $item (@curr) {
                   5233:                         if (ref($request_domains) eq 'HASH') {
                   5234:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5235:                             if ($otherdom ne '') {
                   5236:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5237:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5238:                                         push(@{$request_domains->{$type}},$otherdom);
                   5239:                                     }
                   5240:                                 } else {
                   5241:                                     push(@{$request_domains->{$type}},$otherdom);
                   5242:                                 }
                   5243:                             }
                   5244:                         }
                   5245:                     }
                   5246:                     unless($dom eq $env{'user.domain'}) {
                   5247:                         $canreq ++;
1.1035    raeburn  5248:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5249:                             $can_request->{$type} = 1;
                   5250:                         }
                   5251:                     }
                   5252:                 }
                   5253:             }
                   5254:         }
                   5255:     }
                   5256:     return $canreq;
                   5257: }
                   5258: 
1.341     www      5259: # ---------------------------------------------- Custom access rule evaluation
                   5260: 
                   5261: sub customaccess {
                   5262:     my ($priv,$uri)=@_;
1.807     albertel 5263:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5264:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5265:     $udom = &LONCAPA::clean_domain($udom);
                   5266:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5267:     my $access=0;
1.800     albertel 5268:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5269: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5270: 	if ($type eq 'user') {
                   5271: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5272: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5273: 		if ($tdom) {
                   5274: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5275: 		}
1.896     albertel 5276: 		if ($tuname) {
                   5277: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5278: 		}
                   5279: 		$access=($effect eq 'allow');
                   5280: 		last;
                   5281: 	    }
                   5282: 	} else {
                   5283: 	    if ($role) {
                   5284: 		if ($role ne $urole) { next; }
                   5285: 	    }
                   5286: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5287: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5288: 		if ($tdom) {
                   5289: 		    if ($tdom ne $udom) { next; }
                   5290: 		}
                   5291: 		if ($tcrs) {
                   5292: 		    if ($tcrs ne $ucrs) { next; }
                   5293: 		}
                   5294: 		if ($tsec) {
                   5295: 		    if ($tsec ne $usec) { next; }
                   5296: 		}
                   5297: 		$access=($effect eq 'allow');
                   5298: 		last;
                   5299: 	    }
                   5300: 	    if ($realm eq '' && $role eq '') {
                   5301: 		$access=($effect eq 'allow');
                   5302: 	    }
1.402     bowersj2 5303: 	}
1.341     www      5304:     }
                   5305:     return $access;
                   5306: }
                   5307: 
1.103     harris41 5308: # ------------------------------------------------- Check for a user privilege
1.12      www      5309: 
                   5310: sub allowed {
1.810     raeburn  5311:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5312:     my $ver_orguri=$uri;
1.439     www      5313:     $uri=&deversion($uri);
1.152     www      5314:     my $orguri=$uri;
1.52      www      5315:     $uri=&declutter($uri);
1.809     raeburn  5316: 
1.810     raeburn  5317:     if ($priv eq 'evb') {
                   5318: # Evade communication block restrictions for specified role in a course
                   5319:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5320:             return $1;
                   5321:         } else {
                   5322:             return;
                   5323:         }
                   5324:     }
                   5325: 
1.620     albertel 5326:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5327: # Free bre access to adm and meta resources
1.775     albertel 5328:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5329: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5330: 	&& ($priv eq 'bre')) {
1.14      www      5331: 	return 'F';
1.159     www      5332:     }
                   5333: 
1.545     banghart 5334: # Free bre access to user's own portfolio contents
1.714     raeburn  5335:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5336:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5337: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5338:         my %setters;
                   5339:         my ($startblock,$endblock) = 
                   5340:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5341:         if ($startblock && $endblock) {
                   5342:             return 'B';
                   5343:         } else {
                   5344:             return 'F';
                   5345:         }
1.545     banghart 5346:     }
                   5347: 
1.762     raeburn  5348: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5349:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5350:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5351:         if (exists($env{'request.course.id'})) {
                   5352:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5353:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5354:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5355:                 my $courseprivid=$env{'request.course.id'};
                   5356:                 $courseprivid=~s/\_/\//;
                   5357:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5358:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5359:                     return $1; 
1.762     raeburn  5360:                 } else {
                   5361:                     if ($env{'request.course.sec'}) {
                   5362:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5363:                     }
                   5364:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5365:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5366:                         return $2;
                   5367:                     }
1.714     raeburn  5368:                 }
                   5369:             }
                   5370:         }
                   5371:     }
                   5372: 
1.159     www      5373: # Free bre to public access
                   5374: 
                   5375:     if ($priv eq 'bre') {
1.238     www      5376:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5377: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5378:            return 'F'; 
                   5379:         }
1.238     www      5380:         if ($copyright eq 'priv') {
                   5381:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5382: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5383: 		return '';
                   5384:             }
                   5385:         }
                   5386:         if ($copyright eq 'domain') {
                   5387:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5388: 	    unless (($env{'user.domain'} eq $1) ||
                   5389:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5390: 		return '';
                   5391:             }
1.262     matthew  5392:         }
1.620     albertel 5393:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5394:             # Library role, so allow browsing of resources in this domain.
                   5395:             return 'F';
1.238     www      5396:         }
1.341     www      5397:         if ($copyright eq 'custom') {
                   5398: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5399:         }
1.14      www      5400:     }
1.264     matthew  5401:     # Domain coordinator is trying to create a course
1.620     albertel 5402:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5403:         # uri is the requested domain in this case.
                   5404:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5405:         # a role of dc for the domain in question.
1.620     albertel 5406:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5407:     }
1.29      www      5408: 
1.52      www      5409:     my $thisallowed='';
                   5410:     my $statecond=0;
                   5411:     my $courseprivid='';
                   5412: 
1.1039    raeburn  5413:     my $ownaccess;
1.1043    raeburn  5414:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5415:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5416:         if ($uri eq '') {
                   5417:             $ownaccess = 1;
                   5418:         } else {
                   5419:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5420:                 my $udom = $env{'user.domain'};
                   5421:                 my $uname = $env{'user.name'};
                   5422:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5423:                     $ownaccess = 1;
1.1040    raeburn  5424:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5425:                     unless ($uri =~ m{\.\./}) {
                   5426:                         $ownaccess = 1;
                   5427:                     }
                   5428:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5429:                     my $now = time;
                   5430:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5431:                         my $adom = $1;
                   5432:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5433:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5434:                                 my ($start,$end) = split('.',$env{$key});
                   5435:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5436:                                     $ownaccess = 1;
                   5437:                                     last;
                   5438:                                 }
                   5439:                             }
                   5440:                         }
                   5441:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5442:                         my $adom = $1;
                   5443:                         my $aname = $2;
1.1042    raeburn  5444:                         foreach my $role ('ca','aa') { 
                   5445:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5446:                                 my ($start,$end) =
                   5447:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5448:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5449:                                     $ownaccess = 1;
                   5450:                                     last;
                   5451:                                 }
1.1039    raeburn  5452:                             }
                   5453:                         }
                   5454:                     }
                   5455:                 }
                   5456:             }
                   5457:         }
                   5458:     }
                   5459: 
1.52      www      5460: # Course
                   5461: 
1.620     albertel 5462:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5463:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5464:             $thisallowed.=$1;
                   5465:         }
1.52      www      5466:     }
1.29      www      5467: 
1.52      www      5468: # Domain
                   5469: 
1.620     albertel 5470:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5471:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5472:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5473:             $thisallowed.=$1;
                   5474:         }
1.12      www      5475:     }
1.52      www      5476: 
                   5477: # Course: uri itself is a course
1.66      www      5478:     my $courseuri=$uri;
                   5479:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5480:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5481: 
1.620     albertel 5482:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5483:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5484:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5485:             $thisallowed.=$1;
                   5486:         }
1.12      www      5487:     }
1.29      www      5488: 
1.665     albertel 5489: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5490: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5491:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5492: 	$thisallowed='';
1.671     raeburn  5493:         my ($match)=&is_on_map($uri);
                   5494:         if ($match) {
                   5495:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5496:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5497:                 $thisallowed.=$1;
                   5498:             }
                   5499:         } else {
1.705     albertel 5500:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5501:             if ($refuri) {
                   5502:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5503:                     $thisallowed='F';
1.671     raeburn  5504:                 } else {
                   5505:                     $refuri=&declutter($refuri);
                   5506:                     my ($match) = &is_on_map($refuri);
                   5507:                     if ($match) {
                   5508:                         $thisallowed='F';
                   5509:                     }
1.669     raeburn  5510:                 }
1.671     raeburn  5511:             }
                   5512:         }
1.314     www      5513:     }
1.492     albertel 5514: 
1.766     albertel 5515:     if ($priv eq 'bre'
                   5516: 	&& $thisallowed ne 'F' 
                   5517: 	&& $thisallowed ne '2'
                   5518: 	&& &is_portfolio_url($uri)) {
                   5519: 	$thisallowed = &portfolio_access($uri);
                   5520:     }
                   5521:     
1.52      www      5522: # Full access at system, domain or course-wide level? Exit.
1.29      www      5523:     if ($thisallowed=~/F/) {
                   5524: 	return 'F';
                   5525:     }
                   5526: 
1.52      www      5527: # If this is generating or modifying users, exit with special codes
1.29      www      5528: 
1.643     www      5529:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5530: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5531: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5532: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5533: 	    unless ($auname) { return $thisallowed; }
                   5534: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5535: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5536: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5537: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5538: 	}
1.52      www      5539: 	return $thisallowed;
                   5540:     }
                   5541: #
1.103     harris41 5542: # Gathered so far: system, domain and course wide privileges
1.52      www      5543: #
                   5544: # Course: See if uri or referer is an individual resource that is part of 
                   5545: # the course
                   5546: 
1.620     albertel 5547:     if ($env{'request.course.id'}) {
1.232     www      5548: 
1.620     albertel 5549:        $courseprivid=$env{'request.course.id'};
                   5550:        if ($env{'request.course.sec'}) {
                   5551:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5552:        }
                   5553:        $courseprivid=~s/\_/\//;
                   5554:        my $checkreferer=1;
1.232     www      5555:        my ($match,$cond)=&is_on_map($uri);
                   5556:        if ($match) {
                   5557:            $statecond=$cond;
1.620     albertel 5558:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5559:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5560:                $thisallowed.=$1;
                   5561:                $checkreferer=0;
                   5562:            }
1.29      www      5563:        }
1.83      www      5564:        
1.148     www      5565:        if ($checkreferer) {
1.620     albertel 5566: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5567:             unless ($refuri) {
1.800     albertel 5568:                 foreach my $key (keys(%env)) {
                   5569: 		    if ($key=~/^httpref\..*\*/) {
                   5570: 			my $pattern=$key;
1.156     www      5571:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5572:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5573:                         $pattern=~s/\//\\\//g;
1.152     www      5574:                         if ($orguri=~/$pattern/) {
1.800     albertel 5575: 			    $refuri=$env{$key};
1.148     www      5576:                         }
                   5577:                     }
1.191     harris41 5578:                 }
1.148     www      5579:             }
1.232     www      5580: 
1.148     www      5581:          if ($refuri) { 
1.152     www      5582: 	  $refuri=&declutter($refuri);
1.232     www      5583:           my ($match,$cond)=&is_on_map($refuri);
                   5584:             if ($match) {
                   5585:               my $refstatecond=$cond;
1.620     albertel 5586:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5587:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5588:                   $thisallowed.=$1;
1.53      www      5589:                   $uri=$refuri;
                   5590:                   $statecond=$refstatecond;
1.52      www      5591:               }
                   5592:           }
1.148     www      5593:         }
1.29      www      5594:        }
1.52      www      5595:    }
1.29      www      5596: 
1.52      www      5597: #
1.103     harris41 5598: # Gathered now: all privileges that could apply, and condition number
1.52      www      5599: # 
                   5600: #
                   5601: # Full or no access?
                   5602: #
1.29      www      5603: 
1.52      www      5604:     if ($thisallowed=~/F/) {
                   5605: 	return 'F';
                   5606:     }
1.29      www      5607: 
1.52      www      5608:     unless ($thisallowed) {
                   5609:         return '';
                   5610:     }
1.29      www      5611: 
1.52      www      5612: # Restrictions exist, deal with them
                   5613: #
                   5614: #   C:according to course preferences
                   5615: #   R:according to resource settings
                   5616: #   L:unless locked
                   5617: #   X:according to user session state
                   5618: #
                   5619: 
                   5620: # Possibly locked functionality, check all courses
1.54      www      5621: # Locks might take effect only after 10 minutes cache expiration for other
                   5622: # courses, and 2 minutes for current course
1.52      www      5623: 
                   5624:     my $envkey;
                   5625:     if ($thisallowed=~/L/) {
1.1000    raeburn  5626:         foreach $envkey (keys(%env)) {
1.54      www      5627:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5628:                my $courseid=$2;
                   5629:                my $roleid=$1.'.'.$2;
1.92      www      5630:                $courseid=~s/^\///;
1.54      www      5631:                my $expiretime=600;
1.620     albertel 5632:                if ($env{'request.role'} eq $roleid) {
1.54      www      5633: 		  $expiretime=120;
                   5634:                }
                   5635: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5636:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5637:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5638: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5639:                }
1.620     albertel 5640:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5641:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5642: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5643:                        &log($env{'user.domain'},$env{'user.name'},
                   5644:                             $env{'user.home'},
1.57      www      5645:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5646:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5647:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5648: 		       return '';
                   5649:                    }
                   5650:                }
1.620     albertel 5651:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5652:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5653: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5654:                        &log($env{'user.domain'},$env{'user.name'},
                   5655:                             $env{'user.home'},
1.57      www      5656:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5657:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5658:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5659: 		       return '';
                   5660:                    }
                   5661:                }
                   5662: 	   }
1.29      www      5663:        }
1.52      www      5664:     }
                   5665:    
                   5666: #
                   5667: # Rest of the restrictions depend on selected course
                   5668: #
                   5669: 
1.620     albertel 5670:     unless ($env{'request.course.id'}) {
1.766     albertel 5671: 	if ($thisallowed eq 'A') {
                   5672: 	    return 'A';
1.814     raeburn  5673:         } elsif ($thisallowed eq 'B') {
                   5674:             return 'B';
1.766     albertel 5675: 	} else {
                   5676: 	    return '1';
                   5677: 	}
1.52      www      5678:     }
1.29      www      5679: 
1.52      www      5680: #
                   5681: # Now user is definitely in a course
                   5682: #
1.53      www      5683: 
                   5684: 
                   5685: # Course preferences
                   5686: 
                   5687:    if ($thisallowed=~/C/) {
1.620     albertel 5688:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5689:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5690:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5691: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5692: 	   if ($priv ne 'pch') { 
                   5693: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5694: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5695: 			$env{'request.course.id'});
                   5696: 	   }
1.237     www      5697:            return '';
                   5698:        }
                   5699: 
1.620     albertel 5700:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5701: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5702: 	   if ($priv ne 'pch') { 
                   5703: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5704: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5705: 			$env{'request.course.id'});
                   5706: 	   }
1.54      www      5707:            return '';
                   5708:        }
1.53      www      5709:    }
                   5710: 
                   5711: # Resource preferences
                   5712: 
                   5713:    if ($thisallowed=~/R/) {
1.620     albertel 5714:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5715:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5716: 	   if ($priv ne 'pch') { 
                   5717: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5718: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5719: 	   }
                   5720: 	   return '';
1.54      www      5721:        }
1.53      www      5722:    }
1.30      www      5723: 
1.246     www      5724: # Restricted by state or randomout?
1.30      www      5725: 
1.52      www      5726:    if ($thisallowed=~/X/) {
1.620     albertel 5727:       if ($env{'acc.randomout'}) {
1.579     albertel 5728: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5729:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5730:             return ''; 
                   5731:          }
1.247     www      5732:       }
                   5733:       if (&condval($statecond)) {
1.52      www      5734: 	 return '2';
                   5735:       } else {
                   5736:          return '';
                   5737:       }
                   5738:    }
1.30      www      5739: 
1.766     albertel 5740:     if ($thisallowed eq 'A') {
                   5741: 	return 'A';
1.814     raeburn  5742:     } elsif ($thisallowed eq 'B') {
                   5743:         return 'B';
1.766     albertel 5744:     }
1.52      www      5745:    return 'F';
1.232     www      5746: }
                   5747: 
1.710     albertel 5748: sub split_uri_for_cond {
                   5749:     my $uri=&deversion(&declutter(shift));
                   5750:     my @uriparts=split(/\//,$uri);
                   5751:     my $filename=pop(@uriparts);
                   5752:     my $pathname=join('/',@uriparts);
                   5753:     return ($pathname,$filename);
                   5754: }
1.232     www      5755: # --------------------------------------------------- Is a resource on the map?
                   5756: 
                   5757: sub is_on_map {
1.710     albertel 5758:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5759:     #Trying to find the conditional for the file
1.620     albertel 5760:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5761: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5762:     if ($match) {
1.289     bowersj2 5763: 	return (1,$1);
                   5764:     } else {
1.434     www      5765: 	return (0,0);
1.289     bowersj2 5766:     }
1.12      www      5767: }
                   5768: 
1.427     www      5769: # --------------------------------------------------------- Get symb from alias
                   5770: 
                   5771: sub get_symb_from_alias {
                   5772:     my $symb=shift;
                   5773:     my ($map,$resid,$url)=&decode_symb($symb);
                   5774: # Already is a symb
                   5775:     if ($url) { return $symb; }
                   5776: # Must be an alias
                   5777:     my $aliassymb='';
                   5778:     my %bighash;
1.620     albertel 5779:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5780:                             &GDBM_READER(),0640)) {
                   5781:         my $rid=$bighash{'mapalias_'.$symb};
                   5782: 	if ($rid) {
                   5783: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5784: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5785: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5786: 	}
                   5787:         untie %bighash;
                   5788:     }
                   5789:     return $aliassymb;
                   5790: }
                   5791: 
1.12      www      5792: # ----------------------------------------------------------------- Define Role
                   5793: 
                   5794: sub definerole {
                   5795:   if (allowed('mcr','/')) {
                   5796:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5797:     foreach my $role (split(':',$sysrole)) {
                   5798: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5799:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5800:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5801: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5802:                return "refused:s:$crole&$cqual"; 
                   5803:             }
                   5804:         }
1.191     harris41 5805:     }
1.800     albertel 5806:     foreach my $role (split(':',$domrole)) {
                   5807: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5808:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5809:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5810: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5811:                return "refused:d:$crole&$cqual"; 
                   5812:             }
                   5813:         }
1.191     harris41 5814:     }
1.800     albertel 5815:     foreach my $role (split(':',$courole)) {
                   5816: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5817:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5818:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5819: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5820:                return "refused:c:$crole&$cqual"; 
                   5821:             }
                   5822:         }
1.191     harris41 5823:     }
1.620     albertel 5824:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5825:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5826: 	        "rolesdef_$rolename=".
                   5827:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5828:     return reply($command,$env{'user.home'});
1.12      www      5829:   } else {
                   5830:     return 'refused';
                   5831:   }
1.105     harris41 5832: }
                   5833: 
                   5834: # ---------------- Make a metadata query against the network of library servers
                   5835: 
                   5836: sub metadata_query {
1.244     matthew  5837:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5838:     my %rhash;
1.845     albertel 5839:     my %libserv = &all_library();
1.244     matthew  5840:     my @server_list = (defined($server_array) ? @$server_array
                   5841:                                               : keys(%libserv) );
                   5842:     for my $server (@server_list) {
1.118     harris41 5843: 	unless ($custom or $customshow) {
                   5844: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5845: 	    $rhash{$server}=$reply;
                   5846: 	}
                   5847: 	else {
                   5848: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5849: 			     &escape($custom).':'.&escape($customshow),
                   5850: 			     $server);
                   5851: 	    $rhash{$server}=$reply;
                   5852: 	}
1.112     harris41 5853:     }
1.118     harris41 5854:     return \%rhash;
1.240     www      5855: }
                   5856: 
                   5857: # ----------------------------------------- Send log queries and wait for reply
                   5858: 
                   5859: sub log_query {
                   5860:     my ($uname,$udom,$query,%filters)=@_;
                   5861:     my $uhome=&homeserver($uname,$udom);
                   5862:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5863:     my $uhost=&hostname($uhome);
1.800     albertel 5864:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5865:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5866:                        $uhome);
1.479     albertel 5867:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5868:     return get_query_reply($queryid);
                   5869: }
                   5870: 
1.818     raeburn  5871: # -------------------------- Update MySQL table for portfolio file
                   5872: 
                   5873: sub update_portfolio_table {
1.821     raeburn  5874:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5875:     if ($group ne '') {
                   5876:         $file_name =~s /^\Q$group\E//;
                   5877:     }
1.818     raeburn  5878:     my $homeserver = &homeserver($uname,$udom);
                   5879:     my $queryid=
1.821     raeburn  5880:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5881:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5882:     my $reply = &get_query_reply($queryid);
                   5883:     return $reply;
                   5884: }
                   5885: 
1.899     raeburn  5886: # -------------------------- Update MySQL allusers table
                   5887: 
                   5888: sub update_allusers_table {
                   5889:     my ($uname,$udom,$names) = @_;
                   5890:     my $homeserver = &homeserver($uname,$udom);
                   5891:     my $queryid=
                   5892:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5893:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5894:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5895:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5896:                'generation='.&escape($names->{'generation'}).'%%'.
                   5897:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5898:                'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4  raeburn  5899:     return;
1.899     raeburn  5900: }
                   5901: 
1.508     raeburn  5902: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5903: 
                   5904: sub fetch_enrollment_query {
1.511     raeburn  5905:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5906:     my $homeserver;
1.547     raeburn  5907:     my $maxtries = 1;
1.508     raeburn  5908:     if ($context eq 'automated') {
                   5909:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5910:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5911:     } else {
                   5912:         $homeserver = &homeserver($cnum,$dom);
                   5913:     }
1.838     albertel 5914:     my $host=&hostname($homeserver);
1.506     raeburn  5915:     my $cmd = '';
1.1000    raeburn  5916:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5917:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5918:     }
                   5919:     $cmd =~ s/%%$//;
                   5920:     $cmd = &escape($cmd);
                   5921:     my $query = 'fetchenrollment';
1.620     albertel 5922:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5923:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5924:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5925:         return 'error: '.$queryid;
                   5926:     }
1.506     raeburn  5927:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5928:     my $tries = 1;
                   5929:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5930:         $reply = &get_query_reply($queryid);
                   5931:         $tries ++;
                   5932:     }
1.526     raeburn  5933:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5934:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5935:     } else {
1.901     albertel 5936:         my @responses = split(/:/,$reply);
1.515     raeburn  5937:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5938:             foreach my $line (@responses) {
                   5939:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5940:                 $$replyref{$key} = $value;
                   5941:             }
                   5942:         } else {
1.506     raeburn  5943:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5944:             foreach my $line (@responses) {
                   5945:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5946:                 $$replyref{$key} = $value;
                   5947:                 if ($value > 0) {
1.800     albertel 5948:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5949:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5950:                         my $destname = $pathname.'/'.$filename;
                   5951:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5952:                         if ($xml_classlist =~ /^error/) {
                   5953:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5954:                         } else {
1.506     raeburn  5955:                             if ( open(FILE,">$destname") ) {
                   5956:                                 print FILE &unescape($xml_classlist);
                   5957:                                 close(FILE);
1.526     raeburn  5958:                             } else {
                   5959:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5960:                             }
                   5961:                         }
                   5962:                     }
                   5963:                 }
                   5964:             }
                   5965:         }
                   5966:         return 'ok';
                   5967:     }
                   5968:     return 'error';
                   5969: }
                   5970: 
1.242     www      5971: sub get_query_reply {
                   5972:     my $queryid=shift;
1.240     www      5973:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5974:     my $reply='';
                   5975:     for (1..100) {
                   5976: 	sleep 2;
                   5977:         if (-e $replyfile.'.end') {
1.448     albertel 5978: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5979: 		$reply = join('',<$fh>);
                   5980: 		close($fh);
1.240     www      5981: 	   } else { return 'error: reply_file_error'; }
1.242     www      5982:            return &unescape($reply);
                   5983: 	}
1.240     www      5984:     }
1.242     www      5985:     return 'timeout:'.$queryid;
1.240     www      5986: }
                   5987: 
                   5988: sub courselog_query {
1.241     www      5989: #
                   5990: # possible filters:
                   5991: # url: url or symb
                   5992: # username
                   5993: # domain
                   5994: # action: view, submit, grade
                   5995: # start: timestamp
                   5996: # end: timestamp
                   5997: #
1.240     www      5998:     my (%filters)=@_;
1.620     albertel 5999:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6000:     if ($filters{'url'}) {
                   6001: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6002:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6003:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6004:     }
1.620     albertel 6005:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6006:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6007:     return &log_query($cname,$cdom,'courselog',%filters);
                   6008: }
                   6009: 
                   6010: sub userlog_query {
1.858     raeburn  6011: #
                   6012: # possible filters:
                   6013: # action: log check role
                   6014: # start: timestamp
                   6015: # end: timestamp
                   6016: #
1.240     www      6017:     my ($uname,$udom,%filters)=@_;
                   6018:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6019: }
                   6020: 
1.506     raeburn  6021: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6022: 
                   6023: sub auto_run {
1.508     raeburn  6024:     my ($cnum,$cdom) = @_;
1.876     raeburn  6025:     my $response = 0;
                   6026:     my $settings;
                   6027:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6028:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6029:         $settings = $domconfig{'autoenroll'};
                   6030:         if ($settings->{'run'} eq '1') {
                   6031:             $response = 1;
                   6032:         }
                   6033:     } else {
1.934     raeburn  6034:         my $homeserver;
                   6035:         if (&is_course($cdom,$cnum)) {
                   6036:             $homeserver = &homeserver($cnum,$cdom);
                   6037:         } else {
                   6038:             $homeserver = &domain($cdom,'primary');
                   6039:         }
                   6040:         if ($homeserver ne 'no_host') {
                   6041:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6042:         }
1.876     raeburn  6043:     }
1.506     raeburn  6044:     return $response;
                   6045: }
1.776     albertel 6046: 
1.506     raeburn  6047: sub auto_get_sections {
1.508     raeburn  6048:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6049:     my $homeserver;
                   6050:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6051:         $homeserver = &homeserver($cnum,$cdom);
                   6052:     }
                   6053:     if (!defined($homeserver)) { 
                   6054:         if ($cdom =~ /^$match_domain$/) {
                   6055:             $homeserver = &domain($cdom,'primary');
                   6056:         }
                   6057:     }
                   6058:     my @secs;
                   6059:     if (defined($homeserver)) {
                   6060:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6061:         unless ($response eq 'refused') {
                   6062:             @secs = split(/:/,$response);
                   6063:         }
1.506     raeburn  6064:     }
                   6065:     return @secs;
                   6066: }
1.776     albertel 6067: 
1.506     raeburn  6068: sub auto_new_course {
1.508     raeburn  6069:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   6070:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  6071:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  6072:     return $response;
                   6073: }
1.776     albertel 6074: 
1.506     raeburn  6075: sub auto_validate_courseID {
1.508     raeburn  6076:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6077:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6078:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6079:     return $response;
                   6080: }
1.776     albertel 6081: 
1.1007    raeburn  6082: sub auto_validate_instcode {
1.1020    raeburn  6083:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6084:     my ($homeserver,$response);
                   6085:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6086:         $homeserver = &homeserver($cnum,$cdom);
                   6087:     }
                   6088:     if (!defined($homeserver)) {
                   6089:         if ($cdom =~ /^$match_domain$/) {
                   6090:             $homeserver = &domain($cdom,'primary');
                   6091:         }
                   6092:     }
1.1056.4.2  raeburn  6093:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6094:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6095:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6096:     return ($outcome,$description);
1.1007    raeburn  6097: }
                   6098: 
1.506     raeburn  6099: sub auto_create_password {
1.873     raeburn  6100:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6101:     my ($homeserver,$response);
1.506     raeburn  6102:     my $create_passwd = 0;
                   6103:     my $authchk = '';
1.873     raeburn  6104:     if ($udom =~ /^$match_domain$/) {
                   6105:         $homeserver = &domain($udom,'primary');
                   6106:     }
                   6107:     if ($homeserver eq '') {
                   6108:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6109:             $homeserver = &homeserver($cnum,$cdom);
                   6110:         }
                   6111:     }
                   6112:     if ($homeserver eq '') {
                   6113:         $authchk = 'nodomain';
1.506     raeburn  6114:     } else {
1.873     raeburn  6115:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6116:         if ($response eq 'refused') {
                   6117:             $authchk = 'refused';
                   6118:         } else {
1.901     albertel 6119:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6120:         }
1.506     raeburn  6121:     }
                   6122:     return ($authparam,$create_passwd,$authchk);
                   6123: }
                   6124: 
1.706     raeburn  6125: sub auto_photo_permission {
                   6126:     my ($cnum,$cdom,$students) = @_;
                   6127:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6128:     my ($outcome,$perm_reqd,$conditions) = 
                   6129: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6130:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6131: 	return (undef,undef);
                   6132:     }
1.706     raeburn  6133:     return ($outcome,$perm_reqd,$conditions);
                   6134: }
                   6135: 
                   6136: sub auto_checkphotos {
                   6137:     my ($uname,$udom,$pid) = @_;
                   6138:     my $homeserver = &homeserver($uname,$udom);
                   6139:     my ($result,$resulttype);
                   6140:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6141: 				   &escape($uname).':'.&escape($pid),
                   6142: 				   $homeserver));
1.709     albertel 6143:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6144: 	return (undef,undef);
                   6145:     }
1.706     raeburn  6146:     if ($outcome) {
                   6147:         ($result,$resulttype) = split(/:/,$outcome);
                   6148:     } 
                   6149:     return ($result,$resulttype);
                   6150: }
                   6151: 
                   6152: sub auto_photochoice {
                   6153:     my ($cnum,$cdom) = @_;
                   6154:     my $homeserver = &homeserver($cnum,$cdom);
                   6155:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6156: 						       &escape($cdom),
                   6157: 						       $homeserver)));
1.709     albertel 6158:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6159: 	return (undef,undef);
                   6160:     }
1.706     raeburn  6161:     return ($update,$comment);
                   6162: }
                   6163: 
                   6164: sub auto_photoupdate {
                   6165:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6166:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6167:     my $host=&hostname($homeserver);
1.706     raeburn  6168:     my $cmd = '';
                   6169:     my $maxtries = 1;
1.800     albertel 6170:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6171:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6172:     }
                   6173:     $cmd =~ s/%%$//;
                   6174:     $cmd = &escape($cmd);
                   6175:     my $query = 'institutionalphotos';
                   6176:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6177:     unless ($queryid=~/^\Q$host\E\_/) {
                   6178:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6179:         return 'error: '.$queryid;
                   6180:     }
                   6181:     my $reply = &get_query_reply($queryid);
                   6182:     my $tries = 1;
                   6183:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6184:         $reply = &get_query_reply($queryid);
                   6185:         $tries ++;
                   6186:     }
                   6187:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6188:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6189:     } else {
                   6190:         my @responses = split(/:/,$reply);
                   6191:         my $outcome = shift(@responses); 
                   6192:         foreach my $item (@responses) {
                   6193:             my ($key,$value) = split(/=/,$item);
                   6194:             $$photo{$key} = $value;
                   6195:         }
                   6196:         return $outcome;
                   6197:     }
                   6198:     return 'error';
                   6199: }
                   6200: 
1.521     raeburn  6201: sub auto_instcode_format {
1.793     albertel 6202:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6203: 	$cat_order) = @_;
1.521     raeburn  6204:     my $courses = '';
1.772     raeburn  6205:     my @homeservers;
1.521     raeburn  6206:     if ($caller eq 'global') {
1.841     albertel 6207: 	my %servers = &get_servers($codedom,'library');
                   6208: 	foreach my $tryserver (keys(%servers)) {
                   6209: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6210: 		push(@homeservers,$tryserver);
                   6211: 	    }
1.584     raeburn  6212:         }
1.1022    raeburn  6213:     } elsif ($caller eq 'requests') {
                   6214:         if ($codedom =~ /^$match_domain$/) {
                   6215:             my $chome = &domain($codedom,'primary');
                   6216:             unless ($chome eq 'no_host') {
                   6217:                 push(@homeservers,$chome);
                   6218:             }
                   6219:         }
1.521     raeburn  6220:     } else {
1.772     raeburn  6221:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6222:     }
1.793     albertel 6223:     foreach my $code (keys(%{$instcodes})) {
                   6224:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6225:     }
                   6226:     chop($courses);
1.772     raeburn  6227:     my $ok_response = 0;
                   6228:     my $response;
                   6229:     while (@homeservers > 0 && $ok_response == 0) {
                   6230:         my $server = shift(@homeservers); 
                   6231:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6232:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6233:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6234: 		split(/:/,$response);
1.772     raeburn  6235:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6236:             push(@{$codetitles},&str2array($codetitles_str));
                   6237:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6238:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6239:             $ok_response = 1;
                   6240:         }
                   6241:     }
                   6242:     if ($ok_response) {
1.521     raeburn  6243:         return 'ok';
1.772     raeburn  6244:     } else {
                   6245:         return $response;
1.521     raeburn  6246:     }
                   6247: }
                   6248: 
1.792     raeburn  6249: sub auto_instcode_defaults {
                   6250:     my ($domain,$returnhash,$code_order) = @_;
                   6251:     my @homeservers;
1.841     albertel 6252: 
                   6253:     my %servers = &get_servers($domain,'library');
                   6254:     foreach my $tryserver (keys(%servers)) {
                   6255: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6256: 	    push(@homeservers,$tryserver);
                   6257: 	}
1.792     raeburn  6258:     }
1.841     albertel 6259: 
1.792     raeburn  6260:     my $response;
1.841     albertel 6261:     foreach my $server (@homeservers) {
1.792     raeburn  6262:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6263:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6264: 	
                   6265: 	foreach my $pair (split(/\&/,$response)) {
                   6266: 	    my ($name,$value)=split(/\=/,$pair);
                   6267: 	    if ($name eq 'code_order') {
                   6268: 		@{$code_order} = split(/\&/,&unescape($value));
                   6269: 	    } else {
                   6270: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6271: 	    }
                   6272: 	}
                   6273: 	return 'ok';
1.792     raeburn  6274:     }
1.841     albertel 6275: 
                   6276:     return $response;
1.1003    raeburn  6277: }
                   6278: 
                   6279: sub auto_possible_instcodes {
1.1007    raeburn  6280:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6281:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6282:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6283:         return;
                   6284:     }
1.1003    raeburn  6285:     my (@homeservers,$uhome);
                   6286:     if (defined(&domain($domain,'primary'))) {
                   6287:         $uhome=&domain($domain,'primary');
                   6288:         push(@homeservers,&domain($domain,'primary'));
                   6289:     } else {
                   6290:         my %servers = &get_servers($domain,'library');
                   6291:         foreach my $tryserver (keys(%servers)) {
                   6292:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6293:                 push(@homeservers,$tryserver);
                   6294:             }
                   6295:         }
                   6296:     }
                   6297:     my $response;
                   6298:     foreach my $server (@homeservers) {
                   6299:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6300:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6301:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6302:             split(':',$response);
                   6303:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6304:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6305:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6306:             my ($name,$value)=split('=',$item);
                   6307:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6308:         }
                   6309:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6310:             my ($name,$value)=split('=',$item);
                   6311:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6312:         }
                   6313:         return 'ok';
                   6314:     }
                   6315:     return $response;
                   6316: }
1.792     raeburn  6317: 
1.1010    raeburn  6318: sub auto_courserequest_checks {
                   6319:     my ($dom) = @_;
1.1020    raeburn  6320:     my ($homeserver,%validations);
                   6321:     if ($dom =~ /^$match_domain$/) {
                   6322:         $homeserver = &domain($dom,'primary');
                   6323:     }
                   6324:     unless ($homeserver eq 'no_host') {
                   6325:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6326:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6327:             my @items = split(/&/,$response);
                   6328:             foreach my $item (@items) {
                   6329:                 my ($key,$value) = split('=',$item);
                   6330:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6331:             }
                   6332:         }
                   6333:     }
1.1010    raeburn  6334:     return %validations; 
                   6335: }
                   6336: 
1.1020    raeburn  6337: sub auto_courserequest_validation {
                   6338:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6339:     my ($homeserver,$response);
                   6340:     if ($dom =~ /^$match_domain$/) {
                   6341:         $homeserver = &domain($dom,'primary');
                   6342:     }
                   6343:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6344:           
1.1020    raeburn  6345:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6346:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6347:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6348:                                     $homeserver));
                   6349:     }
                   6350:     return $response;
                   6351: }
                   6352: 
1.777     albertel 6353: sub auto_validate_class_sec {
1.918     raeburn  6354:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6355:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6356:     my $ownerlist;
                   6357:     if (ref($owners) eq 'ARRAY') {
                   6358:         $ownerlist = join(',',@{$owners});
                   6359:     } else {
                   6360:         $ownerlist = $owners;
                   6361:     }
1.773     raeburn  6362:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6363:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6364:     return $response;
                   6365: }
                   6366: 
1.679     raeburn  6367: # ------------------------------------------------------- Course Group routines
                   6368: 
                   6369: sub get_coursegroups {
1.809     raeburn  6370:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6371:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6372: }
                   6373: 
1.679     raeburn  6374: sub modify_coursegroup {
                   6375:     my ($cdom,$cnum,$groupsettings) = @_;
                   6376:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6377: }
                   6378: 
1.809     raeburn  6379: sub toggle_coursegroup_status {
                   6380:     my ($cdom,$cnum,$group,$action) = @_;
                   6381:     my ($from_namespace,$to_namespace);
                   6382:     if ($action eq 'delete') {
                   6383:         $from_namespace = 'coursegroups';
                   6384:         $to_namespace = 'deleted_groups';
                   6385:     } else {
                   6386:         $from_namespace = 'deleted_groups';
                   6387:         $to_namespace = 'coursegroups';
                   6388:     }
                   6389:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6390:     if (my $tmp = &error(%curr_group)) {
                   6391:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6392:         return ('read error',$tmp);
                   6393:     } else {
                   6394:         my %savedsettings = %curr_group; 
1.809     raeburn  6395:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6396:         my $deloutcome;
                   6397:         if ($result eq 'ok') {
1.809     raeburn  6398:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6399:         } else {
                   6400:             return ('write error',$result);
                   6401:         }
                   6402:         if ($deloutcome eq 'ok') {
                   6403:             return 'ok';
                   6404:         } else {
                   6405:             return ('delete error',$deloutcome);
                   6406:         }
                   6407:     }
                   6408: }
                   6409: 
1.679     raeburn  6410: sub modify_group_roles {
1.957     raeburn  6411:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6412:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6413:     my $role = 'gr/'.&escape($userprivs);
                   6414:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6415:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6416:     if ($result eq 'ok') {
                   6417:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6418:     }
1.679     raeburn  6419:     return $result;
                   6420: }
                   6421: 
                   6422: sub modify_coursegroup_membership {
                   6423:     my ($cdom,$cnum,$membership) = @_;
                   6424:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6425:     return $result;
                   6426: }
                   6427: 
1.682     raeburn  6428: sub get_active_groups {
                   6429:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6430:     my $now = time;
                   6431:     my %groups = ();
                   6432:     foreach my $key (keys(%env)) {
1.811     albertel 6433:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6434:             my ($start,$end) = split(/\./,$env{$key});
                   6435:             if (($end!=0) && ($end<$now)) { next; }
                   6436:             if (($start!=0) && ($start>$now)) { next; }
                   6437:             if ($1 eq $cdom && $2 eq $cnum) {
                   6438:                 $groups{$3} = $env{$key} ;
                   6439:             }
                   6440:         }
                   6441:     }
                   6442:     return %groups;
                   6443: }
                   6444: 
1.683     raeburn  6445: sub get_group_membership {
                   6446:     my ($cdom,$cnum,$group) = @_;
                   6447:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6448: }
                   6449: 
                   6450: sub get_users_groups {
                   6451:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6452:     my @usersgroups;
1.683     raeburn  6453:     my $cachetime=1800;
                   6454: 
                   6455:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6456:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6457:     if (defined($cached)) {
1.734     albertel 6458:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6459:     } else {  
                   6460:         $grouplist = '';
1.816     raeburn  6461:         my $courseurl = &courseid_to_courseurl($courseid);
                   6462:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  6463:         my $access_end = $env{'course.'.$courseid.
                   6464:                               '.default_enrollment_end_date'};
                   6465:         my $now = time;
                   6466:         foreach my $key (keys(%roleshash)) {
                   6467:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6468:                 my $group = $1;
                   6469:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6470:                     my $start = $2;
                   6471:                     my $end = $1;
                   6472:                     if ($start == -1) { next; } # deleted from group
                   6473:                     if (($start!=0) && ($start>$now)) { next; }
                   6474:                     if (($end!=0) && ($end<$now)) {
                   6475:                         if ($access_end && $access_end < $now) {
                   6476:                             if ($access_end - $end < 86400) {
                   6477:                                 push(@usersgroups,$group);
1.733     raeburn  6478:                             }
                   6479:                         }
1.817     raeburn  6480:                         next;
1.733     raeburn  6481:                     }
1.817     raeburn  6482:                     push(@usersgroups,$group);
1.683     raeburn  6483:                 }
                   6484:             }
                   6485:         }
1.817     raeburn  6486:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6487:         $grouplist = join(':',@usersgroups);
                   6488:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6489:     }
1.733     raeburn  6490:     return @usersgroups;
1.683     raeburn  6491: }
                   6492: 
                   6493: sub devalidate_getgroups_cache {
                   6494:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6495:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6496: 
1.683     raeburn  6497:     my $hashid="$udom:$uname:$courseid";
                   6498:     &devalidate_cache_new('getgroups',$hashid);
                   6499: }
                   6500: 
1.12      www      6501: # ------------------------------------------------------------------ Plain Text
                   6502: 
                   6503: sub plaintext {
1.988     raeburn  6504:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6505:     if ($short =~ m{^cr/}) {
1.758     albertel 6506: 	return (split('/',$short))[-1];
                   6507:     }
1.742     raeburn  6508:     if (!defined($cid)) {
                   6509:         $cid = $env{'request.course.id'};
                   6510:     }
                   6511:     my %rolenames = (
1.1008    raeburn  6512:                       Course    => 'std',
                   6513:                       Community => 'alt1',
1.742     raeburn  6514:                     );
1.1037    raeburn  6515:     if ($cid ne '') {
                   6516:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6517:             unless ($forcedefault) {
                   6518:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6519:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6520:                 return &Apache::lonlocal::mt($roletext);
                   6521:             }
                   6522:         }
                   6523:     }
                   6524:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6525:         (defined($rolenames{$type})) && 
                   6526:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6527:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6528:     } elsif ($cid ne '') {
                   6529:         my $crstype = $env{'course.'.$cid.'.type'};
                   6530:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6531:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6532:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6533:         }
1.742     raeburn  6534:     }
1.1037    raeburn  6535:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6536: }
                   6537: 
                   6538: # ----------------------------------------------------------------- Assign Role
                   6539: 
                   6540: sub assignrole {
1.957     raeburn  6541:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6542:         $context)=@_;
1.21      www      6543:     my $mrole;
                   6544:     if ($role =~ /^cr\//) {
1.393     www      6545:         my $cwosec=$url;
1.811     albertel 6546:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6547: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6548:            my $refused = 1;
                   6549:            if ($context eq 'requestcourses') {
                   6550:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6551:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6552:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6553:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6554:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6555:                            if ($crsenv{'internal.courseowner'} eq
                   6556:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6557:                                $refused = '';
                   6558:                            }
                   6559:                        }
                   6560:                    }
                   6561:                }
                   6562:            }
                   6563:            if ($refused) {
                   6564:                &logthis('Refused custom assignrole: '.
                   6565:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6566:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6567:                return 'refused';
                   6568:            }
1.104     www      6569:         }
1.21      www      6570:         $mrole='cr';
1.678     raeburn  6571:     } elsif ($role =~ /^gr\//) {
                   6572:         my $cwogrp=$url;
1.811     albertel 6573:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6574:         unless (&allowed('mdg',$cwogrp)) {
                   6575:             &logthis('Refused group assignrole: '.
                   6576:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6577:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6578:             return 'refused';
                   6579:         }
                   6580:         $mrole='gr';
1.21      www      6581:     } else {
1.82      www      6582:         my $cwosec=$url;
1.811     albertel 6583:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6584:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6585:             my $refused;
                   6586:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6587:                 if (!(&allowed('c'.$role,$url))) {
                   6588:                     $refused = 1;
                   6589:                 }
                   6590:             } else {
                   6591:                 $refused = 1;
                   6592:             }
1.947     raeburn  6593:             if ($refused) {
1.1045    raeburn  6594:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6595:                 if (!$selfenroll && $context eq 'course') {
                   6596:                     my %crsenv;
                   6597:                     if ($role eq 'cc' || $role eq 'co') {
                   6598:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6599:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6600:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6601:                                 if ($crsenv{'internal.courseowner'} eq 
                   6602:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6603:                                     $refused = '';
                   6604:                                 }
                   6605:                             }
                   6606:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6607:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6608:                                 if ($crsenv{'internal.courseowner'} eq 
                   6609:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6610:                                     $refused = '';
                   6611:                                 }
                   6612:                             }
                   6613:                         }
                   6614:                     }
                   6615:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6616:                     $refused = '';
1.1017    raeburn  6617:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6618:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6619:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6620:                         my $wrongcc;
                   6621:                         if ($cnum =~ /^$match_community$/) {
                   6622:                             $wrongcc = 1 if ($role eq 'cc');
                   6623:                         } else {
                   6624:                             $wrongcc = 1 if ($role eq 'co');
                   6625:                         }
                   6626:                         unless ($wrongcc) {
                   6627:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6628:                             if ($crsenv{'internal.courseowner'} eq 
                   6629:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6630:                                 $refused = '';
                   6631:                             }
1.1017    raeburn  6632:                         }
                   6633:                     }
                   6634:                 }
                   6635:                 if ($refused) {
1.947     raeburn  6636:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6637:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6638: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6639:                     return 'refused';
                   6640:                 }
1.932     raeburn  6641:             }
1.104     www      6642:         }
1.21      www      6643:         $mrole=$role;
                   6644:     }
1.620     albertel 6645:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6646:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6647:     if ($end) { $command.='_'.$end; }
1.21      www      6648:     if ($start) {
                   6649: 	if ($end) { 
1.81      www      6650:            $command.='_'.$start; 
1.21      www      6651:         } else {
1.81      www      6652:            $command.='_0_'.$start;
1.21      www      6653:         }
                   6654:     }
1.739     raeburn  6655:     my $origstart = $start;
                   6656:     my $origend = $end;
1.957     raeburn  6657:     my $delflag;
1.357     www      6658: # actually delete
                   6659:     if ($deleteflag) {
1.373     www      6660: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6661: # modify command to delete the role
1.620     albertel 6662:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6663:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6664: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6665: # set start and finish to negative values for userrolelog
                   6666:            $start=-1;
                   6667:            $end=-1;
1.957     raeburn  6668:            $delflag = 1;
1.357     www      6669:         }
                   6670:     }
                   6671: # send command
1.349     www      6672:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6673: # log new user role if status is ok
1.349     www      6674:     if ($answer eq 'ok') {
1.663     raeburn  6675: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6676: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6677:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6678:         unless ($role =~ /^gr/) {
                   6679:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6680:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6681:         }
1.1053    raeburn  6682:         if ($role eq 'cc') {
                   6683:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6684:         }
1.349     www      6685:     }
                   6686:     return $answer;
1.169     harris41 6687: }
                   6688: 
1.1053    raeburn  6689: sub autoupdate_coowners {
                   6690:     my ($url,$end,$start,$uname,$udom) = @_;
                   6691:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6692:     if (($cdom ne '') && ($cnum ne '')) {
                   6693:         my $now = time;
                   6694:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6695:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6696:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6697:             my $instcode = $coursehash{'internal.coursecode'};
                   6698:             if ($instcode ne '') {
1.1056    raeburn  6699:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6700:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6701:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6702:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6703:                         if ($result eq 'valid') {
                   6704:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6705:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6706:                                     push(@newcoowners,$coowner);
                   6707:                                 }
                   6708:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6709:                                     push(@newcoowners,$uname.':'.$udom);
                   6710:                                 }
                   6711:                                 @newcoowners = sort(@newcoowners);
                   6712:                             } else {
                   6713:                                 push(@newcoowners,$uname.':'.$udom);
                   6714:                             }
                   6715:                         } else {
                   6716:                             if ($coursehash{'internal.co-owners'}) {
                   6717:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6718:                                     unless ($coowner eq $uname.':'.$udom) {
                   6719:                                         push(@newcoowners,$coowner);
                   6720:                                     }
                   6721:                                 }
                   6722:                                 unless (@newcoowners > 0) {
                   6723:                                     $delcoowners = 1;
                   6724:                                     $coowners = '';
                   6725:                                 }
                   6726:                             }
                   6727:                         }
                   6728:                         if (@newcoowners || $delcoowners) {
                   6729:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6730:                                             $delcoowners,@newcoowners);
                   6731:                         }
                   6732:                     }
                   6733:                 }
                   6734:             }
                   6735:         }
                   6736:     }
                   6737: }
                   6738: 
                   6739: sub store_coowners {
                   6740:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6741:     my $cid = $cdom.'_'.$cnum;
                   6742:     my ($coowners,$delresult,$putresult);
                   6743:     if (@newcoowners) {
                   6744:         $coowners = join(',',@newcoowners);
                   6745:         my %coownershash = (
                   6746:                             'internal.co-owners' => $coowners,
                   6747:                            );
                   6748:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6749:         if ($putresult eq 'ok') {
                   6750:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6751:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6752:             }
                   6753:         }
                   6754:     }
                   6755:     if ($delcoowners) {
                   6756:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6757:         if ($delresult eq 'ok') {
                   6758:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6759:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6760:             }
                   6761:         }
                   6762:     }
                   6763:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6764:         my %crsinfo =
                   6765:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6766:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6767:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6768:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6769:         }
                   6770:     }
                   6771: }
                   6772: 
1.169     harris41 6773: # -------------------------------------------------- Modify user authentication
1.197     www      6774: # Overrides without validation
                   6775: 
1.169     harris41 6776: sub modifyuserauth {
                   6777:     my ($udom,$uname,$umode,$upass)=@_;
                   6778:     my $uhome=&homeserver($uname,$udom);
1.197     www      6779:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6780:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6781:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6782:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6783:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6784: 		     &escape($upass),$uhome);
1.620     albertel 6785:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6786:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6787:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6788:     &log($udom,,$uname,$uhome,
1.620     albertel 6789:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6790:                                      $env{'user.name'}.', '.$umode.
1.197     www      6791:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6792:     unless ($reply eq 'ok') {
1.197     www      6793:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6794: 	return 'error: '.$reply;
                   6795:     }   
1.170     harris41 6796:     return 'ok';
1.80      www      6797: }
                   6798: 
1.81      www      6799: # --------------------------------------------------------------- Modify a user
1.80      www      6800: 
1.81      www      6801: sub modifyuser {
1.206     matthew  6802:     my ($udom,    $uname, $uid,
                   6803:         $umode,   $upass, $first,
                   6804:         $middle,  $last,  $gene,
1.1056.4.1  raeburn  6805:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6806:     $udom= &LONCAPA::clean_domain($udom);
                   6807:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  raeburn  6808:     my $showcandelete = 'none';
                   6809:     if (ref($candelete) eq 'ARRAY') {
                   6810:         if (@{$candelete} > 0) {
                   6811:             $showcandelete = join(', ',@{$candelete});
                   6812:         }
                   6813:     }
1.81      www      6814:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6815:              $umode.', '.$first.', '.$middle.', '.
1.1056.4.1  raeburn  6816:              $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6817:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6818:                                      ' desiredhome not specified'). 
1.620     albertel 6819:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6820:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6821:     my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4  raeburn  6822:     my $newuser;
                   6823:     if ($uhome eq 'no_host') {
                   6824:         $newuser = 1;
                   6825:     }
1.80      www      6826: # ----------------------------------------------------------------- Create User
1.406     albertel 6827:     if (($uhome eq 'no_host') && 
                   6828: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6829:         my $unhome='';
1.844     albertel 6830:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6831:             $unhome = $desiredhome;
1.620     albertel 6832: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6833: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6834:         } else { # load balancing routine for determining $unhome
1.81      www      6835:             my $loadm=10000000;
1.841     albertel 6836: 	    my %servers = &get_servers($udom,'library');
                   6837: 	    foreach my $tryserver (keys(%servers)) {
                   6838: 		my $answer=reply('load',$tryserver);
                   6839: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6840: 		    $loadm=$answer;
                   6841: 		    $unhome=$tryserver;
                   6842: 		}
1.80      www      6843: 	    }
                   6844:         }
                   6845:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6846: 	    return 'error: unable to find a home server for '.$uname.
                   6847:                    ' in domain '.$udom;
1.80      www      6848:         }
                   6849:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6850:                          &escape($upass),$unhome);
                   6851: 	unless ($reply eq 'ok') {
                   6852:             return 'error: '.$reply;
                   6853:         }   
1.230     stredwic 6854:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6855:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6856: 	    return 'error: unable verify users home machine.';
1.80      www      6857:         }
1.209     matthew  6858:     }   # End of creation of new user
1.80      www      6859: # ---------------------------------------------------------------------- Add ID
                   6860:     if ($uid) {
                   6861:        $uid=~tr/A-Z/a-z/;
                   6862:        my %uidhash=&idrget($udom,$uname);
1.196     www      6863:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6864:          && (!$forceid)) {
1.80      www      6865: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6866: 	      return 'error: user id "'.$uid.'" does not match '.
                   6867:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6868:           }
                   6869:        } else {
                   6870: 	  &idput($udom,($uname => $uid));
                   6871:        }
                   6872:     }
                   6873: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6874:     my @tmp=&get('environment',
1.899     raeburn  6875: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6876:                     'permanentemail','inststatus'],
1.134     albertel 6877: 		   $udom,$uname);
1.1056.4.4  raeburn  6878:     my (%names,%oldnames);
1.313     matthew  6879:     if ($tmp[0] =~ m/^error:.*/) { 
                   6880:         %names=(); 
                   6881:     } else {
                   6882:         %names = @tmp;
1.1056.4.4  raeburn  6883:         %oldnames = %names;
1.313     matthew  6884:     }
1.1056.4.6  raeburn  6885: #
1.1056.4.1  raeburn  6886: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6887: # of users did not contain them), do not overwrite existing values
                   6888: # unless field is in $candelete array ref.  
                   6889: #
                   6890: 
                   6891:     my @fields = ('firstname','middlename','lastname','generation',
                   6892:                   'permanentemail','id');
                   6893:     my %newvalues;
                   6894:     if (ref($candelete) eq 'ARRAY') {
                   6895:         foreach my $field (@fields) {
                   6896:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6897:                 if ($field eq 'firstname') {
                   6898:                     $names{$field} = $first;
                   6899:                 } elsif ($field eq 'middlename') {
                   6900:                     $names{$field} = $middle;
                   6901:                 } elsif ($field eq 'lastname') {
                   6902:                     $names{$field} = $last;
                   6903:                 } elsif ($field eq 'generation') { 
                   6904:                     $names{$field} = $gene;
                   6905:                 } elsif ($field eq 'permanentemail') {
                   6906:                     $names{$field} = $email;
                   6907:                 } elsif ($field eq 'id') {
                   6908:                     $names{$field}  = $uid;
                   6909:                 }
                   6910:             }
                   6911:         }
                   6912:     }
1.388     www      6913:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6914:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6915:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6916:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6917:     if ($email) {
                   6918:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6919:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6920:     }
1.899     raeburn  6921:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6922:     if (defined($inststatus)) {
                   6923:         $names{'inststatus'} = '';
                   6924:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6925:         if (ref($usertypes) eq 'HASH') {
                   6926:             my @okstatuses; 
                   6927:             foreach my $item (split(/:/,$inststatus)) {
                   6928:                 if (defined($usertypes->{$item})) {
                   6929:                     push(@okstatuses,$item);  
                   6930:                 }
                   6931:             }
                   6932:             if (@okstatuses) {
                   6933:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6934:             }
                   6935:         }
                   6936:     }
1.1056.4.4  raeburn  6937:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6938:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  raeburn  6939:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6940:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6941:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6942:     } else {
                   6943:         $logmsg .= ' during self creation';
                   6944:     }
1.1056.4.4  raeburn  6945:     my $changed;
                   6946:     if ($newuser) {
                   6947:         $changed = 1;
                   6948:     } else {
                   6949:         foreach my $field (@fields) {
                   6950:             if ($names{$field} ne $oldnames{$field}) {
                   6951:                 $changed = 1;
                   6952:                 last;
                   6953:             }
                   6954:         }
                   6955:     }
                   6956:     unless ($changed) {
                   6957:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6958:         &logthis($logmsg);
                   6959:         return 'ok';
                   6960:     }
                   6961:     my $reply = &put('environment', \%names, $udom,$uname);
                   6962:     if ($reply ne 'ok') {
                   6963:         return 'error: '.$reply;
                   6964:     }
                   6965:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6966:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6967:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6968:     &logthis($logmsg);
1.134     albertel 6969:     return 'ok';
1.80      www      6970: }
                   6971: 
1.81      www      6972: # -------------------------------------------------------------- Modify student
1.80      www      6973: 
1.81      www      6974: sub modifystudent {
                   6975:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6976:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6977:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6978:     if (!$cid) {
1.620     albertel 6979: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6980: 	    return 'not_in_class';
                   6981: 	}
1.80      www      6982:     }
                   6983: # --------------------------------------------------------------- Make the user
1.81      www      6984:     my $reply=&modifyuser
1.209     matthew  6985: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6986:          $desiredhome,$email,$inststatus);
1.80      www      6987:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6988:     # This will cause &modify_student_enrollment to get the uid from the
                   6989:     # students environment
                   6990:     $uid = undef if (!$forceid);
1.455     albertel 6991:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6992: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6993:     return $reply;
                   6994: }
                   6995: 
                   6996: sub modify_student_enrollment {
1.957     raeburn  6997:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6998:     my ($cdom,$cnum,$chome);
                   6999:     if (!$cid) {
1.620     albertel 7000: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7001: 	    return 'not_in_class';
                   7002: 	}
1.620     albertel 7003: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7004: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7005:     } else {
                   7006: 	($cdom,$cnum)=split(/_/,$cid);
                   7007:     }
1.620     albertel 7008:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7009:     if (!$chome) {
1.457     raeburn  7010: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7011:     }
1.455     albertel 7012:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7013:     # Make sure the user exists
1.81      www      7014:     my $uhome=&homeserver($uname,$udom);
                   7015:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7016: 	return 'error: no such user';
                   7017:     }
1.297     matthew  7018:     # Get student data if we were not given enough information
                   7019:     if (!defined($first)  || $first  eq '' || 
                   7020:         !defined($last)   || $last   eq '' || 
                   7021:         !defined($uid)    || $uid    eq '' || 
                   7022:         !defined($middle) || $middle eq '' || 
                   7023:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7024:         # They did not supply us with enough data to enroll the student, so
                   7025:         # we need to pick up more information.
1.297     matthew  7026:         my %tmp = &get('environment',
1.294     matthew  7027:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7028:                        ,$udom,$uname);
                   7029: 
1.800     albertel 7030:         #foreach my $key (keys(%tmp)) {
                   7031:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7032:         #}
1.294     matthew  7033:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7034:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7035:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7036:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7037:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7038:     }
1.556     albertel 7039:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7040:     my $reply=cput('classlist',
                   7041: 		   {"$uname:$udom" => 
1.515     raeburn  7042: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7043: 		   $cdom,$cnum);
1.81      www      7044:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7045: 	return 'error: '.$reply;
1.652     albertel 7046:     } else {
                   7047: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7048:     }
1.297     matthew  7049:     # Add student role to user
1.83      www      7050:     my $uurl='/'.$cid;
1.81      www      7051:     $uurl=~s/\_/\//g;
                   7052:     if ($usec) {
                   7053: 	$uurl.='/'.$usec;
                   7054:     }
1.957     raeburn  7055:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7056: }
                   7057: 
1.556     albertel 7058: sub format_name {
                   7059:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7060:     my $name;
                   7061:     if ($first ne 'lastname') {
                   7062: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7063:     } else {
                   7064: 	if ($lastname=~/\S/) {
                   7065: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7066: 	    $name=~s/\s+,/,/;
                   7067: 	} else {
                   7068: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7069: 	}
                   7070:     }
                   7071:     $name=~s/^\s+//;
                   7072:     $name=~s/\s+$//;
                   7073:     $name=~s/\s+/ /g;
                   7074:     return $name;
                   7075: }
                   7076: 
1.84      www      7077: # ------------------------------------------------- Write to course preferences
                   7078: 
                   7079: sub writecoursepref {
                   7080:     my ($courseid,%prefs)=@_;
                   7081:     $courseid=~s/^\///;
                   7082:     $courseid=~s/\_/\//g;
                   7083:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7084:     my $chome=homeserver($cnum,$cdomain);
                   7085:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7086: 	return 'error: no such course';
                   7087:     }
                   7088:     my $cstring='';
1.800     albertel 7089:     foreach my $pref (keys(%prefs)) {
                   7090: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7091:     }
1.84      www      7092:     $cstring=~s/\&$//;
                   7093:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7094: }
                   7095: 
                   7096: # ---------------------------------------------------------- Make/modify course
                   7097: 
                   7098: sub createcourse {
1.741     raeburn  7099:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7100:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7101:     $url=&declutter($url);
                   7102:     my $cid='';
1.1028    raeburn  7103:     if ($context eq 'requestcourses') {
                   7104:         my $can_create = 0;
                   7105:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7106:         if ($udom eq $ownerdom) {
                   7107:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7108:                                   $context)) {
                   7109:                 $can_create = 1;
                   7110:             }
                   7111:         } else {
                   7112:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7113:                                            $category);
                   7114:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7115:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7116:                 if (@curr > 0) {
                   7117:                     my @options = qw(approval validate autolimit);
                   7118:                     my $optregex = join('|',@options);
                   7119:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7120:                         $can_create = 1;
                   7121:                     }
                   7122:                 }
                   7123:             }
                   7124:         }
                   7125:         if ($can_create) {
                   7126:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7127:                 unless (&allowed('ccc',$udom)) {
                   7128:                     return 'refused'; 
                   7129:                 }
1.1017    raeburn  7130:             }
                   7131:         } else {
                   7132:             return 'refused';
                   7133:         }
1.1028    raeburn  7134:     } elsif (!&allowed('ccc',$udom)) {
                   7135:         return 'refused';
1.84      www      7136:     }
1.1011    raeburn  7137: # --------------------------------------------------------------- Get Unique ID
                   7138:     my $uname;
                   7139:     if ($cnum =~ /^$match_courseid$/) {
                   7140:         my $chome=&homeserver($cnum,$udom,'true');
                   7141:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7142:             $uname = $cnum;
                   7143:         } else {
1.1038    raeburn  7144:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7145:         }
                   7146:     } else {
1.1038    raeburn  7147:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7148:     }
                   7149:     return $uname if ($uname =~ /^error/);
                   7150: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7151:     if (!defined($course_server)) {
                   7152:         if (defined(&domain($udom,'primary'))) {
                   7153:             $course_server = &domain($udom,'primary');
                   7154:         } else {
                   7155:             $course_server = $env{'user.home'}; 
                   7156:         }
                   7157:     }
                   7158:     my %host_servers =
                   7159:         &Apache::lonnet::get_servers($udom,'library');
                   7160:     unless ($host_servers{$course_server}) {
                   7161:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7162:     }
1.84      www      7163: # ------------------------------------------------------------- Make the course
                   7164:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7165:                       $course_server);
1.84      www      7166:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7167:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7168:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7169: 	return 'error: no such course';
                   7170:     }
1.271     www      7171: # ----------------------------------------------------------------- Course made
1.516     raeburn  7172: # log existence
1.1029    raeburn  7173:     my $now = time;
1.918     raeburn  7174:     my $newcourse = {
                   7175:                     $udom.'_'.$uname => {
1.921     raeburn  7176:                                      description => $description,
                   7177:                                      inst_code   => $inst_code,
                   7178:                                      owner       => $course_owner,
                   7179:                                      type        => $crstype,
1.1029    raeburn  7180:                                      creator     => $env{'user.name'}.':'.
                   7181:                                                     $env{'user.domain'},
                   7182:                                      created     => $now,
                   7183:                                      context     => $context,
1.918     raeburn  7184:                                                 },
                   7185:                     };
1.921     raeburn  7186:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7187: # set toplevel url
1.271     www      7188:     my $topurl=$url;
                   7189:     unless ($nonstandard) {
                   7190: # ------------------------------------------ For standard courses, make top url
                   7191:         my $mapurl=&clutter($url);
1.278     www      7192:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7193:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7194: <map>
                   7195: <resource id="1" type="start"></resource>
                   7196: <resource id="2" src="$mapurl"></resource>
                   7197: <resource id="3" type="finish"></resource>
                   7198: <link index="1" from="1" to="2"></link>
                   7199: <link index="2" from="2" to="3"></link>
                   7200: </map>
                   7201: ENDINITMAP
                   7202:         $topurl=&declutter(
1.638     albertel 7203:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7204:                           );
                   7205:     }
                   7206: # ----------------------------------------------------------- Write preferences
1.84      www      7207:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7208:                      ('description'              => $description,
                   7209:                       'url'                      => $topurl,
                   7210:                       'internal.creator'         => $env{'user.name'}.':'.
                   7211:                                                     $env{'user.domain'},
                   7212:                       'internal.created'         => $now,
                   7213:                       'internal.creationcontext' => $context)
                   7214:                     );
1.84      www      7215:     return '/'.$udom.'/'.$uname;
                   7216: }
                   7217: 
1.1011    raeburn  7218: # ------------------------------------------------------------------- Create ID
                   7219: sub generate_coursenum {
1.1038    raeburn  7220:     my ($udom,$crstype) = @_;
1.1011    raeburn  7221:     my $domdesc = &domain($udom);
                   7222:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7223:     my $first;
                   7224:     if ($crstype eq 'Community') {
                   7225:         $first = '0';
                   7226:     } else {
                   7227:         $first = int(1+rand(9)); 
                   7228:     } 
                   7229:     my $uname=$first.
1.1011    raeburn  7230:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7231:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7232:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7233: # ----------------------------------------------- Make sure that does not exist
                   7234:     my $uhome=&homeserver($uname,$udom,'true');
                   7235:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7236:         if ($crstype eq 'Community') {
                   7237:             $first = '0';
                   7238:         } else {
                   7239:             $first = int(1+rand(9));
                   7240:         }
                   7241:         $uname=$first.
1.1011    raeburn  7242:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7243:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7244:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7245:         $uhome=&homeserver($uname,$udom,'true');
                   7246:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7247:             return 'error: unable to generate unique course-ID';
                   7248:         }
                   7249:     }
                   7250:     return $uname;
                   7251: }
                   7252: 
1.813     albertel 7253: sub is_course {
                   7254:     my ($cdom,$cnum) = @_;
                   7255:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7256: 				undef,'.');
1.813     albertel 7257:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7258:         return 1;
                   7259:     }
                   7260:     return 0;
                   7261: }
                   7262: 
1.1015    raeburn  7263: sub store_userdata {
                   7264:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7265:     my $result;
1.1016    raeburn  7266:     if ($datakey ne '') {
1.1013    raeburn  7267:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7268:             if ($udom eq '' || $uname eq '') {
                   7269:                 $udom = $env{'user.domain'};
                   7270:                 $uname = $env{'user.name'};
                   7271:             }
                   7272:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7273:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7274:                 $result = 'error: no_host';
                   7275:             } else {
                   7276:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7277:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7278: 
                   7279:                 my $namevalue='';
                   7280:                 foreach my $key (keys(%{$storehash})) {
                   7281:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7282:                 }
                   7283:                 $namevalue=~s/\&$//;
                   7284:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7285:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7286:             }
                   7287:         } else {
                   7288:             $result = 'error: data to store was not a hash reference'; 
                   7289:         }
                   7290:     } else {
                   7291:         $result= 'error: invalid requestkey'; 
                   7292:     }
                   7293:     return $result;
                   7294: }
                   7295: 
1.21      www      7296: # ---------------------------------------------------------- Assign Custom Role
                   7297: 
                   7298: sub assigncustomrole {
1.957     raeburn  7299:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7300:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7301:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7302: }
                   7303: 
                   7304: # ----------------------------------------------------------------- Revoke Role
                   7305: 
                   7306: sub revokerole {
1.957     raeburn  7307:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7308:     my $now=time;
1.965     raeburn  7309:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7310: }
                   7311: 
                   7312: # ---------------------------------------------------------- Revoke Custom Role
                   7313: 
                   7314: sub revokecustomrole {
1.957     raeburn  7315:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7316:     my $now=time;
1.357     www      7317:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7318:            $deleteflag,$selfenroll,$context);
1.17      www      7319: }
                   7320: 
1.533     banghart 7321: # ------------------------------------------------------------ Disk usage
1.535     albertel 7322: sub diskusage {
1.955     raeburn  7323:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7324:     $directorypath =~ s/\/$//;
                   7325:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7326:                        .&escape($getpropath).':'.&escape($uname).':'
                   7327:                        .&escape($udom),homeserver($uname,$udom));
                   7328:     if ($listing eq 'unknown_cmd') {
                   7329:         if ($getpropath) {
                   7330:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7331:         }
                   7332:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7333:     }
1.514     albertel 7334:     return $listing;
1.512     banghart 7335: }
                   7336: 
1.566     banghart 7337: sub is_locked {
                   7338:     my ($file_name, $domain, $user) = @_;
                   7339:     my @check;
                   7340:     my $is_locked;
                   7341:     push @check, $file_name;
1.613     albertel 7342:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7343: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7344:     my ($tmp)=keys(%locked);
                   7345:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7346:     
1.566     banghart 7347:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7348:         $is_locked = 'false';
                   7349:         foreach my $entry (@{$locked{$file_name}}) {
                   7350:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7351:                $is_locked = 'true';
                   7352:                last;
1.745     raeburn  7353:            }
                   7354:        }
1.566     banghart 7355:     } else {
                   7356:         $is_locked = 'false';
                   7357:     }
                   7358: }
                   7359: 
1.759     albertel 7360: sub declutter_portfile {
                   7361:     my ($file) = @_;
1.833     albertel 7362:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7363:     return $file;
                   7364: }
                   7365: 
1.559     banghart 7366: # ------------------------------------------------------------- Mark as Read Only
                   7367: 
                   7368: sub mark_as_readonly {
                   7369:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7370:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7371:     my ($tmp)=keys(%current_permissions);
                   7372:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7373:     foreach my $file (@{$files}) {
1.759     albertel 7374: 	$file = &declutter_portfile($file);
1.561     banghart 7375:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7376:     }
1.613     albertel 7377:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7378:     return;
                   7379: }
                   7380: 
1.572     banghart 7381: # ------------------------------------------------------------Save Selected Files
                   7382: 
                   7383: sub save_selected_files {
                   7384:     my ($user, $path, @files) = @_;
                   7385:     my $filename = $user."savedfiles";
1.573     banghart 7386:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7387:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7388:     foreach my $file (@files) {
1.620     albertel 7389:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7390:     }
                   7391:     foreach my $file (@other_files) {
1.574     banghart 7392:         print (OUT $file."\n");
1.572     banghart 7393:     }
1.574     banghart 7394:     close (OUT);
1.572     banghart 7395:     return 'ok';
                   7396: }
                   7397: 
1.574     banghart 7398: sub clear_selected_files {
                   7399:     my ($user) = @_;
                   7400:     my $filename = $user."savedfiles";
                   7401:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7402:     print (OUT undef);
                   7403:     close (OUT);
                   7404:     return ("ok");    
                   7405: }
                   7406: 
1.572     banghart 7407: sub files_in_path {
                   7408:     my ($user, $path) = @_;
                   7409:     my $filename = $user."savedfiles";
                   7410:     my %return_files;
1.574     banghart 7411:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7412:     while (my $line_in = <IN>) {
1.574     banghart 7413:         chomp ($line_in);
                   7414:         my @paths_and_file = split (m!/!, $line_in);
                   7415:         my $file_part = pop (@paths_and_file);
                   7416:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7417:         $path_part.='/';
                   7418:         my $path_and_file = $path_part.$file_part;
                   7419:         if ($path_part eq $path) {
                   7420:             $return_files{$file_part}= 'selected';
                   7421:         }
                   7422:     }
1.574     banghart 7423:     close (IN);
                   7424:     return (\%return_files);
1.572     banghart 7425: }
                   7426: 
                   7427: # called in portfolio select mode, to show files selected NOT in current directory
                   7428: sub files_not_in_path {
                   7429:     my ($user, $path) = @_;
                   7430:     my $filename = $user."savedfiles";
                   7431:     my @return_files;
                   7432:     my $path_part;
1.800     albertel 7433:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7434:     while (my $line = <IN>) {
1.572     banghart 7435:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7436:         my @paths_and_file = split(m|/|, $line);
                   7437:         my $file_part = pop(@paths_and_file);
                   7438:         chomp($file_part);
                   7439:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7440:         $path_part .= '/';
                   7441:         my $path_and_file = $path_part.$file_part;
                   7442:         if ($path_part ne $path) {
1.800     albertel 7443:             push(@return_files, ($path_and_file));
1.572     banghart 7444:         }
                   7445:     }
1.800     albertel 7446:     close(OUT);
1.574     banghart 7447:     return (@return_files);
1.572     banghart 7448: }
                   7449: 
1.745     raeburn  7450: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7451: 
1.745     raeburn  7452: sub get_portfile_permissions {
                   7453:     my ($domain,$user) = @_;
1.613     albertel 7454:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7455:     my ($tmp)=keys(%current_permissions);
                   7456:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7457:     return \%current_permissions;
                   7458: }
                   7459: 
                   7460: #---------------------------------------------Get portfolio file access controls
                   7461: 
1.749     raeburn  7462: sub get_access_controls {
1.745     raeburn  7463:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7464:     my %access;
                   7465:     my $real_file = $file;
                   7466:     $file =~ s/\.meta$//;
1.745     raeburn  7467:     if (defined($file)) {
1.749     raeburn  7468:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7469:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7470:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7471:             }
                   7472:         }
1.745     raeburn  7473:     } else {
1.749     raeburn  7474:         foreach my $key (keys(%{$current_permissions})) {
                   7475:             if ($key =~ /\0accesscontrol$/) {
                   7476:                 if (defined($group)) {
                   7477:                     if ($key !~ m-^\Q$group\E/-) {
                   7478:                         next;
                   7479:                     }
                   7480:                 }
                   7481:                 my ($fullpath) = split(/\0/,$key);
                   7482:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7483:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7484:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7485:                     }
                   7486:                 }
                   7487:             }
                   7488:         }
                   7489:     }
                   7490:     return %access;
                   7491: }
                   7492: 
                   7493: sub modify_access_controls {
                   7494:     my ($file_name,$changes,$domain,$user)=@_;
                   7495:     my ($outcome,$deloutcome);
                   7496:     my %store_permissions;
                   7497:     my %new_values;
                   7498:     my %new_control;
                   7499:     my %translation;
                   7500:     my @deletions = ();
                   7501:     my $now = time;
                   7502:     if (exists($$changes{'activate'})) {
                   7503:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7504:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7505:             my $numnew = scalar(@newitems);
                   7506:             for (my $i=0; $i<$numnew; $i++) {
                   7507:                 my $newkey = $newitems[$i];
                   7508:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7509:                 if ($newkey =~ /^\d+:/) { 
                   7510:                     $newkey =~ s/^(\d+)/$newid/;
                   7511:                     $translation{$1} = $newid;
                   7512:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7513:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7514:                     $translation{$1} = $newid;
                   7515:                 }
1.749     raeburn  7516:                 $new_values{$file_name."\0".$newkey} = 
                   7517:                                           $$changes{'activate'}{$newitems[$i]};
                   7518:                 $new_control{$newkey} = $now;
                   7519:             }
                   7520:         }
                   7521:     }
                   7522:     my %todelete;
                   7523:     my %changed_items;
                   7524:     foreach my $action ('delete','update') {
                   7525:         if (exists($$changes{$action})) {
                   7526:             if (ref($$changes{$action}) eq 'HASH') {
                   7527:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7528:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7529:                     if ($action eq 'delete') { 
                   7530:                         $todelete{$itemnum} = 1;
                   7531:                     } else {
                   7532:                         $changed_items{$itemnum} = $key;
                   7533:                     }
                   7534:                 }
1.745     raeburn  7535:             }
                   7536:         }
1.749     raeburn  7537:     }
                   7538:     # get lock on access controls for file.
                   7539:     my $lockhash = {
                   7540:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7541:                                                        ':'.$env{'user.domain'},
                   7542:                    }; 
                   7543:     my $tries = 0;
                   7544:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7545:    
                   7546:     while (($gotlock ne 'ok') && $tries <3) {
                   7547:         $tries ++;
                   7548:         sleep 1;
                   7549:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7550:     }
                   7551:     if ($gotlock eq 'ok') {
                   7552:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7553:         my ($tmp)=keys(%curr_permissions);
                   7554:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7555:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7556:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7557:             if (ref($curr_controls) eq 'HASH') {
                   7558:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7559:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7560:                     if (defined($todelete{$itemnum})) {
                   7561:                         push(@deletions,$file_name."\0".$control_item);
                   7562:                     } else {
                   7563:                         if (defined($changed_items{$itemnum})) {
                   7564:                             $new_control{$changed_items{$itemnum}} = $now;
                   7565:                             push(@deletions,$file_name."\0".$control_item);
                   7566:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7567:                         } else {
                   7568:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7569:                         }
                   7570:                     }
1.745     raeburn  7571:                 }
                   7572:             }
                   7573:         }
1.970     raeburn  7574:         my ($group);
                   7575:         if (&is_course($domain,$user)) {
                   7576:             ($group,my $file) = split(/\//,$file_name,2);
                   7577:         }
1.749     raeburn  7578:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7579:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7580:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7581:         #  remove lock
                   7582:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7583:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7584:         my $sqlresult =
1.970     raeburn  7585:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7586:                                     $group);
1.749     raeburn  7587:     } else {
                   7588:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7589:     }
1.749     raeburn  7590:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7591: }
                   7592: 
1.827     raeburn  7593: sub make_public_indefinitely {
                   7594:     my ($requrl) = @_;
                   7595:     my $now = time;
                   7596:     my $action = 'activate';
                   7597:     my $aclnum = 0;
                   7598:     if (&is_portfolio_url($requrl)) {
                   7599:         my (undef,$udom,$unum,$file_name,$group) =
                   7600:             &parse_portfolio_url($requrl);
                   7601:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7602:         my %access_controls = &get_access_controls($current_perms,
                   7603:                                                    $group,$file_name);
                   7604:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7605:             my ($num,$scope,$end,$start) = 
                   7606:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7607:             if ($scope eq 'public') {
                   7608:                 if ($start <= $now && $end == 0) {
                   7609:                     $action = 'none';
                   7610:                 } else {
                   7611:                     $action = 'update';
                   7612:                     $aclnum = $num;
                   7613:                 }
                   7614:                 last;
                   7615:             }
                   7616:         }
                   7617:         if ($action eq 'none') {
                   7618:              return 'ok';
                   7619:         } else {
                   7620:             my %changes;
                   7621:             my $newend = 0;
                   7622:             my $newstart = $now;
                   7623:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7624:             $changes{$action}{$newkey} = {
                   7625:                 type => 'public',
                   7626:                 time => {
                   7627:                     start => $newstart,
                   7628:                     end   => $newend,
                   7629:                 },
                   7630:             };
                   7631:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7632:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7633:             return $outcome;
                   7634:         }
                   7635:     } else {
                   7636:         return 'invalid';
                   7637:     }
                   7638: }
                   7639: 
1.745     raeburn  7640: #------------------------------------------------------Get Marked as Read Only
                   7641: 
                   7642: sub get_marked_as_readonly {
                   7643:     my ($domain,$user,$what,$group) = @_;
                   7644:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7645:     my @readonly_files;
1.629     banghart 7646:     my $cmp1=$what;
                   7647:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7648:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7649:         if (defined($group)) {
                   7650:             if ($file_name !~ m-^\Q$group\E/-) {
                   7651:                 next;
                   7652:             }
                   7653:         }
1.561     banghart 7654:         if (ref($value) eq "ARRAY"){
                   7655:             foreach my $stored_what (@{$value}) {
1.629     banghart 7656:                 my $cmp2=$stored_what;
1.759     albertel 7657:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7658:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7659:                 }
1.629     banghart 7660:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7661:                     push(@readonly_files, $file_name);
1.745     raeburn  7662:                     last;
1.563     banghart 7663:                 } elsif (!defined($what)) {
                   7664:                     push(@readonly_files, $file_name);
1.745     raeburn  7665:                     last;
1.561     banghart 7666:                 }
                   7667:             }
1.745     raeburn  7668:         }
1.561     banghart 7669:     }
                   7670:     return @readonly_files;
                   7671: }
1.577     banghart 7672: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7673: 
1.577     banghart 7674: sub get_marked_as_readonly_hash {
1.745     raeburn  7675:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7676:     my %readonly_files;
1.745     raeburn  7677:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7678:         if (defined($group)) {
                   7679:             if ($file_name !~ m-^\Q$group\E/-) {
                   7680:                 next;
                   7681:             }
                   7682:         }
1.577     banghart 7683:         if (ref($value) eq "ARRAY"){
                   7684:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7685:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7686:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7687:                         if ($lock_descriptor eq 'graded') {
                   7688:                             $readonly_files{$file_name} = 'graded';
                   7689:                         } elsif ($lock_descriptor eq 'handback') {
                   7690:                             $readonly_files{$file_name} = 'handback';
                   7691:                         } else {
                   7692:                             if (!exists($readonly_files{$file_name})) {
                   7693:                                 $readonly_files{$file_name} = 'locked';
                   7694:                             }
                   7695:                         }
1.745     raeburn  7696:                     }
1.750     banghart 7697:                 } 
1.577     banghart 7698:             }
                   7699:         } 
                   7700:     }
                   7701:     return %readonly_files;
                   7702: }
1.559     banghart 7703: # ------------------------------------------------------------ Unmark as Read Only
                   7704: 
                   7705: sub unmark_as_readonly {
1.629     banghart 7706:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7707:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7708:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7709:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7710:     my $symb_crs = $what;
                   7711:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7712:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7713:     my ($tmp)=keys(%current_permissions);
                   7714:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7715:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7716:     foreach my $file (@readonly_files) {
1.759     albertel 7717: 	my $clean_file = &declutter_portfile($file);
                   7718: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7719: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7720:         my @new_locks;
                   7721:         my @del_keys;
                   7722:         if (ref($current_locks) eq "ARRAY"){
                   7723:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7724:                 my $compare=$locker;
1.749     raeburn  7725:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7726:                     $compare=join('',@{$locker});
1.746     raeburn  7727:                     if ($compare ne $symb_crs) {
                   7728:                         push(@new_locks, $locker);
                   7729:                     }
1.563     banghart 7730:                 }
                   7731:             }
1.650     albertel 7732:             if (scalar(@new_locks) > 0) {
1.563     banghart 7733:                 $current_permissions{$file} = \@new_locks;
                   7734:             } else {
                   7735:                 push(@del_keys, $file);
1.613     albertel 7736:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7737:                 delete($current_permissions{$file});
1.563     banghart 7738:             }
                   7739:         }
1.561     banghart 7740:     }
1.613     albertel 7741:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7742:     return;
                   7743: }
1.512     banghart 7744: 
1.17      www      7745: # ------------------------------------------------------------ Directory lister
                   7746: 
                   7747: sub dirlist {
1.955     raeburn  7748:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7749:     $uri=~s/^\///;
                   7750:     $uri=~s/\/$//;
1.253     stredwic 7751:     my ($udom, $uname);
1.955     raeburn  7752:     if ($getuserdir) {
1.253     stredwic 7753:         $udom = $userdomain;
                   7754:         $uname = $username;
1.955     raeburn  7755:     } else {
                   7756:         (undef,$udom,$uname)=split(/\//,$uri);
                   7757:         if(defined($userdomain)) {
                   7758:             $udom = $userdomain;
                   7759:         }
                   7760:         if(defined($username)) {
                   7761:             $uname = $username;
                   7762:         }
1.253     stredwic 7763:     }
1.955     raeburn  7764:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7765: 
1.955     raeburn  7766:     $dirRoot = $perlvar{'lonDocRoot'};
                   7767:     if (defined($getpropath)) {
                   7768:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7769:         $dirRoot =~ s/\/$//;
1.955     raeburn  7770:     } elsif (defined($getuserdir)) {
                   7771:         my $subdir=$uname.'__';
                   7772:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7773:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7774:                    ."/$udom/$subdir/$uname";
                   7775:     } elsif (defined($alternateRoot)) {
                   7776:         $dirRoot = $alternateRoot;
1.751     banghart 7777:     }
1.253     stredwic 7778: 
                   7779:     if($udom) {
                   7780:         if($uname) {
1.955     raeburn  7781:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7782:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7783:                               .':'.&escape($uname).':'.&escape($udom),
                   7784:                               &homeserver($uname,$udom));
                   7785:             if ($listing eq 'unknown_cmd') {
                   7786:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7787:                                   &homeserver($uname,$udom));
                   7788:             } else {
                   7789:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7790:             }
1.605     matthew  7791:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7792:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7793: 				  &homeserver($uname,$udom));
1.605     matthew  7794:                 @listing_results = split(/:/,$listing);
                   7795:             } else {
                   7796:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7797:             }
                   7798:             return @listing_results;
1.955     raeburn  7799:         } elsif(!$alternateRoot) {
1.800     albertel 7800:             my %allusers;
1.841     albertel 7801: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7802:  	    foreach my $tryserver (keys(%servers)) {
                   7803:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7804:                                   &escape($udom),$tryserver);
                   7805:                 if ($listing eq 'unknown_cmd') {
                   7806: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7807: 				      $udom, $tryserver);
                   7808:                 } else {
                   7809:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7810:                 }
1.841     albertel 7811: 		if ($listing eq 'unknown_cmd') {
                   7812: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7813: 				      $udom, $tryserver);
                   7814: 		    @listing_results = split(/:/,$listing);
                   7815: 		} else {
                   7816: 		    @listing_results =
                   7817: 			map { &unescape($_); } split(/:/,$listing);
                   7818: 		}
                   7819: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7820: 		    $listing_results[0] ne 'empty'       &&
                   7821: 		    $listing_results[0] ne 'con_lost') {
                   7822: 		    foreach my $line (@listing_results) {
                   7823: 			my ($entry) = split(/&/,$line,2);
                   7824: 			$allusers{$entry} = 1;
                   7825: 		    }
                   7826: 		}
1.253     stredwic 7827:             }
                   7828:             my $alluserstr='';
1.800     albertel 7829:             foreach my $user (sort(keys(%allusers))) {
                   7830:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7831:             }
                   7832:             $alluserstr=~s/:$//;
                   7833:             return split(/:/,$alluserstr);
                   7834:         } else {
1.800     albertel 7835:             return ('missing user name');
1.253     stredwic 7836:         }
1.955     raeburn  7837:     } elsif(!defined($getpropath)) {
1.841     albertel 7838:         my @all_domains = sort(&all_domains());
1.955     raeburn  7839:         foreach my $domain (@all_domains) {
                   7840:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7841:         }
                   7842:         return @all_domains;
                   7843:     } else {
1.800     albertel 7844:         return ('missing domain');
1.275     stredwic 7845:     }
                   7846: }
                   7847: 
                   7848: # --------------------------------------------- GetFileTimestamp
                   7849: # This function utilizes dirlist and returns the date stamp for
                   7850: # when it was last modified.  It will also return an error of -1
                   7851: # if an error occurs
                   7852: 
                   7853: sub GetFileTimestamp {
1.955     raeburn  7854:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7855:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7856:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7857:     my ($fileStat) = 
                   7858:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7859:                                  undef,$getuserdir);
1.275     stredwic 7860:     my @stats = split('&', $fileStat);
                   7861:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7862:         # @stats contains first the filename, then the stat output
                   7863:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7864:     } else {
                   7865:         return -1;
1.253     stredwic 7866:     }
1.26      www      7867: }
                   7868: 
1.712     albertel 7869: sub stat_file {
                   7870:     my ($uri) = @_;
1.787     albertel 7871:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7872: 
1.955     raeburn  7873:     my ($udom,$uname,$file);
1.712     albertel 7874:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7875: 	($udom,$uname,$file) =
1.811     albertel 7876: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7877: 	$file = 'userfiles/'.$file;
                   7878:     }
                   7879:     if ($uri =~ m-^/res/-) {
                   7880: 	($udom,$uname) = 
1.807     albertel 7881: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7882: 	$file = $uri;
                   7883:     }
                   7884: 
                   7885:     if (!$udom || !$uname || !$file) {
                   7886: 	# unable to handle the uri
                   7887: 	return ();
                   7888:     }
1.956     raeburn  7889:     my $getpropath;
                   7890:     if ($file =~ /^userfiles\//) {
                   7891:         $getpropath = 1;
                   7892:     }
1.955     raeburn  7893:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7894:     my @stats = split('&', $result);
1.721     banghart 7895:     
1.712     albertel 7896:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7897: 	shift(@stats); #filename is first
                   7898: 	return @stats;
                   7899:     }
                   7900:     return ();
                   7901: }
                   7902: 
1.26      www      7903: # -------------------------------------------------------- Value of a Condition
                   7904: 
1.713     albertel 7905: # gets the value of a specific preevaluated condition
                   7906: #    stored in the string  $env{user.state.<cid>}
                   7907: # or looks up a condition reference in the bighash and if if hasn't
                   7908: # already been evaluated recurses into docondval to get the value of
                   7909: # the condition, then memoizing it to 
                   7910: #   $env{user.state.<cid>.<condition>}
1.40      www      7911: sub directcondval {
                   7912:     my $number=shift;
1.620     albertel 7913:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7914: 	&Apache::lonuserstate::evalstate();
                   7915:     }
1.713     albertel 7916:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7917: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7918:     } elsif ($number =~ /^_/) {
                   7919: 	my $sub_condition;
                   7920: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7921: 		&GDBM_READER(),0640)) {
                   7922: 	    $sub_condition=$bighash{'conditions'.$number};
                   7923: 	    untie(%bighash);
                   7924: 	}
                   7925: 	my $value = &docondval($sub_condition);
1.949     raeburn  7926: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7927: 	return $value;
                   7928:     }
1.620     albertel 7929:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7930:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7931:     } else {
                   7932:        return 2;
                   7933:     }
                   7934: }
                   7935: 
1.713     albertel 7936: # get the collection of conditions for this resource
1.26      www      7937: sub condval {
                   7938:     my $condidx=shift;
1.54      www      7939:     my $allpathcond='';
1.713     albertel 7940:     foreach my $cond (split(/\|/,$condidx)) {
                   7941: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7942: 	    $allpathcond.=
                   7943: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7944: 	}
1.191     harris41 7945:     }
1.54      www      7946:     $allpathcond=~s/\|$//;
1.713     albertel 7947:     return &docondval($allpathcond);
                   7948: }
                   7949: 
                   7950: #evaluates an expression of conditions
                   7951: sub docondval {
                   7952:     my ($allpathcond) = @_;
                   7953:     my $result=0;
                   7954:     if ($env{'request.course.id'}
                   7955: 	&& defined($allpathcond)) {
                   7956: 	my $operand='|';
                   7957: 	my @stack;
                   7958: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7959: 	    if ($chunk eq '(') {
                   7960: 		push @stack,($operand,$result);
                   7961: 	    } elsif ($chunk eq ')') {
                   7962: 		my $before=pop @stack;
                   7963: 		if (pop @stack eq '&') {
                   7964: 		    $result=$result>$before?$before:$result;
                   7965: 		} else {
                   7966: 		    $result=$result>$before?$result:$before;
                   7967: 		}
                   7968: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7969: 		$operand=$chunk;
                   7970: 	    } else {
                   7971: 		my $new=directcondval($chunk);
                   7972: 		if ($operand eq '&') {
                   7973: 		    $result=$result>$new?$new:$result;
                   7974: 		} else {
                   7975: 		    $result=$result>$new?$result:$new;
                   7976: 		}
                   7977: 	    }
                   7978: 	}
1.26      www      7979:     }
                   7980:     return $result;
1.421     albertel 7981: }
                   7982: 
                   7983: # ---------------------------------------------------- Devalidate courseresdata
                   7984: 
                   7985: sub devalidatecourseresdata {
                   7986:     my ($coursenum,$coursedomain)=@_;
                   7987:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7988:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7989: }
                   7990: 
1.763     www      7991: 
1.200     www      7992: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7993: #
                   7994: #  Parameters:
                   7995: #      $coursenum    - Number of the course.
                   7996: #      $coursedomain - Domain at which the course was created.
                   7997: #  Returns:
                   7998: #     A hash of the course parameters along (I think) with timestamps
                   7999: #     and version info.
1.877     foxr     8000: 
1.624     albertel 8001: sub get_courseresdata {
                   8002:     my ($coursenum,$coursedomain)=@_;
1.200     www      8003:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8004:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8005:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8006:     my %dumpreply;
1.417     albertel 8007:     unless (defined($cached)) {
1.624     albertel 8008: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8009: 	$result=\%dumpreply;
1.251     albertel 8010: 	my ($tmp) = keys(%dumpreply);
                   8011: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8012: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8013: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8014: 	    return $tmp;
1.416     albertel 8015: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8016: 	    $result=undef;
1.599     albertel 8017: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8018: 	}
                   8019:     }
1.624     albertel 8020:     return $result;
                   8021: }
                   8022: 
1.633     albertel 8023: sub devalidateuserresdata {
                   8024:     my ($uname,$udom)=@_;
                   8025:     my $hashid="$udom:$uname";
                   8026:     &devalidate_cache_new('userres',$hashid);
                   8027: }
                   8028: 
1.624     albertel 8029: sub get_userresdata {
                   8030:     my ($uname,$udom)=@_;
                   8031:     #most student don\'t have any data set, check if there is some data
                   8032:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8033: 
                   8034:     my $hashid="$udom:$uname";
                   8035:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8036:     if (!defined($cached)) {
                   8037: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8038: 	$result=\%resourcedata;
                   8039: 	&do_cache_new('userres',$hashid,$result,600);
                   8040:     }
                   8041:     my ($tmp)=keys(%$result);
                   8042:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8043: 	return $result;
                   8044:     }
                   8045:     #error 2 occurs when the .db doesn't exist
                   8046:     if ($tmp!~/error: 2 /) {
1.672     albertel 8047: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8048: 		 " Trying to get resource data for ".
                   8049: 		 $uname." at ".$udom.": ".
                   8050: 		 $tmp."</font>");
                   8051:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8052: 	#&EXT_cache_set($udom,$uname);
                   8053: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8054: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8055:     }
                   8056:     return $tmp;
                   8057: }
1.879     foxr     8058: #----------------------------------------------- resdata - return resource data
                   8059: #  Purpose:
                   8060: #    Return resource data for either users or for a course.
                   8061: #  Parameters:
                   8062: #     $name      - Course/user name.
                   8063: #     $domain    - Name of the domain the user/course is registered on.
                   8064: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8065: #     @which     - Array of names of resources desired.
                   8066: #  Returns:
                   8067: #     The value of the first reasource in @which that is found in the
                   8068: #     resource hash.
                   8069: #  Exceptional Conditions:
                   8070: #     If the $type passed in is not valid (not the string 'course' or 
                   8071: #     'user', an undefined  reference is returned.
                   8072: #     If none of the resources are found, an undef is returned
1.624     albertel 8073: sub resdata {
                   8074:     my ($name,$domain,$type,@which)=@_;
                   8075:     my $result;
                   8076:     if ($type eq 'course') {
                   8077: 	$result=&get_courseresdata($name,$domain);
                   8078:     } elsif ($type eq 'user') {
                   8079: 	$result=&get_userresdata($name,$domain);
                   8080:     }
                   8081:     if (!ref($result)) { return $result; }    
1.251     albertel 8082:     foreach my $item (@which) {
1.927     albertel 8083: 	if (defined($result->{$item->[0]})) {
                   8084: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8085: 	}
1.250     albertel 8086:     }
1.291     albertel 8087:     return undef;
1.200     www      8088: }
                   8089: 
1.379     matthew  8090: #
                   8091: # EXT resource caching routines
                   8092: #
                   8093: 
                   8094: sub clear_EXT_cache_status {
1.383     albertel 8095:     &delenv('cache.EXT.');
1.379     matthew  8096: }
                   8097: 
                   8098: sub EXT_cache_status {
                   8099:     my ($target_domain,$target_user) = @_;
1.383     albertel 8100:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8101:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8102:         # We know already the user has no data
                   8103:         return 1;
                   8104:     } else {
                   8105:         return 0;
                   8106:     }
                   8107: }
                   8108: 
                   8109: sub EXT_cache_set {
                   8110:     my ($target_domain,$target_user) = @_;
1.383     albertel 8111:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8112:     #&appenv({$cachename => time});
1.379     matthew  8113: }
                   8114: 
1.28      www      8115: # --------------------------------------------------------- Value of a Variable
1.58      www      8116: sub EXT {
1.715     albertel 8117: 
1.395     albertel 8118:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8119:     unless ($varname) { return ''; }
1.218     albertel 8120:     #get real user name/domain, courseid and symb
                   8121:     my $courseid;
1.359     albertel 8122:     my $publicuser;
1.427     www      8123:     if ($symbparm) {
                   8124: 	$symbparm=&get_symb_from_alias($symbparm);
                   8125:     }
1.218     albertel 8126:     if (!($uname && $udom)) {
1.790     albertel 8127:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8128:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8129:     } else {
1.620     albertel 8130: 	$courseid=$env{'request.course.id'};
1.218     albertel 8131:     }
1.48      www      8132:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8133:     my $rest;
1.320     albertel 8134:     if (defined($therest[0])) {
1.48      www      8135:        $rest=join('.',@therest);
                   8136:     } else {
                   8137:        $rest='';
                   8138:     }
1.320     albertel 8139: 
1.57      www      8140:     my $qualifierrest=$qualifier;
                   8141:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8142:     my $spacequalifierrest=$space;
                   8143:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8144:     if ($realm eq 'user') {
1.48      www      8145: # --------------------------------------------------------------- user.resource
                   8146: 	if ($space eq 'resource') {
1.651     albertel 8147: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8148: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8149: 		 &&
1.744     albertel 8150: 		 ($symbparm eq &symbread()) ) {	
                   8151: 		# if we are in the middle of processing the resource the
                   8152: 		# get the value we are planning on committing
                   8153:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8154:                     return $Apache::lonhomework::results{$qualifierrest};
                   8155:                 } else {
                   8156:                     return $Apache::lonhomework::history{$qualifierrest};
                   8157:                 }
1.335     albertel 8158: 	    } else {
1.359     albertel 8159: 		my %restored;
1.620     albertel 8160: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8161: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8162: 		} else {
                   8163: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8164: 		}
1.335     albertel 8165: 		return $restored{$qualifierrest};
                   8166: 	    }
1.48      www      8167: # ----------------------------------------------------------------- user.access
                   8168:         } elsif ($space eq 'access') {
1.218     albertel 8169: 	    # FIXME - not supporting calls for a specific user
1.48      www      8170:             return &allowed($qualifier,$rest);
                   8171: # ------------------------------------------ user.preferences, user.environment
                   8172:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8173: 	    if (($uname eq $env{'user.name'}) &&
                   8174: 		($udom eq $env{'user.domain'})) {
                   8175: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8176: 	    } else {
1.359     albertel 8177: 		my %returnhash;
                   8178: 		if (!$publicuser) {
                   8179: 		    %returnhash=&userenvironment($udom,$uname,
                   8180: 						 $qualifierrest);
                   8181: 		}
1.218     albertel 8182: 		return $returnhash{$qualifierrest};
                   8183: 	    }
1.48      www      8184: # ----------------------------------------------------------------- user.course
                   8185:         } elsif ($space eq 'course') {
1.218     albertel 8186: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8187:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8188: # ------------------------------------------------------------------- user.role
                   8189:         } elsif ($space eq 'role') {
1.218     albertel 8190: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8191:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8192:             if ($qualifier eq 'value') {
                   8193: 		return $role;
                   8194:             } elsif ($qualifier eq 'extent') {
                   8195:                 return $where;
                   8196:             }
                   8197: # ----------------------------------------------------------------- user.domain
                   8198:         } elsif ($space eq 'domain') {
1.218     albertel 8199:             return $udom;
1.48      www      8200: # ------------------------------------------------------------------- user.name
                   8201:         } elsif ($space eq 'name') {
1.218     albertel 8202:             return $uname;
1.48      www      8203: # ---------------------------------------------------- Any other user namespace
1.29      www      8204:         } else {
1.359     albertel 8205: 	    my %reply;
                   8206: 	    if (!$publicuser) {
                   8207: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8208: 	    }
                   8209: 	    return $reply{$qualifierrest};
1.48      www      8210:         }
1.236     www      8211:     } elsif ($realm eq 'query') {
                   8212: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8213:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8214: 						[$spacequalifierrest]);
1.620     albertel 8215: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8216:    } elsif ($realm eq 'request') {
1.48      www      8217: # ------------------------------------------------------------- request.browser
                   8218:         if ($space eq 'browser') {
1.430     www      8219: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8220: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8221: 		    return 1;
                   8222: 		} else {
                   8223: 		    return 0;
                   8224: 		}
                   8225: 	    } else {
1.620     albertel 8226: 		return $env{'browser.'.$qualifier};
1.430     www      8227: 	    }
1.57      www      8228: # ------------------------------------------------------------ request.filename
                   8229:         } else {
1.620     albertel 8230:             return $env{'request.'.$spacequalifierrest};
1.29      www      8231:         }
1.28      www      8232:     } elsif ($realm eq 'course') {
1.48      www      8233: # ---------------------------------------------------------- course.description
1.620     albertel 8234:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8235:     } elsif ($realm eq 'resource') {
1.165     www      8236: 
1.620     albertel 8237: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8238: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8239: 	}
1.693     albertel 8240: 
                   8241: 	if ($space eq 'title') {
                   8242: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8243: 	    return &gettitle($symbparm);
                   8244: 	}
                   8245: 	
                   8246: 	if ($space eq 'map') {
                   8247: 	    my ($map) = &decode_symb($symbparm);
                   8248: 	    return &symbread($map);
                   8249: 	}
1.905     albertel 8250: 	if ($space eq 'filename') {
                   8251: 	    if ($symbparm) {
                   8252: 		return &clutter((&decode_symb($symbparm))[2]);
                   8253: 	    }
                   8254: 	    return &hreflocation('',$env{'request.filename'});
                   8255: 	}
1.693     albertel 8256: 
                   8257: 	my ($section, $group, @groups);
1.593     albertel 8258: 	my ($courselevelm,$courselevel);
1.539     albertel 8259: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8260: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8261: 
1.218     albertel 8262: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8263: 
1.60      www      8264: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8265: 	    my $symbp=$symbparm;
1.735     albertel 8266: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8267: 
                   8268: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8269: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8270: 
1.620     albertel 8271: 	    if (($env{'user.name'} eq $uname) &&
                   8272: 		($env{'user.domain'} eq $udom)) {
                   8273: 		$section=$env{'request.course.sec'};
1.733     raeburn  8274:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8275:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8276: 	    } else {
1.539     albertel 8277: 		if (! defined($usection)) {
1.551     albertel 8278: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8279: 		} else {
                   8280: 		    $section = $usection;
                   8281: 		}
1.733     raeburn  8282:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8283: 	    }
                   8284: 
                   8285: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8286: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8287: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8288: 
1.593     albertel 8289: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8290: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8291: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8292: 
1.60      www      8293: # ----------------------------------------------------------- first, check user
1.624     albertel 8294: 
                   8295: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8296: 				       ([$courselevelr,'resource'],
                   8297: 					[$courselevelm,'map'     ],
                   8298: 					[$courselevel, 'course'  ]));
1.931     albertel 8299: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8300: 
1.594     albertel 8301: # ------------------------------------------------ second, check some of course
1.684     raeburn  8302:             my $coursereply;
1.691     raeburn  8303:             if (@groups > 0) {
                   8304:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8305:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8306:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8307:             }
1.96      www      8308: 
1.684     raeburn  8309: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8310: 				  $env{'course.'.$courseid.'.domain'},
                   8311: 				  'course',
                   8312: 				  ([$seclevelr,   'resource'],
                   8313: 				   [$seclevelm,   'map'     ],
                   8314: 				   [$seclevel,    'course'  ],
                   8315: 				   [$courselevelr,'resource']));
                   8316: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8317: 
1.60      www      8318: # ------------------------------------------------------ third, check map parms
1.218     albertel 8319: 	    my %parmhash=();
                   8320: 	    my $thisparm='';
                   8321: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8322: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8323: 		    &GDBM_READER(),0640)) {
1.218     albertel 8324: 		$thisparm=$parmhash{$symbparm};
                   8325: 		untie(%parmhash);
                   8326: 	    }
1.927     albertel 8327: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8328: 	}
1.594     albertel 8329: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8330: 
1.218     albertel 8331: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8332: 	my $filename;
                   8333: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8334: 	if ($symbparm) {
1.409     www      8335: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8336: 	} else {
1.620     albertel 8337: 	    $filename=$env{'request.filename'};
1.282     albertel 8338: 	}
                   8339: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8340: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8341: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8342: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8343: 
1.927     albertel 8344: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8345: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8346: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8347: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8348: 				     $env{'course.'.$courseid.'.domain'},
                   8349: 				     'course',
1.927     albertel 8350: 				     ([$courselevelm,'map'   ],
                   8351: 				      [$courselevel, 'course']));
                   8352: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8353: 	}
1.145     www      8354: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8355: 	unless ($space eq '0') {
1.336     albertel 8356: 	    my @parts=split(/_/,$space);
                   8357: 	    my $id=pop(@parts);
                   8358: 	    my $part=join('_',@parts);
                   8359: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8360: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8361: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8362: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8363: 	}
1.395     albertel 8364: 	if ($recurse) { return undef; }
                   8365: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8366: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8367: # ---------------------------------------------------- Any other user namespace
                   8368:     } elsif ($realm eq 'environment') {
                   8369: # ----------------------------------------------------------------- environment
1.620     albertel 8370: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8371: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8372: 	} else {
1.770     albertel 8373: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8374: 		return '';
                   8375: 	    }
1.219     albertel 8376: 	    my %returnhash=&userenvironment($udom,$uname,
                   8377: 					    $spacequalifierrest);
                   8378: 	    return $returnhash{$spacequalifierrest};
                   8379: 	}
1.28      www      8380:     } elsif ($realm eq 'system') {
1.48      www      8381: # ----------------------------------------------------------------- system.time
                   8382: 	if ($space eq 'time') {
                   8383: 	    return time;
                   8384:         }
1.696     albertel 8385:     } elsif ($realm eq 'server') {
                   8386: # ----------------------------------------------------------------- system.time
                   8387: 	if ($space eq 'name') {
                   8388: 	    return $ENV{'SERVER_NAME'};
                   8389:         }
1.28      www      8390:     }
1.48      www      8391:     return '';
1.61      www      8392: }
                   8393: 
1.927     albertel 8394: sub get_reply {
                   8395:     my ($reply_value) = @_;
1.940     raeburn  8396:     if (ref($reply_value) eq 'ARRAY') {
                   8397:         if (wantarray) {
                   8398: 	    return @$reply_value;
                   8399:         }
                   8400:         return $reply_value->[0];
                   8401:     } else {
                   8402:         return $reply_value;
1.927     albertel 8403:     }
                   8404: }
                   8405: 
1.691     raeburn  8406: sub check_group_parms {
                   8407:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8408:     my @groupitems = ();
                   8409:     my $resultitem;
1.927     albertel 8410:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8411:     foreach my $group (@{$groups}) {
                   8412:         foreach my $level (@levels) {
1.927     albertel 8413:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8414:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8415:         }
                   8416:     }
                   8417:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8418:                             $env{'course.'.$courseid.'.domain'},
                   8419:                                      'course',@groupitems);
                   8420:     return $coursereply;
                   8421: }
                   8422: 
                   8423: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8424:     my ($courseid,@groups) = @_;
                   8425:     @groups = sort(@groups);
1.691     raeburn  8426:     return @groups;
                   8427: }
                   8428: 
1.395     albertel 8429: sub packages_tab_default {
                   8430:     my ($uri,$varname)=@_;
                   8431:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8432: 
                   8433:     my (@extension,@specifics,$do_default);
                   8434:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8435: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8436: 	if ($pack_type eq 'default') {
                   8437: 	    $do_default=1;
                   8438: 	} elsif ($pack_type eq 'extension') {
                   8439: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8440: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8441: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8442: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8443: 	}
                   8444:     }
                   8445:     # first look for a package that matches the requested part id
                   8446:     foreach my $package (@specifics) {
                   8447: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8448: 	next if ($pack_part ne $part);
                   8449: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8450: 	    return $packagetab{"$pack_type&$name&default"};
                   8451: 	}
                   8452:     }
                   8453:     # look for any possible matching non extension_ package
                   8454:     foreach my $package (@specifics) {
                   8455: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8456: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8457: 	    return $packagetab{"$pack_type&$name&default"};
                   8458: 	}
1.585     albertel 8459: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8460: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8461: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8462: 	}
                   8463:     }
1.738     albertel 8464:     # look for any posible extension_ match
                   8465:     foreach my $package (@extension) {
                   8466: 	my ($package,$pack_type)=@{$package};
                   8467: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8468: 	    return $packagetab{"$pack_type&$name&default"};
                   8469: 	}
                   8470: 	if (defined($packagetab{$package."&$name&default"})) {
                   8471: 	    return $packagetab{$package."&$name&default"};
                   8472: 	}
                   8473:     }
                   8474:     # look for a global default setting
                   8475:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8476: 	return $packagetab{"default&$name&default"};
                   8477:     }
1.395     albertel 8478:     return undef;
                   8479: }
                   8480: 
1.334     albertel 8481: sub add_prefix_and_part {
                   8482:     my ($prefix,$part)=@_;
                   8483:     my $keyroot;
                   8484:     if (defined($prefix) && $prefix !~ /^__/) {
                   8485: 	# prefix that has a part already
                   8486: 	$keyroot=$prefix;
                   8487:     } elsif (defined($prefix)) {
                   8488: 	# prefix that is missing a part
                   8489: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8490:     } else {
                   8491: 	# no prefix at all
                   8492: 	if (defined($part)) { $keyroot='_'.$part; }
                   8493:     }
                   8494:     return $keyroot;
                   8495: }
                   8496: 
1.71      www      8497: # ---------------------------------------------------------------- Get metadata
                   8498: 
1.599     albertel 8499: my %metaentry;
1.71      www      8500: sub metadata {
1.176     www      8501:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8502:     $uri=&declutter($uri);
1.288     albertel 8503:     # if it is a non metadata possible uri return quickly
1.529     albertel 8504:     if (($uri eq '') || 
                   8505: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8506: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8507:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8508: 	return undef;
                   8509:     }
                   8510:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8511: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8512: 	return undef;
1.288     albertel 8513:     }
1.73      www      8514:     my $filename=$uri;
                   8515:     $uri=~s/\.meta$//;
1.172     www      8516: #
                   8517: # Is the metadata already cached?
1.177     www      8518: # Look at timestamp of caching
1.172     www      8519: # Everything is cached by the main uri, libraries are never directly cached
                   8520: #
1.428     albertel 8521:     if (!defined($liburi)) {
1.599     albertel 8522: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8523: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8524:     }
                   8525:     {
1.172     www      8526: #
                   8527: # Is this a recursive call for a library?
                   8528: #
1.599     albertel 8529: #	if (! exists($metacache{$uri})) {
                   8530: #	    $metacache{$uri}={};
                   8531: #	}
1.924     albertel 8532: 	my $cachetime = 60*60;
1.171     www      8533:         if ($liburi) {
                   8534: 	    $liburi=&declutter($liburi);
                   8535:             $filename=$liburi;
1.401     bowersj2 8536:         } else {
1.599     albertel 8537: 	    &devalidate_cache_new('meta',$uri);
                   8538: 	    undef(%metaentry);
1.401     bowersj2 8539: 	}
1.140     www      8540:         my %metathesekeys=();
1.73      www      8541:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8542: 	my $metastring;
1.924     albertel 8543: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8544: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8545: 	    $metastring = 
1.929     albertel 8546: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8547: 					  ('grade_target' => 'meta'));
                   8548: 	    $cachetime = 1; # only want this cached in the child not long term
                   8549: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8550: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8551: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8552: 	    $metastring=&getfile($file);
1.489     albertel 8553: 	}
1.208     albertel 8554:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8555:         my $token;
1.140     www      8556:         undef %metathesekeys;
1.71      www      8557:         while ($token=$parser->get_token) {
1.339     albertel 8558: 	    if ($token->[0] eq 'S') {
                   8559: 		if (defined($token->[2]->{'package'})) {
1.172     www      8560: #
                   8561: # This is a package - get package info
                   8562: #
1.339     albertel 8563: 		    my $package=$token->[2]->{'package'};
                   8564: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8565: 		    if (defined($token->[2]->{'id'})) { 
                   8566: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8567: 		    }
1.599     albertel 8568: 		    if ($metaentry{':packages'}) {
                   8569: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8570: 		    } else {
1.599     albertel 8571: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8572: 		    }
1.736     albertel 8573: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8574: 			my $part=$keyroot;
                   8575: 			$part=~s/^\_//;
1.736     albertel 8576: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8577: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8578: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8579: 			    # ignore package.tab specified default values
                   8580:                             # here &package_tab_default() will fetch those
                   8581: 			    if ($subp eq 'default') { next; }
1.736     albertel 8582: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8583: 			    my $unikey;
                   8584: 			    if ($pack =~ /_0$/) {
                   8585: 				$unikey='parameter_0_'.$name;
                   8586: 				$part=0;
                   8587: 			    } else {
                   8588: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8589: 			    }
1.339     albertel 8590: 			    if ($subp eq 'display') {
                   8591: 				$value.=' [Part: '.$part.']';
                   8592: 			    }
1.599     albertel 8593: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8594: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8595: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8596: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8597: 			    }
1.599     albertel 8598: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8599: 				$metaentry{':'.$unikey}=
                   8600: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8601: 			    }
1.339     albertel 8602: 			}
                   8603: 		    }
                   8604: 		} else {
1.172     www      8605: #
                   8606: # This is not a package - some other kind of start tag
1.339     albertel 8607: #
                   8608: 		    my $entry=$token->[1];
                   8609: 		    my $unikey;
                   8610: 		    if ($entry eq 'import') {
                   8611: 			$unikey='';
                   8612: 		    } else {
                   8613: 			$unikey=$entry;
                   8614: 		    }
                   8615: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8616: 
                   8617: 		    if (defined($token->[2]->{'id'})) { 
                   8618: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8619: 		    }
1.175     www      8620: 
1.339     albertel 8621: 		    if ($entry eq 'import') {
1.175     www      8622: #
                   8623: # Importing a library here
1.339     albertel 8624: #
                   8625: 			if ($depthcount<20) {
                   8626: 			    my $location=$parser->get_text('/import');
                   8627: 			    my $dir=$filename;
                   8628: 			    $dir=~s|[^/]*$||;
                   8629: 			    $location=&filelocation($dir,$location);
1.736     albertel 8630: 			    my $metadata = 
                   8631: 				&metadata($uri,'keys', $location,$unikey,
                   8632: 					  $depthcount+1);
                   8633: 			    foreach my $meta (split(',',$metadata)) {
                   8634: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8635: 				$metathesekeys{$meta}=1;
1.339     albertel 8636: 			    }
                   8637: 			}
                   8638: 		    } else { 
                   8639: 			if (defined($token->[2]->{'name'})) { 
                   8640: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8641: 			}
                   8642: 			$metathesekeys{$unikey}=1;
1.736     albertel 8643: 			foreach my $param (@{$token->[3]}) {
                   8644: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8645: 				$token->[2]->{$param};
1.339     albertel 8646: 			}
                   8647: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8648: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8649: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8650: 		 # only ws inside the tag, and not in default, so use default
                   8651: 		 # as value
1.599     albertel 8652: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8653: 			} elsif ( $internaltext =~ /\S/ ) {
                   8654: 		  # something interesting inside the tag
                   8655: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8656: 			} else {
1.908     albertel 8657: 		  # no interesting values, don't set a default
1.339     albertel 8658: 			}
1.172     www      8659: # end of not-a-package not-a-library import
1.339     albertel 8660: 		    }
1.172     www      8661: # end of not-a-package start tag
1.339     albertel 8662: 		}
1.172     www      8663: # the next is the end of "start tag"
1.339     albertel 8664: 	    }
                   8665: 	}
1.483     albertel 8666: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8667: 	$extension = lc($extension);
                   8668: 	if ($extension eq 'htm') { $extension='html'; }
                   8669: 
1.737     albertel 8670: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8671: 	    #no specific packages #how's our extension
                   8672: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8673: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8674: 					 \%metathesekeys);
                   8675: 	}
1.883     albertel 8676: 
                   8677: 	if (!exists($metaentry{':packages'})
                   8678: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8679: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8680: 		#no specific packages well let's get default then
                   8681: 		if ($key!~/^default&/) { next; }
1.488     albertel 8682: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8683: 					     \%metathesekeys);
                   8684: 	    }
                   8685: 	}
1.338     www      8686: # are there custom rights to evaluate
1.599     albertel 8687: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8688: 
1.338     www      8689:     #
                   8690:     # Importing a rights file here
1.339     albertel 8691:     #
                   8692: 	    unless ($depthcount) {
1.599     albertel 8693: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8694: 		my $dir=$filename;
                   8695: 		$dir=~s|[^/]*$||;
                   8696: 		$location=&filelocation($dir,$location);
1.736     albertel 8697: 		my $rights_metadata =
                   8698: 		    &metadata($uri,'keys',$location,'_rights',
                   8699: 			      $depthcount+1);
                   8700: 		foreach my $rights (split(',',$rights_metadata)) {
                   8701: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8702: 		    $metathesekeys{$rights}=1;
1.339     albertel 8703: 		}
                   8704: 	    }
                   8705: 	}
1.737     albertel 8706: 	# uniqifiy package listing
                   8707: 	my %seen;
                   8708: 	my @uniq_packages =
                   8709: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8710: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8711: 
                   8712: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8713: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8714: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8715: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8716: # this is the end of "was not already recently cached
1.71      www      8717:     }
1.599     albertel 8718:     return $metaentry{':'.$what};
1.261     albertel 8719: }
                   8720: 
1.488     albertel 8721: sub metadata_create_package_def {
1.483     albertel 8722:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8723:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8724:     if ($subp eq 'default') { next; }
                   8725:     
1.599     albertel 8726:     if (defined($metaentry{':packages'})) {
                   8727: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8728:     } else {
1.599     albertel 8729: 	$metaentry{':packages'}=$package;
1.483     albertel 8730:     }
                   8731:     my $value=$packagetab{$key};
                   8732:     my $unikey;
                   8733:     $unikey='parameter_0_'.$name;
1.599     albertel 8734:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8735:     $$metathesekeys{$unikey}=1;
1.599     albertel 8736:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8737: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8738:     }
1.599     albertel 8739:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8740: 	$metaentry{':'.$unikey}=
                   8741: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8742:     }
                   8743: }
                   8744: 
1.261     albertel 8745: sub metadata_generate_part0 {
                   8746:     my ($metadata,$metacache,$uri) = @_;
                   8747:     my %allnames;
1.737     albertel 8748:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8749: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8750: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8751: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8752: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8753: 	    $allnames{$name}=$part;
                   8754: 	  }
                   8755: 	}
                   8756:     }
                   8757:     foreach my $name (keys(%allnames)) {
                   8758:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8759:       my $key=":parameter_0_$name";
1.261     albertel 8760:       $$metacache{"$key.part"}='0';
                   8761:       $$metacache{"$key.name"}=$name;
1.428     albertel 8762:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8763: 					   $allnames{$name}.'_'.$name.
                   8764: 					   '.type'};
1.428     albertel 8765:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8766: 			     '.display'};
1.644     www      8767:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8768:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8769:       $$metacache{"$key.display"}=$olddis;
                   8770:     }
1.71      www      8771: }
                   8772: 
1.764     albertel 8773: # ------------------------------------------------------ Devalidate title cache
                   8774: 
                   8775: sub devalidate_title_cache {
                   8776:     my ($url)=@_;
                   8777:     if (!$env{'request.course.id'}) { return; }
                   8778:     my $symb=&symbread($url);
                   8779:     if (!$symb) { return; }
                   8780:     my $key=$env{'request.course.id'}."\0".$symb;
                   8781:     &devalidate_cache_new('title',$key);
                   8782: }
                   8783: 
1.1014    droeschl 8784: # ------------------------------------------------- Get the title of a course
                   8785: 
                   8786: sub current_course_title {
                   8787:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8788: }
1.301     www      8789: # ------------------------------------------------- Get the title of a resource
                   8790: 
                   8791: sub gettitle {
                   8792:     my $urlsymb=shift;
                   8793:     my $symb=&symbread($urlsymb);
1.534     albertel 8794:     if ($symb) {
1.620     albertel 8795: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8796: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8797: 	if (defined($cached)) { 
                   8798: 	    return $result;
                   8799: 	}
1.534     albertel 8800: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8801: 	my $title='';
1.907     albertel 8802: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8803: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8804: 	} else {
                   8805: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8806: 		    &GDBM_READER(),0640)) {
                   8807: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8808: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8809: 		untie(%bighash);
                   8810: 	    }
1.534     albertel 8811: 	}
                   8812: 	$title=~s/\&colon\;/\:/gs;
                   8813: 	if ($title) {
1.599     albertel 8814: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8815: 	}
                   8816: 	$urlsymb=$url;
                   8817:     }
                   8818:     my $title=&metadata($urlsymb,'title');
                   8819:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8820:     return $title;
1.301     www      8821: }
1.613     albertel 8822: 
1.614     albertel 8823: sub get_slot {
                   8824:     my ($which,$cnum,$cdom)=@_;
                   8825:     if (!$cnum || !$cdom) {
1.790     albertel 8826: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8827: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8828: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8829:     }
1.703     albertel 8830:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8831:     my %slotinfo;
                   8832:     if (exists($remembered{$key})) {
                   8833: 	$slotinfo{$which} = $remembered{$key};
                   8834:     } else {
                   8835: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8836: 	&Apache::lonhomework::showhash(%slotinfo);
                   8837: 	my ($tmp)=keys(%slotinfo);
                   8838: 	if ($tmp=~/^error:/) { return (); }
                   8839: 	$remembered{$key} = $slotinfo{$which};
                   8840:     }
1.616     albertel 8841:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8842: 	return %{$slotinfo{$which}};
                   8843:     }
                   8844:     return $slotinfo{$which};
1.614     albertel 8845: }
1.31      www      8846: # ------------------------------------------------- Update symbolic store links
                   8847: 
                   8848: sub symblist {
                   8849:     my ($mapname,%newhash)=@_;
1.438     www      8850:     $mapname=&deversion(&declutter($mapname));
1.31      www      8851:     my %hash;
1.620     albertel 8852:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8853:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8854:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8855: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8856: 		next if ($url eq 'last_known'
                   8857: 			 && $env{'form.no_update_last_known'});
                   8858: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8859: 						    $newhash{$url}->[1],
                   8860: 						    $newhash{$url}->[0]);
1.191     harris41 8861:             }
1.31      www      8862:             if (untie(%hash)) {
                   8863: 		return 'ok';
                   8864:             }
                   8865:         }
                   8866:     }
                   8867:     return 'error';
1.212     www      8868: }
                   8869: 
                   8870: # --------------------------------------------------------------- Verify a symb
                   8871: 
                   8872: sub symbverify {
1.510     www      8873:     my ($symb,$thisurl)=@_;
                   8874:     my $thisfn=$thisurl;
1.439     www      8875:     $thisfn=&declutter($thisfn);
1.215     www      8876: # direct jump to resource in page or to a sequence - will construct own symbs
                   8877:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8878: # check URL part
1.409     www      8879:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8880: 
1.431     www      8881:     unless ($url eq $thisfn) { return 0; }
1.213     www      8882: 
1.216     www      8883:     $symb=&symbclean($symb);
1.510     www      8884:     $thisurl=&deversion($thisurl);
1.439     www      8885:     $thisfn=&deversion($thisfn);
1.213     www      8886: 
                   8887:     my %bighash;
                   8888:     my $okay=0;
1.431     www      8889: 
1.620     albertel 8890:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8891:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8892:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8893:             $thisurl =~ s/\?.+$//;
                   8894:         }
1.510     www      8895:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8896:         unless ($ids) { 
1.510     www      8897:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8898:         }
                   8899:         if ($ids) {
                   8900: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8901: 	    foreach my $id (split(/\,/,$ids)) {
                   8902: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8903:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8904:                    $symb =~ s/\?.+$//;
                   8905:                }
1.216     www      8906:                if (
                   8907:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8908:    eq $symb) { 
1.620     albertel 8909: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8910: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8911: 		       $okay=1; 
                   8912: 		   }
                   8913: 	       }
1.216     www      8914: 	   }
                   8915:         }
1.213     www      8916: 	untie(%bighash);
                   8917:     }
                   8918:     return $okay;
1.31      www      8919: }
                   8920: 
1.210     www      8921: # --------------------------------------------------------------- Clean-up symb
                   8922: 
                   8923: sub symbclean {
                   8924:     my $symb=shift;
1.568     albertel 8925:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8926: # remove version from map
                   8927:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8928: 
1.210     www      8929: # remove version from URL
                   8930:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8931: 
1.507     www      8932: # remove wrapper
                   8933: 
1.510     www      8934:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8935:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8936:     return $symb;
1.409     www      8937: }
                   8938: 
                   8939: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8940: 
                   8941: sub encode_symb {
                   8942:     my ($map,$resid,$url)=@_;
                   8943:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8944: }
1.409     www      8945: 
                   8946: sub decode_symb {
1.568     albertel 8947:     my $symb=shift;
                   8948:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8949:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8950:     return (&fixversion($map),$resid,&fixversion($url));
                   8951: }
                   8952: 
                   8953: sub fixversion {
                   8954:     my $fn=shift;
1.609     banghart 8955:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8956:     my %bighash;
                   8957:     my $uri=&clutter($fn);
1.620     albertel 8958:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8959: # is this cached?
1.599     albertel 8960:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8961:     if (defined($cached)) { return $result; }
                   8962: # unfortunately not cached, or expired
1.620     albertel 8963:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8964: 	    &GDBM_READER(),0640)) {
                   8965:  	if ($bighash{'version_'.$uri}) {
                   8966:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8967:  	    unless (($version eq 'mostrecent') || 
                   8968: 		    ($version==&getversion($uri))) {
1.440     www      8969:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8970:  	    }
                   8971:  	}
                   8972:  	untie %bighash;
1.413     www      8973:     }
1.599     albertel 8974:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8975: }
                   8976: 
                   8977: sub deversion {
                   8978:     my $url=shift;
                   8979:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8980:     return $url;
1.210     www      8981: }
                   8982: 
1.31      www      8983: # ------------------------------------------------------ Return symb list entry
                   8984: 
                   8985: sub symbread {
1.249     www      8986:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8987:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8988:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8989: # no filename provided? try from environment
1.44      www      8990:     unless ($thisfn) {
1.620     albertel 8991:         if ($env{'request.symb'}) {
                   8992: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8993: 	}
1.620     albertel 8994: 	$thisfn=$env{'request.filename'};
1.44      www      8995:     }
1.569     albertel 8996:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8997: # is that filename actually a symb? Verify, clean, and return
                   8998:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8999: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9000: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9001: 	}
1.242     www      9002:     }
1.44      www      9003:     $thisfn=declutter($thisfn);
1.31      www      9004:     my %hash;
1.37      www      9005:     my %bighash;
                   9006:     my $syval='';
1.620     albertel 9007:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9008:         my $targetfn = $thisfn;
1.609     banghart 9009:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9010:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9011:         }
1.687     albertel 9012: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9013: 	    $targetfn=$1;
                   9014: 	}
1.620     albertel 9015:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9016:                       &GDBM_READER(),0640)) {
1.481     raeburn  9017: 	    $syval=$hash{$targetfn};
1.37      www      9018:             untie(%hash);
                   9019:         }
                   9020: # ---------------------------------------------------------- There was an entry
                   9021:         if ($syval) {
1.601     albertel 9022: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9023: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9024: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9025: 		    #return $env{$cache_str}='';
1.601     albertel 9026: 		#}    
                   9027: 		#$syval.=$1;
                   9028: 	    #}
1.37      www      9029:         } else {
                   9030: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9031:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9032:                             &GDBM_READER(),0640)) {
1.37      www      9033: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9034:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9035:               unless ($ids) { 
                   9036:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9037:               }
                   9038:               unless ($ids) {
                   9039: # alias?
                   9040: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9041:               }
1.37      www      9042:               if ($ids) {
                   9043: # ------------------------------------------------------------------- Has ID(s)
                   9044:                  my @possibilities=split(/\,/,$ids);
1.39      www      9045:                  if ($#possibilities==0) {
                   9046: # ----------------------------------------------- There is only one possibility
1.37      www      9047: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9048: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9049: 						    $resid,$thisfn);
1.249     www      9050:                  } elsif (!$donotrecurse) {
1.39      www      9051: # ------------------------------------------ There is more than one possibility
                   9052:                      my $realpossible=0;
1.800     albertel 9053:                      foreach my $id (@possibilities) {
                   9054: 			 my $file=$bighash{'src_'.$id};
1.39      www      9055:                          if (&allowed('bre',$file)) {
1.800     albertel 9056:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9057:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9058: 				$realpossible++;
1.626     albertel 9059:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9060: 						    $resid,$thisfn);
1.39      www      9061:                             }
                   9062: 			 }
1.191     harris41 9063:                      }
1.39      www      9064: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9065:                  } else {
                   9066:                      $syval='';
1.37      www      9067:                  }
                   9068: 	      }
                   9069:               untie(%bighash)
1.481     raeburn  9070:            }
1.31      www      9071:         }
1.62      www      9072:         if ($syval) {
1.620     albertel 9073: 	    return $env{$cache_str}=$syval;
1.62      www      9074:         }
1.31      www      9075:     }
1.949     raeburn  9076:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9077:     return $env{$cache_str}='';
1.31      www      9078: }
                   9079: 
                   9080: # ---------------------------------------------------------- Return random seed
                   9081: 
1.32      www      9082: sub numval {
                   9083:     my $txt=shift;
                   9084:     $txt=~tr/A-J/0-9/;
                   9085:     $txt=~tr/a-j/0-9/;
                   9086:     $txt=~tr/K-T/0-9/;
                   9087:     $txt=~tr/k-t/0-9/;
                   9088:     $txt=~tr/U-Z/0-5/;
                   9089:     $txt=~tr/u-z/0-5/;
                   9090:     $txt=~s/\D//g;
1.564     albertel 9091:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9092:     return int($txt);
1.368     albertel 9093: }
                   9094: 
1.484     albertel 9095: sub numval2 {
                   9096:     my $txt=shift;
                   9097:     $txt=~tr/A-J/0-9/;
                   9098:     $txt=~tr/a-j/0-9/;
                   9099:     $txt=~tr/K-T/0-9/;
                   9100:     $txt=~tr/k-t/0-9/;
                   9101:     $txt=~tr/U-Z/0-5/;
                   9102:     $txt=~tr/u-z/0-5/;
                   9103:     $txt=~s/\D//g;
                   9104:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9105:     my $total;
                   9106:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9107:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9108:     return int($total);
                   9109: }
                   9110: 
1.575     albertel 9111: sub numval3 {
                   9112:     use integer;
                   9113:     my $txt=shift;
                   9114:     $txt=~tr/A-J/0-9/;
                   9115:     $txt=~tr/a-j/0-9/;
                   9116:     $txt=~tr/K-T/0-9/;
                   9117:     $txt=~tr/k-t/0-9/;
                   9118:     $txt=~tr/U-Z/0-5/;
                   9119:     $txt=~tr/u-z/0-5/;
                   9120:     $txt=~s/\D//g;
                   9121:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9122:     my $total;
                   9123:     foreach my $val (@txts) { $total+=$val; }
                   9124:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9125:     return $total;
                   9126: }
                   9127: 
1.675     albertel 9128: sub digest {
                   9129:     my ($data)=@_;
                   9130:     my $digest=&Digest::MD5::md5($data);
                   9131:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9132:     my ($e,$f);
                   9133:     {
                   9134:         use integer;
                   9135:         $e=($a+$b);
                   9136:         $f=($c+$d);
                   9137:         if ($_64bit) {
                   9138:             $e=(($e<<32)>>32);
                   9139:             $f=(($f<<32)>>32);
                   9140:         }
                   9141:     }
                   9142:     if (wantarray) {
                   9143: 	return ($e,$f);
                   9144:     } else {
                   9145: 	my $g;
                   9146: 	{
                   9147: 	    use integer;
                   9148: 	    $g=($e+$f);
                   9149: 	    if ($_64bit) {
                   9150: 		$g=(($g<<32)>>32);
                   9151: 	    }
                   9152: 	}
                   9153: 	return $g;
                   9154:     }
                   9155: }
                   9156: 
1.368     albertel 9157: sub latest_rnd_algorithm_id {
1.675     albertel 9158:     return '64bit5';
1.366     albertel 9159: }
1.32      www      9160: 
1.503     albertel 9161: sub get_rand_alg {
                   9162:     my ($courseid)=@_;
1.790     albertel 9163:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9164:     if ($courseid) {
1.620     albertel 9165: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9166:     }
                   9167:     return &latest_rnd_algorithm_id();
                   9168: }
                   9169: 
1.562     albertel 9170: sub validCODE {
                   9171:     my ($CODE)=@_;
                   9172:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9173:     return 0;
                   9174: }
                   9175: 
1.491     albertel 9176: sub getCODE {
1.620     albertel 9177:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9178:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9179: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9180: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9181: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9182:     }
                   9183:     return undef;
                   9184: }
                   9185: 
1.31      www      9186: sub rndseed {
1.155     albertel 9187:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9188:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9189:     if (!defined($symb)) {
1.366     albertel 9190: 	unless ($symb=$wsymb) { return time; }
                   9191:     }
                   9192:     if (!$courseid) { $courseid=$wcourseid; }
                   9193:     if (!$domain) { $domain=$wdomain; }
                   9194:     if (!$username) { $username=$wusername }
1.503     albertel 9195:     my $which=&get_rand_alg();
1.803     albertel 9196: 
1.491     albertel 9197:     if (defined(&getCODE())) {
1.675     albertel 9198: 	if ($which eq '64bit5') {
                   9199: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9200: 	} elsif ($which eq '64bit4') {
1.575     albertel 9201: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9202: 	} else {
                   9203: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9204: 	}
1.675     albertel 9205:     } elsif ($which eq '64bit5') {
                   9206: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9207:     } elsif ($which eq '64bit4') {
                   9208: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9209:     } elsif ($which eq '64bit3') {
                   9210: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9211:     } elsif ($which eq '64bit2') {
                   9212: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9213:     } elsif ($which eq '64bit') {
                   9214: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9215:     }
                   9216:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9217: }
                   9218: 
                   9219: sub rndseed_32bit {
                   9220:     my ($symb,$courseid,$domain,$username)=@_;
                   9221:     {
                   9222: 	use integer;
                   9223: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9224: 	my $symbseed=numval($symb) << 22;
                   9225: 	my $namechck=unpack("%32C*",$username) << 17;
                   9226: 	my $nameseed=numval($username) << 12;
                   9227: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9228: 	my $courseseed=unpack("%32C*",$courseid);
                   9229: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9230: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9231: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9232: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9233: 	return $num;
                   9234:     }
                   9235: }
                   9236: 
                   9237: sub rndseed_64bit {
                   9238:     my ($symb,$courseid,$domain,$username)=@_;
                   9239:     {
                   9240: 	use integer;
                   9241: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9242: 	my $symbseed=numval($symb) << 10;
                   9243: 	my $namechck=unpack("%32S*",$username);
                   9244: 	
                   9245: 	my $nameseed=numval($username) << 21;
                   9246: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9247: 	my $courseseed=unpack("%32S*",$courseid);
                   9248: 	
                   9249: 	my $num1=$symbchck+$symbseed+$namechck;
                   9250: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9251: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9252: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9253: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9254: 	return "$num1,$num2";
1.155     albertel 9255:     }
1.366     albertel 9256: }
                   9257: 
1.443     albertel 9258: sub rndseed_64bit2 {
                   9259:     my ($symb,$courseid,$domain,$username)=@_;
                   9260:     {
                   9261: 	use integer;
                   9262: 	# strings need to be an even # of cahracters long, it it is odd the
                   9263:         # last characters gets thrown away
                   9264: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9265: 	my $symbseed=numval($symb) << 10;
                   9266: 	my $namechck=unpack("%32S*",$username.' ');
                   9267: 	
                   9268: 	my $nameseed=numval($username) << 21;
1.501     albertel 9269: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9270: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9271: 	
                   9272: 	my $num1=$symbchck+$symbseed+$namechck;
                   9273: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9274: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9275: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9276: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9277: 	return "$num1,$num2";
                   9278:     }
                   9279: }
                   9280: 
                   9281: sub rndseed_64bit3 {
                   9282:     my ($symb,$courseid,$domain,$username)=@_;
                   9283:     {
                   9284: 	use integer;
                   9285: 	# strings need to be an even # of cahracters long, it it is odd the
                   9286:         # last characters gets thrown away
                   9287: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9288: 	my $symbseed=numval2($symb) << 10;
                   9289: 	my $namechck=unpack("%32S*",$username.' ');
                   9290: 	
                   9291: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9292: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9293: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9294: 	
                   9295: 	my $num1=$symbchck+$symbseed+$namechck;
                   9296: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9297: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9298: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9299: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9300: 	
1.503     albertel 9301: 	return "$num1:$num2";
1.443     albertel 9302:     }
                   9303: }
                   9304: 
1.575     albertel 9305: sub rndseed_64bit4 {
                   9306:     my ($symb,$courseid,$domain,$username)=@_;
                   9307:     {
                   9308: 	use integer;
                   9309: 	# strings need to be an even # of cahracters long, it it is odd the
                   9310:         # last characters gets thrown away
                   9311: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9312: 	my $symbseed=numval3($symb) << 10;
                   9313: 	my $namechck=unpack("%32S*",$username.' ');
                   9314: 	
                   9315: 	my $nameseed=numval3($username) << 21;
                   9316: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9317: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9318: 	
                   9319: 	my $num1=$symbchck+$symbseed+$namechck;
                   9320: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9321: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9322: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9323: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9324: 	
                   9325: 	return "$num1:$num2";
                   9326:     }
                   9327: }
                   9328: 
1.675     albertel 9329: sub rndseed_64bit5 {
                   9330:     my ($symb,$courseid,$domain,$username)=@_;
                   9331:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9332:     return "$num1:$num2";
                   9333: }
                   9334: 
1.366     albertel 9335: sub rndseed_CODE_64bit {
                   9336:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9337:     {
1.366     albertel 9338: 	use integer;
1.443     albertel 9339: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9340: 	my $symbseed=numval2($symb);
1.491     albertel 9341: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9342: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9343: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9344: 	my $num1=$symbseed+$CODEchck;
                   9345: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9346: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9347: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9348: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9349: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9350: 	return "$num1:$num2";
1.366     albertel 9351:     }
                   9352: }
                   9353: 
1.575     albertel 9354: sub rndseed_CODE_64bit4 {
                   9355:     my ($symb,$courseid,$domain,$username)=@_;
                   9356:     {
                   9357: 	use integer;
                   9358: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9359: 	my $symbseed=numval3($symb);
                   9360: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9361: 	my $CODEseed=numval3(&getCODE());
                   9362: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9363: 	my $num1=$symbseed+$CODEchck;
                   9364: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9365: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9366: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9367: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9368: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9369: 	return "$num1:$num2";
                   9370:     }
                   9371: }
                   9372: 
1.675     albertel 9373: sub rndseed_CODE_64bit5 {
                   9374:     my ($symb,$courseid,$domain,$username)=@_;
                   9375:     my $code = &getCODE();
                   9376:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9377:     return "$num1:$num2";
                   9378: }
                   9379: 
1.366     albertel 9380: sub setup_random_from_rndseed {
                   9381:     my ($rndseed)=@_;
1.503     albertel 9382:     if ($rndseed =~/([,:])/) {
                   9383: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9384: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9385:     } else {
                   9386: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9387:     }
1.36      albertel 9388: }
                   9389: 
1.474     albertel 9390: sub latest_receipt_algorithm_id {
1.835     albertel 9391:     return 'receipt3';
1.474     albertel 9392: }
                   9393: 
1.480     www      9394: sub recunique {
                   9395:     my $fucourseid=shift;
                   9396:     my $unique;
1.835     albertel 9397:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9398: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9399: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9400:     } else {
                   9401: 	$unique=$perlvar{'lonReceipt'};
                   9402:     }
                   9403:     return unpack("%32C*",$unique);
                   9404: }
                   9405: 
                   9406: sub recprefix {
                   9407:     my $fucourseid=shift;
                   9408:     my $prefix;
1.835     albertel 9409:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9410: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9411: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9412:     } else {
                   9413: 	$prefix=$perlvar{'lonHostID'};
                   9414:     }
                   9415:     return unpack("%32C*",$prefix);
                   9416: }
                   9417: 
1.76      www      9418: sub ireceipt {
1.474     albertel 9419:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9420: 
                   9421:     my $return =&recprefix($fucourseid).'-';
                   9422: 
                   9423:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9424: 	$env{'request.state'} eq 'construct') {
                   9425: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9426: 	return $return;
                   9427:     }
                   9428: 
1.76      www      9429:     my $cuname=unpack("%32C*",$funame);
                   9430:     my $cudom=unpack("%32C*",$fudom);
                   9431:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9432:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9433:     my $cunique=&recunique($fucourseid);
1.474     albertel 9434:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9435:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9436: 
1.790     albertel 9437: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9438: 			       
                   9439: 	$return.= ($cunique%$cuname+
                   9440: 		   $cunique%$cudom+
                   9441: 		   $cusymb%$cuname+
                   9442: 		   $cusymb%$cudom+
                   9443: 		   $cucourseid%$cuname+
                   9444: 		   $cucourseid%$cudom+
                   9445: 		   $cpart%$cuname+
                   9446: 		   $cpart%$cudom);
                   9447:     } else {
                   9448: 	$return.= ($cunique%$cuname+
                   9449: 		   $cunique%$cudom+
                   9450: 		   $cusymb%$cuname+
                   9451: 		   $cusymb%$cudom+
                   9452: 		   $cucourseid%$cuname+
                   9453: 		   $cucourseid%$cudom);
                   9454:     }
                   9455:     return $return;
1.76      www      9456: }
                   9457: 
                   9458: sub receipt {
1.474     albertel 9459:     my ($part)=@_;
1.790     albertel 9460:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9461:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9462: }
1.260     ng       9463: 
1.790     albertel 9464: sub whichuser {
                   9465:     my ($passedsymb)=@_;
                   9466:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9467:     if (defined($env{'form.grade_symb'})) {
                   9468: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9469: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9470: 	if (!$allowed &&
                   9471: 	    exists($env{'request.course.sec'}) &&
                   9472: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9473: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9474: 			      '/'.$env{'request.course.sec'});
                   9475: 	}
                   9476: 	if ($allowed) {
                   9477: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9478: 	    $courseid=$tmp_courseid;
                   9479: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9480: 	    ($name)=&get_env_multiple('form.grade_username');
                   9481: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9482: 	}
                   9483:     }
                   9484:     if (!$passedsymb) {
                   9485: 	$symb=&symbread();
                   9486:     } else {
                   9487: 	$symb=$passedsymb;
                   9488:     }
                   9489:     $courseid=$env{'request.course.id'};
                   9490:     $domain=$env{'user.domain'};
                   9491:     $name=$env{'user.name'};
                   9492:     if ($name eq 'public' && $domain eq 'public') {
                   9493: 	if (!defined($env{'form.username'})) {
                   9494: 	    $env{'form.username'}.=time.rand(10000000);
                   9495: 	}
                   9496: 	$name.=$env{'form.username'};
                   9497:     }
                   9498:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9499: 
                   9500: }
                   9501: 
1.36      albertel 9502: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9503: # returns either the contents of the file or 
                   9504: # -1 if the file doesn't exist
1.481     raeburn  9505: #
                   9506: # if the target is a file that was uploaded via DOCS, 
                   9507: # a check will be made to see if a current copy exists on the local server,
                   9508: # if it does this will be served, otherwise a copy will be retrieved from
                   9509: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9510: # the local server.   
1.472     albertel 9511: 
1.36      albertel 9512: sub getfile {
1.538     albertel 9513:     my ($file) = @_;
1.609     banghart 9514:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9515:     &repcopy($file);
                   9516:     return &readfile($file);
                   9517: }
                   9518: 
                   9519: sub repcopy_userfile {
                   9520:     my ($file)=@_;
1.609     banghart 9521:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9522:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9523:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9524: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9525:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9526:     if (-e "$file") {
1.828     www      9527: # we already have a local copy, check it out
1.538     albertel 9528: 	my @fileinfo = stat($file);
1.828     www      9529: 	my $rtncode;
                   9530: 	my $info;
1.538     albertel 9531: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9532: 	if ($lwpresp ne 'ok') {
1.828     www      9533: # there is no such file anymore, even though we had a local copy
1.482     albertel 9534: 	    if ($rtncode eq '404') {
1.538     albertel 9535: 		unlink($file);
1.482     albertel 9536: 	    }
                   9537: 	    return -1;
                   9538: 	}
                   9539: 	if ($info < $fileinfo[9]) {
1.828     www      9540: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9541: 	    return 'ok';
1.828     www      9542: 	} else {
                   9543: # the file is outdated, get rid of it
                   9544: 	    unlink($file);
1.482     albertel 9545: 	}
1.828     www      9546:     }
                   9547: # one way or the other, at this point, we don't have the file
                   9548: # construct the correct path for the file
                   9549:     my @parts = ($cdom,$cnum); 
                   9550:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9551: 	push @parts, split(/\//,$1);
                   9552:     }
                   9553:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9554:     foreach my $part (@parts) {
                   9555: 	$path .= '/'.$part;
                   9556: 	if (!-e $path) {
                   9557: 	    mkdir($path,0770);
1.482     albertel 9558: 	}
                   9559:     }
1.828     www      9560: # now the path exists for sure
                   9561: # get a user agent
                   9562:     my $ua=new LWP::UserAgent;
                   9563:     my $transferfile=$file.'.in.transfer';
                   9564: # FIXME: this should flock
                   9565:     if (-e $transferfile) { return 'ok'; }
                   9566:     my $request;
                   9567:     $uri=~s/^\///;
1.980     raeburn  9568:     my $homeserver = &homeserver($cnum,$cdom);
                   9569:     my $protocol = $protocol{$homeserver};
                   9570:     $protocol = 'http' if ($protocol ne 'https');
                   9571:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9572:     my $response=$ua->request($request,$transferfile);
                   9573: # did it work?
                   9574:     if ($response->is_error()) {
                   9575: 	unlink($transferfile);
                   9576: 	&logthis("Userfile repcopy failed for $uri");
                   9577: 	return -1;
                   9578:     }
                   9579: # worked, rename the transfer file
                   9580:     rename($transferfile,$file);
1.607     raeburn  9581:     return 'ok';
1.481     raeburn  9582: }
                   9583: 
1.517     albertel 9584: sub tokenwrapper {
                   9585:     my $uri=shift;
1.980     raeburn  9586:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9587:     $uri=~s|^/||;
1.620     albertel 9588:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9589:     my $token=$1;
1.552     albertel 9590:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9591:     if ($udom && $uname && $file) {
                   9592: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9593:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9594:         my $homeserver = &homeserver($uname,$udom);
                   9595:         my $protocol = $protocol{$homeserver};
                   9596:         $protocol = 'http' if ($protocol ne 'https');
                   9597:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9598:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9599:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9600:     } else {
                   9601:         return '/adm/notfound.html';
                   9602:     }
                   9603: }
                   9604: 
1.828     www      9605: # call with reqtype HEAD: get last modification time
                   9606: # call with reqtype GET: get the file contents
                   9607: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9608: #
1.481     raeburn  9609: sub getuploaded {
                   9610:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9611:     $uri=~s/^\///;
1.980     raeburn  9612:     my $homeserver = &homeserver($cnum,$cdom);
                   9613:     my $protocol = $protocol{$homeserver};
                   9614:     $protocol = 'http' if ($protocol ne 'https');
                   9615:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9616:     my $ua=new LWP::UserAgent;
                   9617:     my $request=new HTTP::Request($reqtype,$uri);
                   9618:     my $response=$ua->request($request);
                   9619:     $$rtncode = $response->code;
1.482     albertel 9620:     if (! $response->is_success()) {
                   9621: 	return 'failed';
                   9622:     }      
                   9623:     if ($reqtype eq 'HEAD') {
1.486     www      9624: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9625:     } elsif ($reqtype eq 'GET') {
                   9626: 	$$info = $response->content;
1.472     albertel 9627:     }
1.482     albertel 9628:     return 'ok';
1.36      albertel 9629: }
                   9630: 
1.481     raeburn  9631: sub readfile {
                   9632:     my $file = shift;
                   9633:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9634:     my $fh;
                   9635:     open($fh,"<$file");
                   9636:     my $a='';
1.800     albertel 9637:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9638:     return $a;
                   9639: }
                   9640: 
1.36      albertel 9641: sub filelocation {
1.590     banghart 9642:     my ($dir,$file) = @_;
                   9643:     my $location;
                   9644:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9645: 
                   9646:     if ($file =~ m-^/adm/-) {
                   9647: 	$file=~s-^/adm/wrapper/-/-;
                   9648: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9649:     }
1.882     albertel 9650: 
1.590     banghart 9651:     if ($file=~m:^/~:) { # is a contruction space reference
                   9652:         $location = $file;
                   9653:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9654:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9655: 	# is a correct contruction space reference
                   9656:         $location = $file;
1.956     raeburn  9657:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9658:         $location = $file;
1.609     banghart 9659:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9660:         my ($udom,$uname,$filename)=
1.811     albertel 9661:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9662:         my $home=&homeserver($uname,$udom);
                   9663:         my $is_me=0;
                   9664:         my @ids=&current_machine_ids();
                   9665:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9666:         if ($is_me) {
1.955     raeburn  9667:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9668:         } else {
                   9669:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9670:   	      $udom.'/'.$uname.'/'.$filename;
                   9671:         }
1.882     albertel 9672:     } elsif ($file =~ m-^/adm/-) {
                   9673: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9674:     } else {
                   9675:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9676:         $file=~s:^/res/:/:;
                   9677:         if ( !( $file =~ m:^/:) ) {
                   9678:             $location = $dir. '/'.$file;
                   9679:         } else {
                   9680:             $location = '/home/httpd/html/res'.$file;
                   9681:         }
1.59      albertel 9682:     }
1.590     banghart 9683:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9684:     while ($location=~m{/\.\./}) {
                   9685: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9686: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9687: 	} else {
                   9688: 	    $location=~ s{/\.\./}{/}g;
                   9689: 	}
                   9690:     } #remove dir/..
1.590     banghart 9691:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9692:     return $location;
1.46      www      9693: }
1.36      albertel 9694: 
1.46      www      9695: sub hreflocation {
                   9696:     my ($dir,$file)=@_;
1.980     raeburn  9697:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9698: 	$file=filelocation($dir,$file);
1.700     albertel 9699:     } elsif ($file=~m-^/adm/-) {
                   9700: 	$file=~s-^/adm/wrapper/-/-;
                   9701: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9702:     }
                   9703:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9704: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9705:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9706: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9707:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9708: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9709: 	    -/uploaded/$1/$2/-x;
1.46      www      9710:     }
1.913     albertel 9711:     if ($file=~ m{^/userfiles/}) {
                   9712: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9713:     }
1.462     albertel 9714:     return $file;
1.465     albertel 9715: }
                   9716: 
                   9717: sub current_machine_domains {
1.853     albertel 9718:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9719: }
                   9720: 
                   9721: sub machine_domains {
                   9722:     my ($hostname) = @_;
1.465     albertel 9723:     my @domains;
1.838     albertel 9724:     my %hostname = &all_hostnames();
1.465     albertel 9725:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9726: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9727: 	if ($hostname eq $name) {
1.844     albertel 9728: 	    push(@domains,&host_domain($id));
1.465     albertel 9729: 	}
                   9730:     }
                   9731:     return @domains;
                   9732: }
                   9733: 
                   9734: sub current_machine_ids {
1.853     albertel 9735:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9736: }
                   9737: 
                   9738: sub machine_ids {
                   9739:     my ($hostname) = @_;
                   9740:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9741:     my @ids;
1.888     albertel 9742:     my %name_to_host = &all_names();
1.889     albertel 9743:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9744: 	return @{ $name_to_host{$hostname} };
                   9745:     }
                   9746:     return;
1.31      www      9747: }
                   9748: 
1.824     raeburn  9749: sub additional_machine_domains {
                   9750:     my @domains;
                   9751:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9752:     while( my $line = <$fh>) {
                   9753:         $line =~ s/\s//g;
                   9754:         push(@domains,$line);
                   9755:     }
                   9756:     return @domains;
                   9757: }
                   9758: 
                   9759: sub default_login_domain {
                   9760:     my $domain = $perlvar{'lonDefDomain'};
                   9761:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9762:     foreach my $posdom (&current_machine_domains(),
                   9763:                         &additional_machine_domains()) {
                   9764:         if (lc($posdom) eq lc($testdomain)) {
                   9765:             $domain=$posdom;
                   9766:             last;
                   9767:         }
                   9768:     }
                   9769:     return $domain;
                   9770: }
                   9771: 
1.31      www      9772: # ------------------------------------------------------------- Declutters URLs
                   9773: 
                   9774: sub declutter {
                   9775:     my $thisfn=shift;
1.569     albertel 9776:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9777:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9778:     $thisfn=~s/^\///;
1.697     albertel 9779:     $thisfn=~s|^adm/wrapper/||;
                   9780:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9781:     $thisfn=~s/^res\///;
1.1032    raeburn  9782:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9783:         $thisfn=~s/\?.+$//;
                   9784:     }
1.268     www      9785:     return $thisfn;
                   9786: }
                   9787: 
                   9788: # ------------------------------------------------------------- Clutter up URLs
                   9789: 
                   9790: sub clutter {
                   9791:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9792:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9793: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9794:        $thisfn='/res'.$thisfn; 
                   9795:     }
1.1031    raeburn  9796:     if ($thisfn !~m|^/adm|) {
                   9797: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9798: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9799: 	} else {
                   9800: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9801: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9802: 	    if ($embstyle eq 'ssi'
                   9803: 		|| ($embstyle eq 'hdn')
                   9804: 		|| ($embstyle eq 'rat')
                   9805: 		|| ($embstyle eq 'prv')
                   9806: 		|| ($embstyle eq 'ign')) {
                   9807: 		#do nothing with these
                   9808: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9809: 		|| ($embstyle eq 'emb')
                   9810: 		|| ($embstyle eq 'wrp')) {
                   9811: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9812: 	    } elsif ($embstyle eq 'unk'
                   9813: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9814: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9815: 	    } else {
1.718     www      9816: #		&logthis("Got a blank emb style");
1.695     albertel 9817: 	    }
1.694     albertel 9818: 	}
                   9819:     }
1.31      www      9820:     return $thisfn;
1.12      www      9821: }
                   9822: 
1.787     albertel 9823: sub clutter_with_no_wrapper {
                   9824:     my $uri = &clutter(shift);
                   9825:     if ($uri =~ m-^/adm/-) {
                   9826: 	$uri =~ s-^/adm/wrapper/-/-;
                   9827: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9828:     }
                   9829:     return $uri;
                   9830: }
                   9831: 
1.557     albertel 9832: sub freeze_escape {
                   9833:     my ($value)=@_;
                   9834:     if (ref($value)) {
                   9835: 	$value=&nfreeze($value);
                   9836: 	return '__FROZEN__'.&escape($value);
                   9837:     }
                   9838:     return &escape($value);
                   9839: }
                   9840: 
1.11      www      9841: 
1.557     albertel 9842: sub thaw_unescape {
                   9843:     my ($value)=@_;
                   9844:     if ($value =~ /^__FROZEN__/) {
                   9845: 	substr($value,0,10,undef);
                   9846: 	$value=&unescape($value);
                   9847: 	return &thaw($value);
                   9848:     }
                   9849:     return &unescape($value);
                   9850: }
                   9851: 
1.436     albertel 9852: sub correct_line_ends {
                   9853:     my ($result)=@_;
                   9854:     $$result =~s/\r\n/\n/mg;
                   9855:     $$result =~s/\r/\n/mg;
1.415     albertel 9856: }
1.1       albertel 9857: # ================================================================ Main Program
                   9858: 
1.184     www      9859: sub goodbye {
1.204     albertel 9860:    &logthis("Starting Shut down");
1.443     albertel 9861: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9862:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9863: #converted
1.599     albertel 9864: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9865:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9866: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9867: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9868: #1.1 only
1.870     albertel 9869: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9870: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9871: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9872: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9873:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9874:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9875:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9876:    &flushcourselogs();
                   9877:    &logthis("Shutting down");
                   9878: }
                   9879: 
1.852     albertel 9880: sub get_dns {
1.869     albertel 9881:     my ($url,$func,$ignore_cache) = @_;
                   9882:     if (!$ignore_cache) {
                   9883: 	my ($content,$cached)=
                   9884: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9885: 	if ($cached) {
                   9886: 	    &$func($content);
                   9887: 	    return;
                   9888: 	}
                   9889:     }
                   9890: 
                   9891:     my %alldns;
1.852     albertel 9892:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9893:     foreach my $dns (<$config>) {
                   9894: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9895:         my $line = $1;
                   9896:         my ($host,$protocol) = split(/:/,$line);
                   9897:         if ($protocol ne 'https') {
                   9898:             $protocol = 'http';
                   9899:         }
                   9900: 	$alldns{$host} = $protocol;
1.869     albertel 9901:     }
                   9902:     while (%alldns) {
                   9903: 	my ($dns) = keys(%alldns);
1.852     albertel 9904: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9905: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9906: 	my $response=$ua->request($request);
1.979     raeburn  9907:         delete($alldns{$dns});
1.852     albertel 9908: 	next if ($response->is_error());
                   9909: 	my @content = split("\n",$response->content);
1.869     albertel 9910: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9911: 	&$func(\@content);
1.869     albertel 9912: 	return;
1.852     albertel 9913:     }
                   9914:     close($config);
1.871     albertel 9915:     my $which = (split('/',$url))[3];
                   9916:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9917:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9918:     my @content = <$config>;
                   9919:     &$func(\@content);
                   9920:     return;
1.852     albertel 9921: }
1.327     albertel 9922: # ------------------------------------------------------------ Read domain file
                   9923: {
1.852     albertel 9924:     my $loaded;
1.846     albertel 9925:     my %domain;
                   9926: 
1.852     albertel 9927:     sub parse_domain_tab {
                   9928: 	my ($lines) = @_;
                   9929: 	foreach my $line (@$lines) {
                   9930: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9931: 
1.846     albertel 9932: 	    chomp($line);
1.852     albertel 9933: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9934: 	    my %this_domain;
                   9935: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9936: 			       'lang_def', 'city', 'longi', 'lati',
                   9937: 			       'primary') {
                   9938: 		$this_domain{$field} = shift(@elements);
                   9939: 	    }
                   9940: 	    $domain{$name} = \%this_domain;
1.852     albertel 9941: 	}
                   9942:     }
1.864     albertel 9943: 
                   9944:     sub reset_domain_info {
                   9945: 	undef($loaded);
                   9946: 	undef(%domain);
                   9947:     }
                   9948: 
1.852     albertel 9949:     sub load_domain_tab {
1.869     albertel 9950: 	my ($ignore_cache) = @_;
                   9951: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9952: 	my $fh;
                   9953: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9954: 	    my @lines = <$fh>;
                   9955: 	    &parse_domain_tab(\@lines);
1.448     albertel 9956: 	}
1.852     albertel 9957: 	close($fh);
                   9958: 	$loaded = 1;
1.327     albertel 9959:     }
1.846     albertel 9960: 
                   9961:     sub domain {
1.852     albertel 9962: 	&load_domain_tab() if (!$loaded);
                   9963: 
1.846     albertel 9964: 	my ($name,$what) = @_;
                   9965: 	return if ( !exists($domain{$name}) );
                   9966: 
                   9967: 	if (!$what) {
                   9968: 	    return $domain{$name}{'description'};
                   9969: 	}
                   9970: 	return $domain{$name}{$what};
                   9971:     }
1.974     raeburn  9972: 
                   9973:     sub domain_info {
                   9974:         &load_domain_tab() if (!$loaded);
                   9975:         return %domain;
                   9976:     }
                   9977: 
1.327     albertel 9978: }
                   9979: 
                   9980: 
1.1       albertel 9981: # ------------------------------------------------------------- Read hosts file
                   9982: {
1.838     albertel 9983:     my %hostname;
1.844     albertel 9984:     my %hostdom;
1.845     albertel 9985:     my %libserv;
1.852     albertel 9986:     my $loaded;
1.888     albertel 9987:     my %name_to_host;
1.1056.4.6  raeburn  9988:     my %internetdom;
1.852     albertel 9989: 
                   9990:     sub parse_hosts_tab {
                   9991: 	my ($file) = @_;
                   9992: 	foreach my $configline (@$file) {
                   9993: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9994: 	    next if ($configline =~ /^\^/);
                   9995: 	    chomp($configline);
1.1056.4.6  raeburn  9996: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 9997: 	    $name=~s/\s//g;
                   9998: 	    if ($id && $domain && $role && $name) {
                   9999: 		$hostname{$id}=$name;
1.888     albertel 10000: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10001: 		$hostdom{$id}=$domain;
                   10002: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10003:                 if (defined($protocol)) {
                   10004:                     if ($protocol eq 'https') {
                   10005:                         $protocol{$id} = $protocol;
                   10006:                     } else {
                   10007:                         $protocol{$id} = 'http'; 
                   10008:                     }
1.968     raeburn  10009:                 } else {
1.969     raeburn  10010:                     $protocol{$id} = 'http';
1.968     raeburn  10011:                 }
1.1056.4.6  raeburn  10012:                 if (defined($intdom)) {
                   10013:                     $internetdom{$id} = $intdom;
                   10014:                 }
1.852     albertel 10015: 	    }
                   10016: 	}
                   10017:     }
1.864     albertel 10018:     
                   10019:     sub reset_hosts_info {
1.897     albertel 10020: 	&purge_remembered();
1.864     albertel 10021: 	&reset_domain_info();
                   10022: 	&reset_hosts_ip_info();
1.892     albertel 10023: 	undef(%name_to_host);
1.864     albertel 10024: 	undef(%hostname);
                   10025: 	undef(%hostdom);
                   10026: 	undef(%libserv);
                   10027: 	undef($loaded);
                   10028:     }
1.1       albertel 10029: 
1.852     albertel 10030:     sub load_hosts_tab {
1.869     albertel 10031: 	my ($ignore_cache) = @_;
                   10032: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10033: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10034: 	my @config = <$config>;
                   10035: 	&parse_hosts_tab(\@config);
                   10036: 	close($config);
                   10037: 	$loaded=1;
1.1       albertel 10038:     }
1.852     albertel 10039: 
1.838     albertel 10040:     sub hostname {
1.852     albertel 10041: 	&load_hosts_tab() if (!$loaded);
                   10042: 
1.838     albertel 10043: 	my ($lonid) = @_;
                   10044: 	return $hostname{$lonid};
                   10045:     }
1.845     albertel 10046: 
1.838     albertel 10047:     sub all_hostnames {
1.852     albertel 10048: 	&load_hosts_tab() if (!$loaded);
                   10049: 
1.838     albertel 10050: 	return %hostname;
                   10051:     }
1.845     albertel 10052: 
1.888     albertel 10053:     sub all_names {
                   10054: 	&load_hosts_tab() if (!$loaded);
                   10055: 
                   10056: 	return %name_to_host;
                   10057:     }
                   10058: 
1.974     raeburn  10059:     sub all_host_domain {
                   10060:         &load_hosts_tab() if (!$loaded);
                   10061:         return %hostdom;
                   10062:     }
                   10063: 
1.845     albertel 10064:     sub is_library {
1.852     albertel 10065: 	&load_hosts_tab() if (!$loaded);
                   10066: 
1.845     albertel 10067: 	return exists($libserv{$_[0]});
                   10068:     }
                   10069: 
                   10070:     sub all_library {
1.852     albertel 10071: 	&load_hosts_tab() if (!$loaded);
                   10072: 
1.845     albertel 10073: 	return %libserv;
                   10074:     }
                   10075: 
1.1056.4.2  raeburn  10076:     sub unique_library {
                   10077:         #2x reverse removes all hostnames that appear more than once
                   10078:         my %unique = reverse &all_library();
                   10079:         return reverse %unique;
                   10080:     }
                   10081: 
1.841     albertel 10082:     sub get_servers {
1.852     albertel 10083: 	&load_hosts_tab() if (!$loaded);
                   10084: 
1.841     albertel 10085: 	my ($domain,$type) = @_;
                   10086: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10087: 	                                          : %hostname;
                   10088: 	my %result;
1.842     albertel 10089: 	if (ref($domain) eq 'ARRAY') {
                   10090: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10091: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10092: 		    $result{$host} = $hostname;
                   10093: 		}
                   10094: 	    }
                   10095: 	} else {
                   10096: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10097: 		if ($hostdom{$host} eq $domain) {
                   10098: 		    $result{$host} = $hostname;
                   10099: 		}
1.841     albertel 10100: 	    }
                   10101: 	}
                   10102: 	return %result;
                   10103:     }
1.845     albertel 10104: 
1.1056.4.2  raeburn  10105:     sub get_unique_servers {
                   10106:         my %unique = reverse &get_servers(@_);
                   10107:         return reverse %unique;
                   10108:     }
                   10109: 
1.844     albertel 10110:     sub host_domain {
1.852     albertel 10111: 	&load_hosts_tab() if (!$loaded);
                   10112: 
1.844     albertel 10113: 	my ($lonid) = @_;
                   10114: 	return $hostdom{$lonid};
                   10115:     }
                   10116: 
1.841     albertel 10117:     sub all_domains {
1.852     albertel 10118: 	&load_hosts_tab() if (!$loaded);
                   10119: 
1.841     albertel 10120: 	my %seen;
                   10121: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10122: 	return @uniq;
                   10123:     }
1.1056.4.3  raeburn  10124: 
                   10125:     sub internet_dom {
                   10126:         &load_hosts_tab() if (!$loaded);
                   10127: 
                   10128:         my ($lonid) = @_;
                   10129:         return $internetdom{$lonid};
                   10130:     }
1.1       albertel 10131: }
                   10132: 
1.847     albertel 10133: { 
                   10134:     my %iphost;
1.856     albertel 10135:     my %name_to_ip;
                   10136:     my %lonid_to_ip;
1.869     albertel 10137: 
1.847     albertel 10138:     sub get_hosts_from_ip {
                   10139: 	my ($ip) = @_;
                   10140: 	my %iphosts = &get_iphost();
                   10141: 	if (ref($iphosts{$ip})) {
                   10142: 	    return @{$iphosts{$ip}};
                   10143: 	}
                   10144: 	return;
1.839     albertel 10145:     }
1.864     albertel 10146:     
                   10147:     sub reset_hosts_ip_info {
                   10148: 	undef(%iphost);
                   10149: 	undef(%name_to_ip);
                   10150: 	undef(%lonid_to_ip);
                   10151:     }
1.856     albertel 10152: 
                   10153:     sub get_host_ip {
                   10154: 	my ($lonid) = @_;
                   10155: 	if (exists($lonid_to_ip{$lonid})) {
                   10156: 	    return $lonid_to_ip{$lonid};
                   10157: 	}
                   10158: 	my $name=&hostname($lonid);
                   10159:    	my $ip = gethostbyname($name);
                   10160: 	return if (!$ip || length($ip) ne 4);
                   10161: 	$ip=inet_ntoa($ip);
                   10162: 	$name_to_ip{$name}   = $ip;
                   10163: 	$lonid_to_ip{$lonid} = $ip;
                   10164: 	return $ip;
                   10165:     }
1.847     albertel 10166:     
                   10167:     sub get_iphost {
1.869     albertel 10168: 	my ($ignore_cache) = @_;
1.894     albertel 10169: 
1.869     albertel 10170: 	if (!$ignore_cache) {
                   10171: 	    if (%iphost) {
                   10172: 		return %iphost;
                   10173: 	    }
                   10174: 	    my ($ip_info,$cached)=
                   10175: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10176: 	    if ($cached) {
                   10177: 		%iphost      = %{$ip_info->[0]};
                   10178: 		%name_to_ip  = %{$ip_info->[1]};
                   10179: 		%lonid_to_ip = %{$ip_info->[2]};
                   10180: 		return %iphost;
                   10181: 	    }
                   10182: 	}
1.894     albertel 10183: 
                   10184: 	# get yesterday's info for fallback
                   10185: 	my %old_name_to_ip;
                   10186: 	my ($ip_info,$cached)=
                   10187: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10188: 	if ($cached) {
                   10189: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10190: 	}
                   10191: 
1.888     albertel 10192: 	my %name_to_host = &all_names();
                   10193: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10194: 	    my $ip;
                   10195: 	    if (!exists($name_to_ip{$name})) {
                   10196: 		$ip = gethostbyname($name);
                   10197: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10198: 		    if (defined($old_name_to_ip{$name})) {
                   10199: 			$ip = $old_name_to_ip{$name};
                   10200: 			&logthis("Can't find $name defaulting to old $ip");
                   10201: 		    } else {
                   10202: 			&logthis("Name $name no IP found");
                   10203: 			next;
                   10204: 		    }
                   10205: 		} else {
                   10206: 		    $ip=inet_ntoa($ip);
1.847     albertel 10207: 		}
                   10208: 		$name_to_ip{$name} = $ip;
                   10209: 	    } else {
                   10210: 		$ip = $name_to_ip{$name};
1.653     albertel 10211: 	    }
1.888     albertel 10212: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10213: 		$lonid_to_ip{$id} = $ip;
                   10214: 	    }
                   10215: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10216: 	}
1.869     albertel 10217: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10218: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10219: 				      48*60*60);
1.869     albertel 10220: 
1.847     albertel 10221: 	return %iphost;
1.598     albertel 10222:     }
                   10223: 
1.992     raeburn  10224:     #
                   10225:     #  Given a DNS returns the loncapa host name for that DNS 
                   10226:     # 
                   10227:     sub host_from_dns {
                   10228:         my ($dns) = @_;
                   10229:         my @hosts;
                   10230:         my $ip;
                   10231: 
1.993     raeburn  10232:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10233:             $ip = $name_to_ip{$dns};
                   10234:         }
                   10235:         if (!$ip) {
                   10236:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10237:             if (length($ip) == 4) { 
                   10238: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10239:             }
                   10240:         }
                   10241:         if ($ip) {
                   10242: 	    @hosts = get_hosts_from_ip($ip);
                   10243: 	    return $hosts[0];
                   10244:         }
                   10245:         return undef;
1.986     foxr     10246:     }
1.992     raeburn  10247: 
1.1056.4.3  raeburn  10248:     sub get_internet_names {
                   10249:         my ($lonid) = @_;
                   10250:         return if ($lonid eq '');
                   10251:         my ($idnref,$cached)=
                   10252:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10253:         if ($cached) {
                   10254:             return $idnref;
                   10255:         }
                   10256:         my $ip = &get_host_ip($lonid);
                   10257:         my @hosts = &get_hosts_from_ip($ip);
                   10258:         my %iphost = &get_iphost();
                   10259:         my (@idns,%seen);
                   10260:         foreach my $id (@hosts) {
                   10261:             my $dom = &host_domain($id);
                   10262:             my $prim_id = &domain($dom,'primary');
                   10263:             my $prim_ip = &get_host_ip($prim_id);
                   10264:             next if ($seen{$prim_ip});
                   10265:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10266:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10267:                     my $intdom = &internet_dom($id);
                   10268:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10269:                         push(@idns,$intdom);
                   10270:                     }
                   10271:                 }
                   10272:             }
                   10273:             $seen{$prim_ip} = 1;
                   10274:         }
                   10275:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10276:     }
                   10277: 
                   10278: }
                   10279: 
                   10280: sub all_loncaparevs {
                   10281:     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);
1.986     foxr     10282: }
                   10283: 
1.862     albertel 10284: BEGIN {
                   10285: 
                   10286: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10287:     unless ($readit) {
                   10288: {
                   10289:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10290:     %perlvar = (%perlvar,%{$configvars});
                   10291: }
                   10292: 
                   10293: 
1.1       albertel 10294: # ------------------------------------------------------ Read spare server file
                   10295: {
1.448     albertel 10296:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10297: 
                   10298:     while (my $configline=<$config>) {
                   10299:        chomp($configline);
1.284     matthew  10300:        if ($configline) {
1.784     albertel 10301: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10302: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10303: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10304:        }
                   10305:     }
1.448     albertel 10306:     close($config);
1.1       albertel 10307: }
1.11      www      10308: # ------------------------------------------------------------ Read permissions
                   10309: {
1.448     albertel 10310:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10311: 
                   10312:     while (my $configline=<$config>) {
1.448     albertel 10313: 	chomp($configline);
                   10314: 	if ($configline) {
                   10315: 	    my ($role,$perm)=split(/ /,$configline);
                   10316: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10317: 	}
1.11      www      10318:     }
1.448     albertel 10319:     close($config);
1.11      www      10320: }
                   10321: 
                   10322: # -------------------------------------------- Read plain texts for permissions
                   10323: {
1.448     albertel 10324:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10325: 
                   10326:     while (my $configline=<$config>) {
1.448     albertel 10327: 	chomp($configline);
                   10328: 	if ($configline) {
1.742     raeburn  10329: 	    my ($short,@plain)=split(/:/,$configline);
                   10330:             %{$prp{$short}} = ();
                   10331: 	    if (@plain > 0) {
                   10332:                 $prp{$short}{'std'} = $plain[0];
                   10333:                 for (my $i=1; $i<@plain; $i++) {
                   10334:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10335:                 }
                   10336:             }
1.448     albertel 10337: 	}
1.135     www      10338:     }
1.448     albertel 10339:     close($config);
1.135     www      10340: }
                   10341: 
                   10342: # ---------------------------------------------------------- Read package table
                   10343: {
1.448     albertel 10344:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10345: 
                   10346:     while (my $configline=<$config>) {
1.483     albertel 10347: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10348: 	chomp($configline);
                   10349: 	my ($short,$plain)=split(/:/,$configline);
                   10350: 	my ($pack,$name)=split(/\&/,$short);
                   10351: 	if ($plain ne '') {
                   10352: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10353: 	    $packagetab{$short}=$plain; 
                   10354: 	}
1.11      www      10355:     }
1.448     albertel 10356:     close($config);
1.329     matthew  10357: }
                   10358: 
1.1056.4.3  raeburn  10359: # ---------------------------------------------------------- Read loncaparev table
                   10360: {
                   10361:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10362:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10363:             while (my $configline=<$config>) {
                   10364:                 chomp($configline);
                   10365:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10366:                 $loncaparevs{$hostid}=$loncaparev;
                   10367:             }
                   10368:             close($config);
                   10369:         }
                   10370:     }
                   10371: }
                   10372: 
                   10373: # ---------------------------------------------------------- Read serverhostID table
                   10374: {
                   10375:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10376:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10377:             while (my $configline=<$config>) {
                   10378:                 chomp($configline);
                   10379:                 my ($name,$id)=split(/:/,$configline);
                   10380:                 $serverhomeIDs{$name}=$id;
                   10381:             }
                   10382:             close($config);
                   10383:         }
                   10384:     }
                   10385: }
                   10386: 
1.1056.4.5  raeburn  10387: {
                   10388:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10389:     if (-e $file) {
                   10390:         my $parser = HTML::LCParser->new($file);
                   10391:         while (my $token = $parser->get_token()) {
                   10392:             if ($token->[0] eq 'S') {
                   10393:                 my $item = $token->[1];
                   10394:                 my $name = $token->[2]{'name'};
                   10395:                 my $value = $token->[2]{'value'};
                   10396:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10397:                     my $release = $parser->get_text();
                   10398:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10399:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10400:                 }
                   10401:             }
                   10402:         }
                   10403:     }
                   10404: }
                   10405: 
1.329     matthew  10406: # ------------- set up temporary directory
                   10407: {
                   10408:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10409: 
1.11      www      10410: }
                   10411: 
1.794     albertel 10412: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10413: 				'compress_threshold'=> 20_000,
                   10414:  			        });
1.185     www      10415: 
1.281     www      10416: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10417: $dumpcount=0;
1.958     www      10418: $locknum=0;
1.22      www      10419: 
1.163     harris41 10420: &logtouch();
1.672     albertel 10421: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10422: $readit=1;
1.564     albertel 10423:     {
                   10424: 	use integer;
                   10425: 	my $test=(2**32)+1;
1.568     albertel 10426: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10427: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10428:     }
1.195     www      10429: }
1.1       albertel 10430: }
1.179     www      10431: 
1.1       albertel 10432: 1;
1.191     harris41 10433: __END__
                   10434: 
1.243     albertel 10435: =pod
                   10436: 
1.191     harris41 10437: =head1 NAME
                   10438: 
1.243     albertel 10439: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10440: 
                   10441: =head1 SYNOPSIS
                   10442: 
1.243     albertel 10443: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10444: 
                   10445:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10446: 
1.243     albertel 10447: Common parameters:
                   10448: 
                   10449: =over 4
                   10450: 
                   10451: =item *
                   10452: 
                   10453: $uname : an internal username (if $cname expecting a course Id specifically)
                   10454: 
                   10455: =item *
                   10456: 
                   10457: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10458: 
                   10459: =item *
                   10460: 
                   10461: $symb : a resource instance identifier
                   10462: 
                   10463: =item *
                   10464: 
                   10465: $namespace : the name of a .db file that contains the data needed or
                   10466: being set.
                   10467: 
                   10468: =back
                   10469: 
1.394     bowersj2 10470: =head1 OVERVIEW
1.191     harris41 10471: 
1.394     bowersj2 10472: lonnet provides subroutines which interact with the
                   10473: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10474: about classes, users, and resources.
1.243     albertel 10475: 
                   10476: For many of these objects you can also use this to store data about
                   10477: them or modify them in various ways.
1.191     harris41 10478: 
1.394     bowersj2 10479: =head2 Symbs
1.191     harris41 10480: 
1.394     bowersj2 10481: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10482: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10483: map, the resource number of the resource in the map, and the URL of
                   10484: the resource itself. The latter is somewhat redundant, but might help
                   10485: if maps change.
                   10486: 
                   10487: An example is
                   10488: 
                   10489:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10490: 
                   10491: The respective map entry is
                   10492: 
                   10493:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10494:   title="Problem 2">
                   10495:  </resource>
                   10496: 
                   10497: Symbs are used by the random number generator, as well as to store and
                   10498: restore data specific to a certain instance of for example a problem.
                   10499: 
                   10500: =head2 Storing And Retrieving Data
                   10501: 
                   10502: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10503: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10504: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10505: is is the non-critical message twin of cstore. These functions are for
                   10506: handlers to store a perl hash to a user's permanent data space in an
                   10507: easy manner, and to retrieve it again on another call. It is expected
                   10508: that a handler would use this once at the beginning to retrieve data,
                   10509: and then again once at the end to send only the new data back.
                   10510: 
                   10511: The data is stored in the user's data directory on the user's
                   10512: homeserver under the ID of the course.
                   10513: 
                   10514: The hash that is returned by restore will have all of the previous
                   10515: value for all of the elements of the hash.
                   10516: 
                   10517: Example:
                   10518: 
                   10519:  #creating a hash
                   10520:  my %hash;
                   10521:  $hash{'foo'}='bar';
                   10522: 
                   10523:  #storing it
                   10524:  &Apache::lonnet::cstore(\%hash);
                   10525: 
                   10526:  #changing a value
                   10527:  $hash{'foo'}='notbar';
                   10528: 
                   10529:  #adding a new value
                   10530:  $hash{'bar'}='foo';
                   10531:  &Apache::lonnet::cstore(\%hash);
                   10532: 
                   10533:  #retrieving the hash
                   10534:  my %history=&Apache::lonnet::restore();
                   10535: 
                   10536:  #print the hash
                   10537:  foreach my $key (sort(keys(%history))) {
                   10538:    print("\%history{$key} = $history{$key}");
                   10539:  }
                   10540: 
                   10541: Will print out:
1.191     harris41 10542: 
1.394     bowersj2 10543:  %history{1:foo} = bar
                   10544:  %history{1:keys} = foo:timestamp
                   10545:  %history{1:timestamp} = 990455579
                   10546:  %history{2:bar} = foo
                   10547:  %history{2:foo} = notbar
                   10548:  %history{2:keys} = foo:bar:timestamp
                   10549:  %history{2:timestamp} = 990455580
                   10550:  %history{bar} = foo
                   10551:  %history{foo} = notbar
                   10552:  %history{timestamp} = 990455580
                   10553:  %history{version} = 2
                   10554: 
                   10555: Note that the special hash entries C<keys>, C<version> and
                   10556: C<timestamp> were added to the hash. C<version> will be equal to the
                   10557: total number of versions of the data that have been stored. The
                   10558: C<timestamp> attribute will be the UNIX time the hash was
                   10559: stored. C<keys> is available in every historical section to list which
                   10560: keys were added or changed at a specific historical revision of a
                   10561: hash.
                   10562: 
                   10563: B<Warning>: do not store the hash that restore returns directly. This
                   10564: will cause a mess since it will restore the historical keys as if the
                   10565: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10566: 
1.394     bowersj2 10567: Calling convention:
1.191     harris41 10568: 
1.394     bowersj2 10569:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10570:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10571: 
1.394     bowersj2 10572: For more detailed information, see lonnet specific documentation.
1.191     harris41 10573: 
1.394     bowersj2 10574: =head1 RETURN MESSAGES
1.191     harris41 10575: 
1.394     bowersj2 10576: =over 4
1.191     harris41 10577: 
1.394     bowersj2 10578: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10579: 
1.394     bowersj2 10580: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10581: when the connection is brought back up
1.191     harris41 10582: 
1.394     bowersj2 10583: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10584: for later delivery
1.191     harris41 10585: 
1.967     bisitz   10586: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10587: 
1.394     bowersj2 10588: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10589: that was requested
1.191     harris41 10590: 
1.243     albertel 10591: =back
1.191     harris41 10592: 
1.243     albertel 10593: =head1 PUBLIC SUBROUTINES
1.191     harris41 10594: 
1.243     albertel 10595: =head2 Session Environment Functions
1.191     harris41 10596: 
1.243     albertel 10597: =over 4
1.191     harris41 10598: 
1.394     bowersj2 10599: =item * 
                   10600: X<appenv()>
1.949     raeburn  10601: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10602: the user envirnoment file, and will be restored for each access this
1.620     albertel 10603: user makes during this session, also modifies the %env for the current
1.949     raeburn  10604: process. Optional rolesarrayref - if defined contains a reference to an array
                   10605: of roles which are exempt from the restriction on modifying user.role entries 
                   10606: in the user's environment.db and in %env.    
1.191     harris41 10607: 
                   10608: =item *
1.394     bowersj2 10609: X<delenv()>
1.987     raeburn  10610: B<delenv($delthis,$regexp)>: removes all items from the session
                   10611: environment file that begin with $delthis. If the 
                   10612: optional second arg - $regexp - is true, $delthis is treated as a 
                   10613: regular expression, otherwise \Q$delthis\E is used. 
                   10614: The values are also deleted from the current processes %env.
1.191     harris41 10615: 
1.795     albertel 10616: =item * get_env_multiple($name) 
                   10617: 
                   10618: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10619: values may be defined and end up as an array ref.
                   10620: 
                   10621: returns an array of values
                   10622: 
1.243     albertel 10623: =back
                   10624: 
                   10625: =head2 User Information
1.191     harris41 10626: 
1.243     albertel 10627: =over 4
1.191     harris41 10628: 
                   10629: =item *
1.394     bowersj2 10630: X<queryauthenticate()>
                   10631: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10632: authentication scheme
                   10633: 
                   10634: =item *
1.394     bowersj2 10635: X<authenticate()>
1.1056.4.3  raeburn  10636: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10637: authenticate user from domain's lib servers (first use the current
                   10638: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10639: $checkdefauth is optional (value is 1 if a check should be made to
                   10640:    authenticate user using default authentication method, and allow
                   10641:    account creation if username does not have account in the domain).
                   10642: $clientcancheckhost is optional (value is 1 if checking whether the
                   10643:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10644: 
                   10645: =item *
1.394     bowersj2 10646: X<homeserver()>
                   10647: B<homeserver($uname,$udom)>: find the server which has
                   10648: the user's directory and files (there must be only one), this caches
                   10649: the answer, and also caches if there is a borken connection.
1.191     harris41 10650: 
                   10651: =item *
1.394     bowersj2 10652: X<idget()>
                   10653: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10654: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10655: username, and only 1 username per ID in a specific domain) (returns
                   10656: hash: id=>name,id=>name)
1.191     harris41 10657: 
                   10658: =item *
1.394     bowersj2 10659: X<idrget()>
                   10660: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10661: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10662: 
                   10663: =item *
1.394     bowersj2 10664: X<idput()>
                   10665: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10666: 
                   10667: =item *
1.394     bowersj2 10668: X<rolesinit()>
                   10669: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10670: 
                   10671: =item *
1.551     albertel 10672: X<getsection()>
                   10673: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10674: course $cname, return section name/number or '' for "not in course"
                   10675: and '-1' for "no section"
                   10676: 
                   10677: =item *
1.394     bowersj2 10678: X<userenvironment()>
                   10679: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10680: passed in @what from the requested user's environment, returns a hash
                   10681: 
1.858     raeburn  10682: =item * 
                   10683: X<userlog_query()>
1.859     albertel 10684: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10685: activity.log file. %filters defines filters applied when parsing the
                   10686: log file. These can be start or end timestamps, or the type of action
                   10687: - log to look for Login or Logout events, check for Checkin or
                   10688: Checkout, role for role selection. The response is in the form
                   10689: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10690: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10691: 
1.243     albertel 10692: =back
                   10693: 
                   10694: =head2 User Roles
                   10695: 
                   10696: =over 4
                   10697: 
                   10698: =item *
                   10699: 
1.810     raeburn  10700: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10701:  F: full access
                   10702:  U,I,K: authentication modes (cxx only)
                   10703:  '': forbidden
                   10704:  1: user needs to choose course
                   10705:  2: browse allowed
1.766     albertel 10706:  A: passphrase authentication needed
1.243     albertel 10707: 
                   10708: =item *
                   10709: 
                   10710: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10711: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10712: and course level
                   10713: 
                   10714: =item *
                   10715: 
1.988     raeburn  10716: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10717: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10718: $type is Course (default) or Community.
1.988     raeburn  10719: If $forcedefault evaluates to true, text returned will be default 
                   10720: text for $type. Otherwise, if this is a course, the text returned 
                   10721: will be a custom name for the role (if defined in the course's 
                   10722: environment).  If no custom name is defined the default is returned.
                   10723:    
1.832     raeburn  10724: =item *
                   10725: 
1.935     raeburn  10726: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10727: All arguments are optional. Returns a hash of a roles, either for
                   10728: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10729: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10730: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10731: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10732: For each key, value is set to colon-separated start and end times for
                   10733: the role.  If no username and domain are specified, will default to
1.934     raeburn  10734: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10735: of role statuses (active, future or previous), roles 
                   10736: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10737: to restrict the list of roles reported. If no array ref is 
                   10738: provided for types, will default to return only active roles.
1.834     albertel 10739: 
1.243     albertel 10740: =back
                   10741: 
                   10742: =head2 User Modification
                   10743: 
                   10744: =over 4
                   10745: 
                   10746: =item *
                   10747: 
1.957     raeburn  10748: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10749: user for the level given by URL.  Optional start and end dates (leave empty
                   10750: string or zero for "no date")
1.191     harris41 10751: 
                   10752: =item *
                   10753: 
1.243     albertel 10754: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10755: change a users, password, possible return values are: ok,
                   10756: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10757: refused
1.191     harris41 10758: 
                   10759: =item *
                   10760: 
1.243     albertel 10761: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10762: 
                   10763: =item *
                   10764: 
1.1056.4.1  raeburn  10765: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10766:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10767: 
                   10768: will update user information (firstname,middlename,lastname,generation,
                   10769: permanentemail), and if forceid is true, student/employee ID also.
                   10770: A user's institutional affiliation(s) can also be updated.
                   10771: User information fields will not be overwritten with empty entries 
                   10772: unless the field is included in the $candelete array reference.
                   10773: This array is included when a single user is modified via "Manage Users",
                   10774: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10775: 
                   10776: =item *
                   10777: 
1.286     matthew  10778: modifystudent
                   10779: 
1.957     raeburn  10780: modify a student's enrollment and identification information.
1.286     matthew  10781: The course id is resolved based on the current users environment.  
                   10782: This means the envoking user must be a course coordinator or otherwise
                   10783: associated with a course.
                   10784: 
1.297     matthew  10785: This call is essentially a wrapper for lonnet::modifyuser and
                   10786: lonnet::modify_student_enrollment
1.286     matthew  10787: 
                   10788: Inputs: 
                   10789: 
                   10790: =over 4
                   10791: 
1.957     raeburn  10792: =item B<$udom> Student's loncapa domain
1.286     matthew  10793: 
1.957     raeburn  10794: =item B<$uname> Student's loncapa login name
1.286     matthew  10795: 
1.964     bisitz   10796: =item B<$uid> Student/Employee ID
1.286     matthew  10797: 
1.957     raeburn  10798: =item B<$umode> Student's authentication mode
1.286     matthew  10799: 
1.957     raeburn  10800: =item B<$upass> Student's password
1.286     matthew  10801: 
1.957     raeburn  10802: =item B<$first> Student's first name
1.286     matthew  10803: 
1.957     raeburn  10804: =item B<$middle> Student's middle name
1.286     matthew  10805: 
1.957     raeburn  10806: =item B<$last> Student's last name
1.286     matthew  10807: 
1.957     raeburn  10808: =item B<$gene> Student's generation
1.286     matthew  10809: 
1.957     raeburn  10810: =item B<$usec> Student's section in course
1.286     matthew  10811: 
                   10812: =item B<$end> Unix time of the roles expiration
                   10813: 
                   10814: =item B<$start> Unix time of the roles start date
                   10815: 
                   10816: =item B<$forceid> If defined, allow $uid to be changed
                   10817: 
                   10818: =item B<$desiredhome> server to use as home server for student
                   10819: 
1.957     raeburn  10820: =item B<$email> Student's permanent e-mail address
                   10821: 
                   10822: =item B<$type> Type of enrollment (auto or manual)
                   10823: 
1.963     raeburn  10824: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10825: 
                   10826: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10827: 
1.963     raeburn  10828: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10829: 
1.963     raeburn  10830: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10831: 
1.963     raeburn  10832: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10833: 
1.286     matthew  10834: =back
1.297     matthew  10835: 
                   10836: =item *
                   10837: 
                   10838: modify_student_enrollment
                   10839: 
                   10840: Change a students enrollment status in a class.  The environment variable
                   10841: 'role.request.course' must be defined for this function to proceed.
                   10842: 
                   10843: Inputs:
                   10844: 
                   10845: =over 4
                   10846: 
                   10847: =item $udom, students domain
                   10848: 
                   10849: =item $uname, students name
                   10850: 
                   10851: =item $uid, students user id
                   10852: 
                   10853: =item $first, students first name
                   10854: 
                   10855: =item $middle
                   10856: 
                   10857: =item $last
                   10858: 
                   10859: =item $gene
                   10860: 
                   10861: =item $usec
                   10862: 
                   10863: =item $end
                   10864: 
                   10865: =item $start
                   10866: 
1.957     raeburn  10867: =item $type
                   10868: 
                   10869: =item $locktype
                   10870: 
                   10871: =item $cid
                   10872: 
                   10873: =item $selfenroll
                   10874: 
                   10875: =item $context
                   10876: 
1.297     matthew  10877: =back
                   10878: 
1.191     harris41 10879: 
                   10880: =item *
                   10881: 
1.243     albertel 10882: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10883: custom role; give a custom role to a user for the level given by URL.  Specify
                   10884: name and domain of role author, and role name
1.191     harris41 10885: 
                   10886: =item *
                   10887: 
1.243     albertel 10888: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10889: 
                   10890: =item *
                   10891: 
1.243     albertel 10892: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10893: 
                   10894: =back
                   10895: 
                   10896: =head2 Course Infomation
                   10897: 
                   10898: =over 4
1.191     harris41 10899: 
                   10900: =item *
                   10901: 
1.631     albertel 10902: coursedescription($courseid) : returns a hash of information about the
                   10903: specified course id, including all environment settings for the
                   10904: course, the description of the course will be in the hash under the
                   10905: key 'description'
1.191     harris41 10906: 
                   10907: =item *
                   10908: 
1.624     albertel 10909: resdata($name,$domain,$type,@which) : request for current parameter
                   10910: setting for a specific $type, where $type is either 'course' or 'user',
                   10911: @what should be a list of parameters to ask about. This routine caches
                   10912: answers for 5 minutes.
1.243     albertel 10913: 
1.877     foxr     10914: =item *
                   10915: 
                   10916: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10917: data base, returning a hash that is keyed by the resource name and has
                   10918: values that are the resource value.  I believe that the timestamps and
                   10919: versions are also returned.
                   10920: 
                   10921: 
1.243     albertel 10922: =back
                   10923: 
                   10924: =head2 Course Modification
                   10925: 
                   10926: =over 4
1.191     harris41 10927: 
                   10928: =item *
                   10929: 
1.243     albertel 10930: writecoursepref($courseid,%prefs) : write preferences (environment
                   10931: database) for a course
1.191     harris41 10932: 
                   10933: =item *
                   10934: 
1.1011    raeburn  10935: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10936: 
                   10937: =item *
                   10938: 
1.1038    raeburn  10939: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10940: 
                   10941: =back
                   10942: 
                   10943: =head2 Resource Subroutines
                   10944: 
                   10945: =over 4
1.191     harris41 10946: 
                   10947: =item *
                   10948: 
1.243     albertel 10949: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10950: 
                   10951: =item *
                   10952: 
1.243     albertel 10953: repcopy($filename) : subscribes to the requested file, and attempts to
                   10954: replicate from the owning library server, Might return
1.607     raeburn  10955: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10956: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10957: resource. Expects the local filesystem pathname
                   10958: (/home/httpd/html/res/....)
                   10959: 
                   10960: =back
                   10961: 
                   10962: =head2 Resource Information
                   10963: 
                   10964: =over 4
1.191     harris41 10965: 
                   10966: =item *
                   10967: 
1.243     albertel 10968: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10969: a vairety of different possible values, $varname should be a request
                   10970: string, and the other parameters can be used to specify who and what
                   10971: one is asking about.
                   10972: 
                   10973: Possible values for $varname are environment.lastname (or other item
                   10974: from the envirnment hash), user.name (or someother aspect about the
                   10975: user), resource.0.maxtries (or some other part and parameter of a
                   10976: resource)
1.204     albertel 10977: 
                   10978: =item *
                   10979: 
1.243     albertel 10980: directcondval($number) : get current value of a condition; reads from a state
                   10981: string
1.204     albertel 10982: 
                   10983: =item *
                   10984: 
1.243     albertel 10985: condval($condidx) : value of condition index based on state
1.204     albertel 10986: 
                   10987: =item *
                   10988: 
1.243     albertel 10989: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10990: resource's metadata, $what should be either a specific key, or either
                   10991: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10992: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10993: 
                   10994: this function automatically caches all requests
1.191     harris41 10995: 
                   10996: =item *
                   10997: 
1.243     albertel 10998: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10999: network of library servers; returns file handle of where SQL and regex results
                   11000: will be stored for query
1.191     harris41 11001: 
                   11002: =item *
                   11003: 
1.243     albertel 11004: symbread($filename) : return symbolic list entry (filename argument optional);
                   11005: returns the data handle
1.191     harris41 11006: 
                   11007: =item *
                   11008: 
1.243     albertel 11009: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11010: a possible symb for the URL in $thisfn, and if is an encryypted
                   11011: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11012: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11013: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11014: 
1.191     harris41 11015: 
                   11016: =item *
                   11017: 
1.243     albertel 11018: symbclean($symb) : removes versions numbers from a symb, returns the
                   11019: cleaned symb
1.191     harris41 11020: 
                   11021: =item *
                   11022: 
1.243     albertel 11023: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11024: course map, user must be in a course for it to work.
1.191     harris41 11025: 
                   11026: =item *
                   11027: 
1.243     albertel 11028: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11029: 
                   11030: =item *
                   11031: 
1.243     albertel 11032: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11033: a random seed, all arguments are optional, if they aren't sent it uses the
                   11034: environment to derive them. Note: if symb isn't sent and it can't get one
                   11035: from &symbread it will use the current time as its return value
1.191     harris41 11036: 
                   11037: =item *
                   11038: 
1.243     albertel 11039: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11040: unfakeable, receipt
1.191     harris41 11041: 
                   11042: =item *
                   11043: 
1.620     albertel 11044: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11045: 
                   11046: =item *
                   11047: 
1.243     albertel 11048: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11049: 
                   11050: =item *
                   11051: 
1.243     albertel 11052: 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 11053: 
                   11054: =item *
                   11055: 
1.243     albertel 11056: 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 11057: 
                   11058: =item *
                   11059: 
1.243     albertel 11060: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11061: 
                   11062: =item *
                   11063: 
1.243     albertel 11064: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11065: forcing spreadsheet to reevaluate the resource scores next time.
                   11066: 
                   11067: =back
                   11068: 
                   11069: =head2 Storing/Retreiving Data
                   11070: 
                   11071: =over 4
1.191     harris41 11072: 
                   11073: =item *
                   11074: 
1.243     albertel 11075: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11076: for this url; hashref needs to be given and should be a \%hashname; the
                   11077: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11078: be derived from the env
1.191     harris41 11079: 
                   11080: =item *
                   11081: 
1.243     albertel 11082: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11083: uses critical subroutine
1.191     harris41 11084: 
                   11085: =item *
                   11086: 
1.243     albertel 11087: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11088: all args are optional
1.191     harris41 11089: 
                   11090: =item *
                   11091: 
1.717     albertel 11092: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11093: dumps the complete (or key matching regexp) namespace into a hash
                   11094: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11095: normally &store()ed into
                   11096: 
                   11097: $range should be either an integer '100' (give me the first 100
                   11098:                                            matching records)
                   11099:               or be  two integers sperated by a - with no spaces
                   11100:                  '30-50' (give me the 30th through the 50th matching
                   11101:                           records)
                   11102: 
                   11103: 
                   11104: =item *
                   11105: 
                   11106: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11107: replaces a &store() version of data with a replacement set of data
                   11108: for a particular resource in a namespace passed in the $storehash hash 
                   11109: reference
                   11110: 
                   11111: =item *
                   11112: 
1.243     albertel 11113: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11114: works very similar to store/cstore, but all data is stored in a
                   11115: temporary location and can be reset using tmpreset, $storehash should
                   11116: be a hash reference, returns nothing on success
1.191     harris41 11117: 
                   11118: =item *
                   11119: 
1.243     albertel 11120: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11121: similar to restore, but all data is stored in a temporary location and
                   11122: can be reset using tmpreset. Returns a hash of values on success,
                   11123: error string otherwise.
1.191     harris41 11124: 
                   11125: =item *
                   11126: 
1.243     albertel 11127: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11128: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11129: 
                   11130: =item *
                   11131: 
1.243     albertel 11132: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11133: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11134: 
                   11135: =item *
                   11136: 
1.243     albertel 11137: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11138: namesp ($udom and $uname are optional)
1.191     harris41 11139: 
                   11140: =item *
                   11141: 
1.702     albertel 11142: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11143: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11144: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11145: 
1.702     albertel 11146: $range should be either an integer '100' (give me the first 100
                   11147:                                            matching records)
                   11148:               or be  two integers sperated by a - with no spaces
                   11149:                  '30-50' (give me the 30th through the 50th matching
                   11150:                           records)
1.449     matthew  11151: =item *
                   11152: 
                   11153: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11154: $store can be a scalar, an array reference, or if the amount to be 
                   11155: incremented is > 1, a hash reference.
                   11156: 
                   11157: ($udom and $uname are optional)
1.191     harris41 11158: 
                   11159: =item *
                   11160: 
1.243     albertel 11161: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11162: ($udom and $uname are optional)
1.191     harris41 11163: 
                   11164: =item *
                   11165: 
1.243     albertel 11166: cput($namespace,$storehash,$udom,$uname) : critical put
                   11167: ($udom and $uname are optional)
1.191     harris41 11168: 
                   11169: =item *
                   11170: 
1.748     albertel 11171: newput($namespace,$storehash,$udom,$uname) :
                   11172: 
                   11173: Attempts to store the items in the $storehash, but only if they don't
                   11174: currently exist, if this succeeds you can be certain that you have 
                   11175: successfully created a new key value pair in the $namespace db.
                   11176: 
                   11177: 
                   11178: Args:
                   11179:  $namespace: name of database to store values to
                   11180:  $storehash: hashref to store to the db
                   11181:  $udom: (optional) domain of user containing the db
                   11182:  $uname: (optional) name of user caontaining the db
                   11183: 
                   11184: Returns:
                   11185:  'ok' -> succeeded in storing all keys of $storehash
                   11186:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11187:                         least <key> already existed in the db (other
                   11188:                         requested keys may also already exist)
1.967     bisitz   11189:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11190:  'con_lost' -> unable to contact request server
                   11191:  'refused' -> action was not allowed by remote machine
                   11192: 
                   11193: 
                   11194: =item *
                   11195: 
1.243     albertel 11196: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11197: reference filled in from namesp (encrypts the return communication)
                   11198: ($udom and $uname are optional)
1.191     harris41 11199: 
                   11200: =item *
                   11201: 
1.243     albertel 11202: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11203: critical subroutine
                   11204: 
1.806     raeburn  11205: =item *
                   11206: 
1.860     raeburn  11207: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11208: array reference filled in from namespace found in domain level on either
                   11209: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11210: 
                   11211: =item *
                   11212: 
1.860     raeburn  11213: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11214: domain level either on specified domain server ($uhome) or primary domain 
                   11215: server ($udom and $uhome are optional)
1.806     raeburn  11216: 
1.943     raeburn  11217: =item * 
                   11218: 
                   11219: get_domain_defaults($target_domain) : returns hash with defaults for
                   11220: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11221: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11222: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11223: Values are retrieved from cache (if current), or from domain's configuration.db
                   11224: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11225: or lonTabs/domain.tab. 
                   11226: 
                   11227: %domdefaults = &get_auth_defaults($target_domain);
                   11228: 
1.243     albertel 11229: =back
                   11230: 
                   11231: =head2 Network Status Functions
                   11232: 
                   11233: =over 4
1.191     harris41 11234: 
                   11235: =item *
                   11236: 
                   11237: dirlist($uri) : return directory list based on URI
                   11238: 
                   11239: =item *
                   11240: 
1.243     albertel 11241: spareserver() : find server with least workload from spare.tab
                   11242: 
1.986     foxr     11243: 
                   11244: =item *
                   11245: 
                   11246: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11247: if there is no corresponding loncapa host.
                   11248: 
1.243     albertel 11249: =back
                   11250: 
1.986     foxr     11251: 
1.243     albertel 11252: =head2 Apache Request
                   11253: 
                   11254: =over 4
1.191     harris41 11255: 
                   11256: =item *
                   11257: 
1.243     albertel 11258: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11259: localhost, posts hash
                   11260: 
                   11261: =back
                   11262: 
                   11263: =head2 Data to String to Data
                   11264: 
                   11265: =over 4
1.191     harris41 11266: 
                   11267: =item *
                   11268: 
1.243     albertel 11269: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11270: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11271: 
                   11272: =item *
                   11273: 
1.243     albertel 11274: hashref2str($hashref) : convert a hashref into a string complete with
                   11275: escaping and '=' and '&' separators, supports elements that are
                   11276: arrayrefs and hashrefs
1.191     harris41 11277: 
                   11278: =item *
                   11279: 
1.243     albertel 11280: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11281: with escaping and '&' separators, supports elements that are arrayrefs
                   11282: and hashrefs
1.191     harris41 11283: 
                   11284: =item *
                   11285: 
1.243     albertel 11286: str2hash($string) : convert string to hash using unescaping and
                   11287: splitting on '=' and '&', supports elements that are arrayrefs and
                   11288: hashrefs
1.191     harris41 11289: 
                   11290: =item *
                   11291: 
1.243     albertel 11292: str2array($string) : convert string to hash using unescaping and
                   11293: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11294: 
                   11295: =back
                   11296: 
                   11297: =head2 Logging Routines
                   11298: 
                   11299: =over 4
                   11300: 
                   11301: These routines allow one to make log messages in the lonnet.log and
                   11302: lonnet.perm logfiles.
1.191     harris41 11303: 
                   11304: =item *
                   11305: 
1.243     albertel 11306: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11307: 
                   11308: =item *
                   11309: 
1.243     albertel 11310: logthis() : append message to the normal lonnet.log file, it gets
                   11311: preiodically rolled over and deleted.
1.191     harris41 11312: 
                   11313: =item *
                   11314: 
1.243     albertel 11315: logperm() : append a permanent message to lonnet.perm.log, this log
                   11316: file never gets deleted by any automated portion of the system, only
                   11317: messages of critical importance should go in here.
                   11318: 
                   11319: =back
                   11320: 
                   11321: =head2 General File Helper Routines
                   11322: 
                   11323: =over 4
1.191     harris41 11324: 
                   11325: =item *
                   11326: 
1.481     raeburn  11327: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11328: (a) files in /uploaded
                   11329:   (i) If a local copy of the file exists - 
                   11330:       compares modification date of local copy with last-modified date for 
                   11331:       definitive version stored on home server for course. If local copy is 
                   11332:       stale, requests a new version from the home server and stores it. 
                   11333:       If the original has been removed from the home server, then local copy 
                   11334:       is unlinked.
                   11335:   (ii) If local copy does not exist -
                   11336:       requests the file from the home server and stores it. 
                   11337:   
                   11338:   If $caller is 'uploadrep':  
                   11339:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11340:     for request for files originally uploaded via DOCS. 
                   11341:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11342:   
                   11343:   Otherwise:
                   11344:      This indicates a call from the content generation phase of the request.
                   11345:      -  returns the entire contents of the file or -1.
                   11346:      
                   11347: (b) files in /res
                   11348:    - returns the entire contents of a file or -1; 
                   11349:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11350: 
1.712     albertel 11351: 
                   11352: =item *
                   11353: 
                   11354: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11355:                   reference
                   11356: 
                   11357: returns either a stat() list of data about the file or an empty list
                   11358: if the file doesn't exist or couldn't find out about it (connection
                   11359: problems or user unknown)
                   11360: 
1.191     harris41 11361: =item *
                   11362: 
1.243     albertel 11363: filelocation($dir,$file) : returns file system location of a file
                   11364: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11365: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11366: and a file of ../bob will become /a/bob)
1.191     harris41 11367: 
                   11368: =item *
                   11369: 
                   11370: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11371: filelocation except for hrefs
                   11372: 
                   11373: =item *
                   11374: 
                   11375: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11376: 
1.243     albertel 11377: =back
                   11378: 
1.608     albertel 11379: =head2 Usererfile file routines (/uploaded*)
                   11380: 
                   11381: =over 4
                   11382: 
                   11383: =item *
                   11384: 
                   11385: userfileupload(): main rotine for putting a file in a user or course's
                   11386:                   filespace, arguments are,
                   11387: 
1.620     albertel 11388:  formname - required - this is the name of the element in $env where the
1.608     albertel 11389:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11390:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11391:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 11392:  coursedoc - if true, store the file in the course of the active role
                   11393:              of the current user
                   11394:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11395:          if undefined, it will be placed in "unknown"
                   11396: 
                   11397:  (This routine calls clean_filename() to remove any dangerous
                   11398:  characters from the filename, and then calls finuserfileupload() to
                   11399:  complete the transaction)
                   11400: 
                   11401:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11402:  and /adm/notfound.html if unsuccessful
                   11403: 
                   11404: =item *
                   11405: 
                   11406: clean_filename(): routine for cleaing a filename up for storage in
                   11407:                  userfile space, argument is:
                   11408: 
                   11409:  filename - proposed filename
                   11410: 
                   11411: returns: the new clean filename
                   11412: 
                   11413: =item *
                   11414: 
                   11415: finishuserfileupload(): routine that creaes and sends the file to
                   11416: userspace, probably shouldn't be called directly
                   11417: 
                   11418:   docuname: username or courseid of destination for the file
                   11419:   docudom: domain of user/course of destination for the file
                   11420:   formname: same as for userfileupload()
                   11421:   fname: filename (inculding subdirectories) for the file
                   11422: 
                   11423:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11424:  and /adm/notfound.html if unsuccessful
                   11425: 
                   11426: =item *
                   11427: 
                   11428: renameuserfile(): renames an existing userfile to a new name
                   11429: 
                   11430:   Args:
                   11431:    docuname: username or courseid of destination for the file
                   11432:    docudom: domain of user/course of destination for the file
                   11433:    old: current file name (including any subdirs under userfiles)
                   11434:    new: desired file name (including any subdirs under userfiles)
                   11435: 
                   11436: =item *
                   11437: 
                   11438: mkdiruserfile(): creates a directory is a userfiles dir
                   11439: 
                   11440:   Args:
                   11441:    docuname: username or courseid of destination for the file
                   11442:    docudom: domain of user/course of destination for the file
                   11443:    dir: dir to create (including any subdirs under userfiles)
                   11444: 
                   11445: =item *
                   11446: 
                   11447: removeuserfile(): removes a file that exists in userfiles
                   11448: 
                   11449:   Args:
                   11450:    docuname: username or courseid of destination for the file
                   11451:    docudom: domain of user/course of destination for the file
                   11452:    fname: filname to delete (including any subdirs under userfiles)
                   11453: 
                   11454: =item *
                   11455: 
                   11456: removeuploadedurl(): convience function for removeuserfile()
                   11457: 
                   11458:   Args:
                   11459:    url:  a full /uploaded/... url to delete
                   11460: 
1.747     albertel 11461: =item * 
                   11462: 
                   11463: get_portfile_permissions():
                   11464:   Args:
                   11465:     domain: domain of user or course contain the portfolio files
                   11466:     user: name of user or num of course contain the portfolio files
                   11467:   Returns:
                   11468:     hashref of a dump of the proper file_permissions.db
                   11469:    
                   11470: 
                   11471: =item * 
                   11472: 
                   11473: get_access_controls():
                   11474: 
                   11475: Args:
                   11476:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11477:   group: (optional) the group you want the files associated with
                   11478:   file: (optional) the file you want access info on
                   11479: 
                   11480: Returns:
1.749     raeburn  11481:     a hash (keys are file names) of hashes containing
                   11482:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11483:         values are XML containing access control settings (see below) 
1.747     albertel 11484: 
                   11485: Internal notes:
                   11486: 
1.749     raeburn  11487:  access controls are stored in file_permissions.db as key=value pairs.
                   11488:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11489:         where scope -> public,guest,course,group,domains or users.
                   11490:               end -> UNIX time for end of access (0 -> no end date)
                   11491:               start -> UNIX time for start of access
                   11492: 
                   11493:     value -> XML description of access control
                   11494:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11495:             <start></start>
                   11496:             <end></end>
                   11497: 
                   11498:             <password></password>  for scope type = guest
                   11499: 
                   11500:             <domain></domain>     for scope type = course or group
                   11501:             <number></number>
                   11502:             <roles id="">
                   11503:              <role></role>
                   11504:              <access></access>
                   11505:              <section></section>
                   11506:              <group></group>
                   11507:             </roles>
                   11508: 
                   11509:             <dom></dom>         for scope type = domains
                   11510: 
                   11511:             <users>             for scope type = users
                   11512:              <user>
                   11513:               <uname></uname>
                   11514:               <udom></udom>
                   11515:              </user>
                   11516:             </users>
                   11517:            </scope> 
                   11518:               
                   11519:  Access data is also aggregated for each file in an additional key=value pair:
                   11520:  key -> path to file/file_name\0accesscontrol 
                   11521:  value -> reference to hash
                   11522:           hash contains key = value pairs
                   11523:           where key = uniqueID:scope_end_start
                   11524:                 value = UNIX time record was last updated
                   11525: 
                   11526:           Used to improve speed of look-ups of access controls for each file.  
                   11527:  
                   11528:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11529: 
                   11530: modify_access_controls():
                   11531: 
                   11532: Modifies access controls for a portfolio file
                   11533: Args
                   11534: 1. file name
                   11535: 2. reference to hash of required changes,
                   11536: 3. domain
                   11537: 4. username
                   11538:   where domain,username are the domain of the portfolio owner 
                   11539:   (either a user or a course) 
                   11540: 
                   11541: Returns:
                   11542: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11543: 2. result of deletions ('ok' or 'error', with error message).
                   11544: 3. reference to hash of any new or updated access controls.
                   11545: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11546:    key = integer (inbound ID)
                   11547:    value = uniqueID  
1.747     albertel 11548: 
1.608     albertel 11549: =back
                   11550: 
1.243     albertel 11551: =head2 HTTP Helper Routines
                   11552: 
                   11553: =over 4
                   11554: 
1.191     harris41 11555: =item *
                   11556: 
                   11557: escape() : unpack non-word characters into CGI-compatible hex codes
                   11558: 
                   11559: =item *
                   11560: 
                   11561: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11562: 
1.243     albertel 11563: =back
                   11564: 
                   11565: =head1 PRIVATE SUBROUTINES
                   11566: 
                   11567: =head2 Underlying communication routines (Shouldn't call)
                   11568: 
                   11569: =over 4
                   11570: 
                   11571: =item *
                   11572: 
                   11573: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11574: 
                   11575: =item *
                   11576: 
                   11577: reply() : uses subreply to send a message to remote machine, logs all failures
                   11578: 
                   11579: =item *
                   11580: 
                   11581: critical() : passes a critical message to another server; if cannot
                   11582: get through then place message in connection buffer directory and
                   11583: returns con_delayed, if incapable of saving message, returns
                   11584: con_failed
                   11585: 
                   11586: =item *
                   11587: 
                   11588: reconlonc() : tries to reconnect lonc client processes.
                   11589: 
                   11590: =back
                   11591: 
                   11592: =head2 Resource Access Logging
                   11593: 
                   11594: =over 4
                   11595: 
                   11596: =item *
                   11597: 
                   11598: flushcourselogs() : flush (save) buffer logs and access logs
                   11599: 
                   11600: =item *
                   11601: 
                   11602: courselog($what) : save message for course in hash
                   11603: 
                   11604: =item *
                   11605: 
                   11606: courseacclog($what) : save message for course using &courselog().  Perform
                   11607: special processing for specific resource types (problems, exams, quizzes, etc).
                   11608: 
1.191     harris41 11609: =item *
                   11610: 
                   11611: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11612: as a PerlChildExitHandler
1.243     albertel 11613: 
                   11614: =back
                   11615: 
                   11616: =head2 Other
                   11617: 
                   11618: =over 4
                   11619: 
                   11620: =item *
                   11621: 
                   11622: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11623: 
                   11624: =back
                   11625: 
                   11626: =cut
1.877     foxr     11627: 

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