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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.12! raeburn     4: # $Id: lonnet.pm,v 1.1056.4.11 2010/10/01 14:26:07 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.1056.4.10  raeburn  1760:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1761:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1762:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1763:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1764:         my $section=$1;
                   1765:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1766:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1767:         my $now=time;
1.548     albertel 1768:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1769:             $Expired{$end}=$section;
                   1770:             next;
                   1771:         }
1.548     albertel 1772:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1773:             $Pending{$start}=$section;
                   1774:             next;
                   1775:         }
1.599     albertel 1776:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1777:     }
                   1778:     #
                   1779:     # Presumedly there will be few matching roles from the above
                   1780:     # loop and the sorting time will be negligible.
                   1781:     if (scalar(keys(%Pending))) {
                   1782:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1783:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1784:     } 
                   1785:     if (scalar(keys(%Expired))) {
                   1786:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1787:         my $time = pop(@sorted);
1.599     albertel 1788:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1789:     }
1.599     albertel 1790:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1791: }
1.70      www      1792: 
1.599     albertel 1793: sub save_cache {
                   1794:     &purge_remembered();
1.722     albertel 1795:     #&Apache::loncommon::validate_page();
1.620     albertel 1796:     undef(%env);
1.780     albertel 1797:     undef($env_loaded);
1.599     albertel 1798: }
1.452     albertel 1799: 
1.599     albertel 1800: my $to_remember=-1;
                   1801: my %remembered;
                   1802: my %accessed;
                   1803: my $kicks=0;
                   1804: my $hits=0;
1.849     albertel 1805: sub make_key {
                   1806:     my ($name,$id) = @_;
1.872     albertel 1807:     if (length($id) > 65 
                   1808: 	&& length(&escape($id)) > 200) {
                   1809: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1810:     }
1.849     albertel 1811:     return &escape($name.':'.$id);
                   1812: }
                   1813: 
1.599     albertel 1814: sub devalidate_cache_new {
                   1815:     my ($name,$id,$debug) = @_;
                   1816:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1817:     $id=&make_key($name,$id);
1.599     albertel 1818:     $memcache->delete($id);
                   1819:     delete($remembered{$id});
                   1820:     delete($accessed{$id});
                   1821: }
                   1822: 
                   1823: sub is_cached_new {
                   1824:     my ($name,$id,$debug) = @_;
1.849     albertel 1825:     $id=&make_key($name,$id);
1.599     albertel 1826:     if (exists($remembered{$id})) {
                   1827: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1828: 	$accessed{$id}=[&gettimeofday()];
                   1829: 	$hits++;
                   1830: 	return ($remembered{$id},1);
                   1831:     }
                   1832:     my $value = $memcache->get($id);
                   1833:     if (!(defined($value))) {
                   1834: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1835: 	return (undef,undef);
1.416     albertel 1836:     }
1.599     albertel 1837:     if ($value eq '__undef__') {
                   1838: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1839: 	$value=undef;
                   1840:     }
                   1841:     &make_room($id,$value,$debug);
                   1842:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1843:     return ($value,1);
                   1844: }
                   1845: 
                   1846: sub do_cache_new {
                   1847:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1848:     $id=&make_key($name,$id);
1.599     albertel 1849:     my $setvalue=$value;
                   1850:     if (!defined($setvalue)) {
                   1851: 	$setvalue='__undef__';
                   1852:     }
1.623     albertel 1853:     if (!defined($time) ) {
                   1854: 	$time=600;
                   1855:     }
1.599     albertel 1856:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1857:     my $result = $memcache->set($id,$setvalue,$time);
                   1858:     if (! $result) {
1.872     albertel 1859: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1860: 	$memcache->disconnect_all();
1.872     albertel 1861:     }
1.600     albertel 1862:     # need to make a copy of $value
1.919     albertel 1863:     &make_room($id,$value,$debug);
1.599     albertel 1864:     return $value;
                   1865: }
                   1866: 
                   1867: sub make_room {
                   1868:     my ($id,$value,$debug)=@_;
1.919     albertel 1869: 
                   1870:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1871:                                     : $value;
1.599     albertel 1872:     if ($to_remember<0) { return; }
                   1873:     $accessed{$id}=[&gettimeofday()];
                   1874:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1875:     my $to_kick;
                   1876:     my $max_time=0;
                   1877:     foreach my $other (keys(%accessed)) {
                   1878: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1879: 	    $to_kick=$other;
                   1880: 	    $max_time=&tv_interval($accessed{$other});
                   1881: 	}
                   1882:     }
                   1883:     delete($remembered{$to_kick});
                   1884:     delete($accessed{$to_kick});
                   1885:     $kicks++;
                   1886:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1887:     return;
                   1888: }
                   1889: 
1.599     albertel 1890: sub purge_remembered {
1.604     albertel 1891:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1892:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1893:     undef(%remembered);
                   1894:     undef(%accessed);
1.428     albertel 1895: }
1.70      www      1896: # ------------------------------------- Read an entry from a user's environment
                   1897: 
                   1898: sub userenvironment {
                   1899:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1900:     my $items;
                   1901:     foreach my $item (@what) {
                   1902:         $items.=&escape($item).'&';
                   1903:     }
                   1904:     $items=~s/\&$//;
1.70      www      1905:     my %returnhash=();
1.1009    raeburn  1906:     my $uhome = &homeserver($unam,$udom);
                   1907:     unless ($uhome eq 'no_host') {
                   1908:         my @answer=split(/\&/, 
                   1909:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1910:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1911:             return %returnhash;
                   1912:         }
1.1009    raeburn  1913:         my $i;
                   1914:         for ($i=0;$i<=$#what;$i++) {
                   1915: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1916:         }
1.70      www      1917:     }
                   1918:     return %returnhash;
1.1       albertel 1919: }
                   1920: 
1.617     albertel 1921: # ---------------------------------------------------------- Get a studentphoto
                   1922: sub studentphoto {
                   1923:     my ($udom,$unam,$ext) = @_;
                   1924:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1925:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1926:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1927:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1928:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1929:             } else {
                   1930:                 my ($result,$perm_reqd)=
1.707     albertel 1931: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1932:                 if ($result eq 'ok') {
                   1933:                     if (!($perm_reqd eq 'yes')) {
                   1934:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1935:                     }
                   1936:                 }
                   1937:             }
                   1938:         }
                   1939:     } else {
                   1940:         my ($result,$perm_reqd) = 
1.707     albertel 1941: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1942:         if ($result eq 'ok') {
                   1943:             if (!($perm_reqd eq 'yes')) {
                   1944:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1945:             }
                   1946:         }
                   1947:     }
                   1948:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1949: }
                   1950: 
                   1951: sub retrievestudentphoto {
                   1952:     my ($udom,$unam,$ext,$type) = @_;
                   1953:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1954:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1955:     if ($ret eq 'ok') {
                   1956:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1957:         if ($type eq 'thumbnail') {
                   1958:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1959:         }
                   1960:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1961:         return $tokenurl;
                   1962:     } else {
                   1963:         if ($type eq 'thumbnail') {
                   1964:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1965:         } else { 
                   1966:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1967:         }
1.617     albertel 1968:     }
                   1969: }
                   1970: 
1.263     www      1971: # -------------------------------------------------------------------- New chat
                   1972: 
                   1973: sub chatsend {
1.724     raeburn  1974:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1975:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1976:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1977:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1978:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1979: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1980: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1981: }
                   1982: 
                   1983: # ------------------------------------------ Find current version of a resource
                   1984: 
                   1985: sub getversion {
                   1986:     my $fname=&clutter(shift);
                   1987:     unless ($fname=~/^\/res\//) { return -1; }
                   1988:     return &currentversion(&filelocation('',$fname));
                   1989: }
                   1990: 
                   1991: sub currentversion {
                   1992:     my $fname=shift;
1.599     albertel 1993:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1994:     if (defined($cached)) { return $result; }
1.292     www      1995:     my $author=$fname;
                   1996:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1997:     my ($udom,$uname)=split(/\//,$author);
                   1998:     my $home=homeserver($uname,$udom);
                   1999:     if ($home eq 'no_host') { 
                   2000:         return -1; 
                   2001:     }
                   2002:     my $answer=reply("currentversion:$fname",$home);
                   2003:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2004: 	return -1;
                   2005:     }
1.599     albertel 2006:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      2007: }
                   2008: 
1.1       albertel 2009: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2010: 
1.1       albertel 2011: sub subscribe {
                   2012:     my $fname=shift;
1.761     raeburn  2013:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2014:     $fname=~s/[\n\r]//g;
1.1       albertel 2015:     my $author=$fname;
                   2016:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2017:     my ($udom,$uname)=split(/\//,$author);
                   2018:     my $home=homeserver($uname,$udom);
1.335     albertel 2019:     if ($home eq 'no_host') {
                   2020:         return 'not_found';
1.1       albertel 2021:     }
                   2022:     my $answer=reply("sub:$fname",$home);
1.64      www      2023:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2024: 	$answer.=' by '.$home;
                   2025:     }
1.1       albertel 2026:     return $answer;
                   2027: }
                   2028:     
1.8       www      2029: # -------------------------------------------------------------- Replicate file
                   2030: 
                   2031: sub repcopy {
                   2032:     my $filename=shift;
1.23      www      2033:     $filename=~s/\/+/\//g;
1.607     raeburn  2034:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2035:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2036:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2037: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2038: 	return &repcopy_userfile($filename);
                   2039:     }
1.532     albertel 2040:     $filename=~s/[\n\r]//g;
1.8       www      2041:     my $transname="$filename.in.transfer";
1.828     www      2042: # FIXME: this should flock
1.607     raeburn  2043:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2044:     my $remoteurl=subscribe($filename);
1.64      www      2045:     if ($remoteurl =~ /^con_lost by/) {
                   2046: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2047:            return 'unavailable';
1.8       www      2048:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2049: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2050: 	   return 'not_found';
1.64      www      2051:     } elsif ($remoteurl =~ /^rejected by/) {
                   2052: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2053:            return 'forbidden';
1.20      www      2054:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2055:            return 'ok';
1.8       www      2056:     } else {
1.290     www      2057:         my $author=$filename;
                   2058:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2059:         my ($udom,$uname)=split(/\//,$author);
                   2060:         my $home=homeserver($uname,$udom);
                   2061:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2062:            my @parts=split(/\//,$filename);
                   2063:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2064:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2065:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2066: 	       return 'bad_request';
1.8       www      2067:            }
                   2068:            my $count;
                   2069:            for ($count=5;$count<$#parts;$count++) {
                   2070:                $path.="/$parts[$count]";
                   2071:                if ((-e $path)!=1) {
                   2072: 		   mkdir($path,0777);
                   2073:                }
                   2074:            }
                   2075:            my $ua=new LWP::UserAgent;
                   2076:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2077:            my $response=$ua->request($request,$transname);
                   2078:            if ($response->is_error()) {
                   2079: 	       unlink($transname);
                   2080:                my $message=$response->status_line;
1.672     albertel 2081:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2082:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2083:                return 'unavailable';
1.8       www      2084:            } else {
1.16      www      2085: 	       if ($remoteurl!~/\.meta$/) {
                   2086:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2087:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2088:                   if ($mresponse->is_error()) {
                   2089: 		      unlink($filename.'.meta');
                   2090:                       &logthis(
1.672     albertel 2091:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2092:                   }
                   2093: 	       }
1.8       www      2094:                rename($transname,$filename);
1.607     raeburn  2095:                return 'ok';
1.8       www      2096:            }
1.290     www      2097:        }
1.8       www      2098:     }
1.330     www      2099: }
                   2100: 
                   2101: # ------------------------------------------------ Get server side include body
                   2102: sub ssi_body {
1.381     albertel 2103:     my ($filelink,%form)=@_;
1.606     matthew  2104:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2105:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2106:     }
1.953     www      2107:     my $output='';
                   2108:     my $response;
1.980     raeburn  2109:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2110:        ($output,$response)=&externalssi($filelink);
1.953     www      2111:     } else {
1.1004    droeschl 2112:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2113:        $filelink .= 'inhibitmenu=yes';
1.953     www      2114:        ($output,$response)=&ssi($filelink,%form);
                   2115:     }
1.778     albertel 2116:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2117:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2118:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2119:     if (wantarray) {
                   2120:         return ($output, $response);
                   2121:     } else {
                   2122:         return $output;
                   2123:     }
1.8       www      2124: }
                   2125: 
1.15      www      2126: # --------------------------------------------------------- Server Side Include
                   2127: 
1.782     albertel 2128: sub absolute_url {
                   2129:     my ($host_name) = @_;
                   2130:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2131:     if ($host_name eq '') {
                   2132: 	$host_name = $ENV{'SERVER_NAME'};
                   2133:     }
                   2134:     return $protocol.$host_name;
                   2135: }
                   2136: 
1.942     foxr     2137: #
                   2138: #   Server side include.
                   2139: # Parameters:
                   2140: #  fn     Possibly encrypted resource name/id.
                   2141: #  form   Hash that describes how the rendering should be done
                   2142: #         and other things.
1.944     foxr     2143: # Returns:
1.950     raeburn  2144: #   Scalar context: The content of the response.
                   2145: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2146: #     
1.15      www      2147: sub ssi {
                   2148: 
1.944     foxr     2149:     my ($fn,%form)=@_;
1.15      www      2150:     my $ua=new LWP::UserAgent;
1.23      www      2151:     my $request;
1.711     albertel 2152: 
                   2153:     $form{'no_update_last_known'}=1;
1.895     albertel 2154:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2155:     if (%form) {
1.782     albertel 2156:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2157:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2158:     } else {
1.782     albertel 2159:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2160:     }
                   2161: 
1.15      www      2162:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2163:     my $response=$ua->request($request);
                   2164: 
1.944     foxr     2165:     if (wantarray) {
                   2166: 	return ($response->content, $response);
                   2167:     } else {
                   2168: 	return $response->content;
1.942     foxr     2169:     }
1.324     www      2170: }
                   2171: 
                   2172: sub externalssi {
                   2173:     my ($url)=@_;
                   2174:     my $ua=new LWP::UserAgent;
                   2175:     my $request=new HTTP::Request('GET',$url);
                   2176:     my $response=$ua->request($request);
1.954     raeburn  2177:     if (wantarray) {
                   2178:         return ($response->content, $response);
                   2179:     } else {
                   2180:         return $response->content;
                   2181:     }
1.15      www      2182: }
1.254     www      2183: 
1.492     albertel 2184: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2185: 
                   2186: sub allowuploaded {
                   2187:     my ($srcurl,$url)=@_;
                   2188:     $url=&clutter(&declutter($url));
                   2189:     my $dir=$url;
                   2190:     $dir=~s/\/[^\/]+$//;
                   2191:     my %httpref=();
                   2192:     my $httpurl=&hreflocation('',$url);
                   2193:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2194:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2195: }
1.477     raeburn  2196: 
1.478     albertel 2197: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2198: # input: action, courseID, current domain, intended
1.637     raeburn  2199: #        path to file, source of file, instruction to parse file for objects,
                   2200: #        ref to hash for embedded objects,
                   2201: #        ref to hash for codebase of java objects.
                   2202: #
1.485     raeburn  2203: # output: url to file (if action was uploaddoc), 
                   2204: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2205: #
1.478     albertel 2206: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2207: # course.
1.477     raeburn  2208: #
1.478     albertel 2209: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2210: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2211: #          course's home server.
1.477     raeburn  2212: #
1.478     albertel 2213: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2214: #          be copied from $source (current location) to 
                   2215: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2216: #         and will then be copied to
                   2217: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2218: #         course's home server.
1.485     raeburn  2219: #
1.481     raeburn  2220: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2221: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2222: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2223: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2224: #         in course's home server.
1.637     raeburn  2225: #
1.477     raeburn  2226: 
                   2227: sub process_coursefile {
1.638     albertel 2228:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2229:     my $fetchresult;
1.638     albertel 2230:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2231:     if ($action eq 'propagate') {
1.638     albertel 2232:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2233: 			     $home);
1.481     raeburn  2234:     } else {
1.477     raeburn  2235:         my $fpath = '';
                   2236:         my $fname = $file;
1.478     albertel 2237:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2238:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2239:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2240:         if ($action eq 'copy') {
                   2241:             if ($source eq '') {
                   2242:                 $fetchresult = 'no source file';
                   2243:                 return $fetchresult;
                   2244:             } else {
                   2245:                 my $destination = $filepath.'/'.$fname;
                   2246:                 rename($source,$destination);
                   2247:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2248:                                  $home);
1.481     raeburn  2249:             }
                   2250:         } elsif ($action eq 'uploaddoc') {
                   2251:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2252:             print $fh $env{'form.'.$source};
1.481     raeburn  2253:             close($fh);
1.637     raeburn  2254:             if ($parser eq 'parse') {
1.1024    raeburn  2255:                 my $mm = new File::MMagic;
                   2256:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2257:                 if ($mime_type eq 'text/html') {
                   2258:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2259:                     unless ($parse_result eq 'ok') {
                   2260:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2261:                     }
1.637     raeburn  2262:                 }
                   2263:             }
1.477     raeburn  2264:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2265:                                  $home);
1.481     raeburn  2266:             if ($fetchresult eq 'ok') {
                   2267:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2268:             } else {
                   2269:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2270:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2271:                 return '/adm/notfound.html';
                   2272:             }
1.477     raeburn  2273:         }
                   2274:     }
1.485     raeburn  2275:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2276:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2277:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2278:     }
                   2279:     return $fetchresult;
                   2280: }
                   2281: 
1.637     raeburn  2282: sub build_filepath {
                   2283:     my ($fpath) = @_;
                   2284:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2285:     unless ($fpath eq '') {
                   2286:         my @parts=split('/',$fpath);
                   2287:         foreach my $part (@parts) {
                   2288:             $filepath.= '/'.$part;
                   2289:             if ((-e $filepath)!=1) {
                   2290:                 mkdir($filepath,0777);
                   2291:             }
                   2292:         }
                   2293:     }
                   2294:     return $filepath;
                   2295: }
                   2296: 
                   2297: sub store_edited_file {
1.638     albertel 2298:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2299:     my $file = $primary_url;
                   2300:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2301:     my $fpath = '';
                   2302:     my $fname = $file;
                   2303:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2304:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2305:     my $filepath = &build_filepath($fpath);
                   2306:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2307:     print $fh $content;
                   2308:     close($fh);
1.638     albertel 2309:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2310:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2311: 			  $home);
1.637     raeburn  2312:     if ($$fetchresult eq 'ok') {
                   2313:         return '/uploaded/'.$fpath.'/'.$fname;
                   2314:     } else {
1.638     albertel 2315:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2316: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2317:         return '/adm/notfound.html';
                   2318:     }
                   2319: }
                   2320: 
1.531     albertel 2321: sub clean_filename {
1.831     albertel 2322:     my ($fname,$args)=@_;
1.315     www      2323: # Replace Windows backslashes by forward slashes
1.257     www      2324:     $fname=~s/\\/\//g;
1.831     albertel 2325:     if (!$args->{'keep_path'}) {
                   2326:         # Get rid of everything but the actual filename
                   2327: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2328:     }
1.315     www      2329: # Replace spaces by underscores
                   2330:     $fname=~s/\s+/\_/g;
                   2331: # Replace all other weird characters by nothing
1.831     albertel 2332:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2333: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2334: # numbers
                   2335:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2336:     return $fname;
                   2337: }
1.1051    raeburn  2338: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2339: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2340: # image with the same aspect ratio as the original, but with dimensions which do 
                   2341: # not exceed $resizewidth and $resizeheight.
                   2342:  
1.984     neumanie 2343: sub resizeImage {
1.1051    raeburn  2344:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2345:     my $ima = Image::Magick->new;
                   2346:     my $resized;
                   2347:     if (-e $img_path) {
                   2348:         $ima->Read($img_path);
                   2349:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2350:             my $width = $ima->Get('width');
                   2351:             my $height = $ima->Get('height');
                   2352:             if ($width > $resizewidth) {
                   2353: 	        my $factor = $width/$resizewidth;
                   2354:                 my $newheight = $height/$factor;
                   2355:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2356:                 $resized = 1;
                   2357:             }
                   2358:         }
                   2359:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2360:             my $width = $ima->Get('width');
                   2361:             my $height = $ima->Get('height');
                   2362:             if ($height > $resizeheight) {
                   2363:                 my $factor = $height/$resizeheight;
                   2364:                 my $newwidth = $width/$factor;
                   2365:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2366:                 $resized = 1;
                   2367:             }
                   2368:         }
                   2369:         if ($resized) {
                   2370:             $ima->Write($img_path);
                   2371:         }
                   2372:     }
                   2373:     return;
1.977     amueller 2374: }
                   2375: 
1.608     albertel 2376: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2377: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2378: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2379: #        $coursedoc - if true up to the current course
                   2380: #                     if false
                   2381: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2382: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2383: #        $allfiles - reference to hash for embedded objects
                   2384: #        $codebase - reference to hash for codebase of java objects
                   2385: #        $desuname - username for permanent storage of uploaded file
                   2386: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2387: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2388: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2389: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2390: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2391: # 
1.686     albertel 2392: # output: url of file in userspace, or error: <message> 
                   2393: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2394: 
1.531     albertel 2395: sub userfileupload {
1.860     raeburn  2396:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2397:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2398:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2399:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2400:     $fname=&clean_filename($fname);
1.315     www      2401: # See if there is anything left
1.257     www      2402:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2403:     chop($env{'form.'.$formname});
1.523     raeburn  2404:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2405:         my $now = time;
                   2406:         my $filepath = 'tmp/helprequests/'.$now;
                   2407:         my @parts=split(/\//,$filepath);
                   2408:         my $fullpath = $perlvar{'lonDaemons'};
                   2409:         for (my $i=0;$i<@parts;$i++) {
                   2410:             $fullpath .= '/'.$parts[$i];
                   2411:             if ((-e $fullpath)!=1) {
                   2412:                 mkdir($fullpath,0777);
                   2413:             }
                   2414:         }
                   2415:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2416:         print $fh $env{'form.'.$formname};
1.523     raeburn  2417:         close($fh);
1.741     raeburn  2418:         return $fullpath.'/'.$fname;
                   2419:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2420:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2421:                        '_'.$env{'user.domain'}.'/pending';
                   2422:         my @parts=split(/\//,$filepath);
                   2423:         my $fullpath = $perlvar{'lonDaemons'};
                   2424:         for (my $i=0;$i<@parts;$i++) {
                   2425:             $fullpath .= '/'.$parts[$i];
                   2426:             if ((-e $fullpath)!=1) {
                   2427:                 mkdir($fullpath,0777);
                   2428:             }
                   2429:         }
                   2430:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2431:         print $fh $env{'form.'.$formname};
                   2432:         close($fh);
                   2433:         return $fullpath.'/'.$fname;
1.523     raeburn  2434:     }
1.995     raeburn  2435:     if ($subdir eq 'scantron') {
                   2436:         $fname = 'scantron_orig_'.$fname;
                   2437:     } else {   
1.258     www      2438: # Create the directory if not present
1.995     raeburn  2439:         $fname="$subdir/$fname";
                   2440:     }
1.259     www      2441:     if ($coursedoc) {
1.638     albertel 2442: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2443: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2444:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2445:             return &finishuserfileupload($docuname,$docudom,
                   2446: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2447: 					 $codebase,$thumbwidth,$thumbheight,
                   2448:                                          $resizewidth,$resizeheight);
1.481     raeburn  2449:         } else {
1.620     albertel 2450:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2451:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2452: 				       $fname,$formname,$parser,
                   2453: 				       $allfiles,$codebase);
1.481     raeburn  2454:         }
1.719     banghart 2455:     } elsif (defined($destuname)) {
                   2456:         my $docuname=$destuname;
                   2457:         my $docudom=$destudom;
1.860     raeburn  2458: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2459: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2460:                                      $thumbwidth,$thumbheight,
                   2461:                                      $resizewidth,$resizeheight);
1.719     banghart 2462:         
1.259     www      2463:     } else {
1.638     albertel 2464:         my $docuname=$env{'user.name'};
                   2465:         my $docudom=$env{'user.domain'};
1.714     raeburn  2466:         if (exists($env{'form.group'})) {
                   2467:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2468:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2469:         }
1.860     raeburn  2470: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2471: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2472:                                      $thumbwidth,$thumbheight,
                   2473:                                      $resizewidth,$resizeheight);
1.259     www      2474:     }
1.271     www      2475: }
                   2476: 
                   2477: sub finishuserfileupload {
1.860     raeburn  2478:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051    raeburn  2479:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477     raeburn  2480:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2481:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2482:   
1.860     raeburn  2483:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2484:     $file=$fname;
                   2485:     if ($fname=~m|/|) {
                   2486:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2487: 	$path.=$fnamepath.'/';
                   2488:     }
1.259     www      2489:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2490:     my $count;
                   2491:     for ($count=4;$count<=$#parts;$count++) {
                   2492:         $filepath.="/$parts[$count]";
                   2493:         if ((-e $filepath)!=1) {
                   2494: 	    mkdir($filepath,0777);
                   2495:         }
                   2496:     }
1.984     neumanie 2497: 
1.258     www      2498: # Save the file
                   2499:     {
1.701     albertel 2500: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2501: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2502: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2503: 	    return '/adm/notfound.html';
                   2504: 	}
                   2505: 	if (!print FH ($env{'form.'.$formname})) {
                   2506: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2507: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2508: 	    return '/adm/notfound.html';
                   2509: 	}
1.570     albertel 2510: 	close(FH);
1.1051    raeburn  2511:         if ($resizewidth && $resizeheight) {
                   2512:             my $mm = new File::MMagic;
                   2513:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2514:             if ($mime_type =~ m{^image/}) {
                   2515: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2516:             }  
1.977     amueller 2517: 	}
1.258     www      2518:     }
1.637     raeburn  2519:     if ($parser eq 'parse') {
1.1024    raeburn  2520:         my $mm = new File::MMagic;
                   2521:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2522:         if ($mime_type eq 'text/html') {
                   2523:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2524:                                                        $allfiles,$codebase);
                   2525:             unless ($parse_result eq 'ok') {
                   2526:                 &logthis('Failed to parse '.$filepath.$file.
                   2527: 	   	         ' for embedded media: '.$parse_result); 
                   2528:             }
1.637     raeburn  2529:         }
                   2530:     }
1.860     raeburn  2531:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2532:         my $input = $filepath.'/'.$file;
                   2533:         my $output = $filepath.'/'.'tn-'.$file;
                   2534:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2535:         system("convert -sample $thumbsize $input $output");
                   2536:         if (-e $filepath.'/'.'tn-'.$file) {
                   2537:             $fetchthumb  = 1; 
                   2538:         }
                   2539:     }
1.858     raeburn  2540:  
1.259     www      2541: # Notify homeserver to grep it
                   2542: #
1.984     neumanie 2543:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2544:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2545:     if ($fetchresult eq 'ok') {
1.860     raeburn  2546:         if ($fetchthumb) {
                   2547:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2548:             if ($thumbresult ne 'ok') {
                   2549:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2550:                          $docuhome.': '.$thumbresult);
                   2551:             }
                   2552:         }
1.259     www      2553: #
1.258     www      2554: # Return the URL to it
1.494     albertel 2555:         return '/uploaded/'.$path.$file;
1.263     www      2556:     } else {
1.494     albertel 2557:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2558: 		 ': '.$fetchresult);
1.263     www      2559:         return '/adm/notfound.html';
1.858     raeburn  2560:     }
1.493     albertel 2561: }
                   2562: 
1.637     raeburn  2563: sub extract_embedded_items {
1.961     raeburn  2564:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2565:     my @state = ();
                   2566:     my %javafiles = (
                   2567:                       codebase => '',
                   2568:                       code => '',
                   2569:                       archive => ''
                   2570:                     );
                   2571:     my %mediafiles = (
                   2572:                       src => '',
                   2573:                       movie => '',
                   2574:                      );
1.648     raeburn  2575:     my $p;
                   2576:     if ($content) {
                   2577:         $p = HTML::LCParser->new($content);
                   2578:     } else {
1.961     raeburn  2579:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2580:     }
1.641     albertel 2581:     while (my $t=$p->get_token()) {
1.640     albertel 2582: 	if ($t->[0] eq 'S') {
                   2583: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2584: 	    push(@state, $tagname);
1.648     raeburn  2585:             if (lc($tagname) eq 'allow') {
                   2586:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2587:             }
1.640     albertel 2588: 	    if (lc($tagname) eq 'img') {
                   2589: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2590: 	    }
1.886     albertel 2591: 	    if (lc($tagname) eq 'a') {
                   2592: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2593: 	    }
1.645     raeburn  2594:             if (lc($tagname) eq 'script') {
                   2595:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2596:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2597:                 } else {
                   2598:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2599:                 }
                   2600:             }
                   2601:             if (lc($tagname) eq 'link') {
                   2602:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2603:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2604:                 }
                   2605:             }
1.640     albertel 2606: 	    if (lc($tagname) eq 'object' ||
                   2607: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2608: 		foreach my $item (keys(%javafiles)) {
                   2609: 		    $javafiles{$item} = '';
                   2610: 		}
                   2611: 	    }
                   2612: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2613: 		my $name = lc($attr->{'name'});
                   2614: 		foreach my $item (keys(%javafiles)) {
                   2615: 		    if ($name eq $item) {
                   2616: 			$javafiles{$item} = $attr->{'value'};
                   2617: 			last;
                   2618: 		    }
                   2619: 		}
                   2620: 		foreach my $item (keys(%mediafiles)) {
                   2621: 		    if ($name eq $item) {
                   2622: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2623: 			last;
                   2624: 		    }
                   2625: 		}
                   2626: 	    }
                   2627: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2628: 		foreach my $item (keys(%javafiles)) {
                   2629: 		    if ($attr->{$item}) {
                   2630: 			$javafiles{$item} = $attr->{$item};
                   2631: 			last;
                   2632: 		    }
                   2633: 		}
                   2634: 		foreach my $item (keys(%mediafiles)) {
                   2635: 		    if ($attr->{$item}) {
                   2636: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2637: 			last;
                   2638: 		    }
                   2639: 		}
                   2640: 	    }
                   2641: 	} elsif ($t->[0] eq 'E') {
                   2642: 	    my ($tagname) = ($t->[1]);
                   2643: 	    if ($javafiles{'codebase'} ne '') {
                   2644: 		$javafiles{'codebase'} .= '/';
                   2645: 	    }  
                   2646: 	    if (lc($tagname) eq 'applet' ||
                   2647: 		lc($tagname) eq 'object' ||
                   2648: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2649: 		) {
                   2650: 		foreach my $item (keys(%javafiles)) {
                   2651: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2652: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2653: 			&add_filetype($allfiles,$file,$item);
                   2654: 		    }
                   2655: 		}
                   2656: 	    } 
                   2657: 	    pop @state;
                   2658: 	}
                   2659:     }
1.637     raeburn  2660:     return 'ok';
                   2661: }
                   2662: 
1.639     albertel 2663: sub add_filetype {
                   2664:     my ($allfiles,$file,$type)=@_;
                   2665:     if (exists($allfiles->{$file})) {
                   2666: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2667: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2668: 	}
                   2669:     } else {
                   2670: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2671:     }
                   2672: }
                   2673: 
1.493     albertel 2674: sub removeuploadedurl {
1.984     neumanie 2675:     my ($url)=@_;	
                   2676:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2677:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2678: }
                   2679: 
                   2680: sub removeuserfile {
                   2681:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2682:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2683:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2684:     if ($result eq 'ok') {	
1.798     raeburn  2685:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2686:             my $metafile = $fname.'.meta';
                   2687:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2688: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2689:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2690:             my $sqlresult = 
1.823     albertel 2691:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2692:                                         'portfolio_metadata',$group,
                   2693:                                         'delete');
1.798     raeburn  2694:         }
                   2695:     }
                   2696:     return $result;
1.257     www      2697: }
1.15      www      2698: 
1.530     albertel 2699: sub mkdiruserfile {
                   2700:     my ($docuname,$docudom,$dir)=@_;
                   2701:     my $home=&homeserver($docuname,$docudom);
                   2702:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2703: }
                   2704: 
1.531     albertel 2705: sub renameuserfile {
                   2706:     my ($docuname,$docudom,$old,$new)=@_;
                   2707:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2708:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2709:                         &escape("$old").':'.&escape("$new"),$home);
                   2710:     if ($result eq 'ok') {
                   2711:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2712:             my $oldmeta = $old.'.meta';
                   2713:             my $newmeta = $new.'.meta';
                   2714:             my $metaresult = 
                   2715:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2716: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2717:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2718:             my $sqlresult = 
1.823     albertel 2719:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2720:                                         'portfolio_metadata',$group,
                   2721:                                         'delete');
1.798     raeburn  2722:         }
                   2723:     }
                   2724:     return $result;
1.531     albertel 2725: }
                   2726: 
1.14      www      2727: # ------------------------------------------------------------------------- Log
                   2728: 
                   2729: sub log {
                   2730:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2731:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2732: }
                   2733: 
                   2734: # ------------------------------------------------------------------ Course Log
1.352     www      2735: #
                   2736: # This routine flushes several buffers of non-mission-critical nature
                   2737: #
1.157     www      2738: 
                   2739: sub flushcourselogs {
1.352     www      2740:     &logthis('Flushing log buffers');
                   2741: #
                   2742: # course logs
                   2743: # This is a log of all transactions in a course, which can be used
                   2744: # for data mining purposes
                   2745: #
                   2746: # It also collects the courseid database, which lists last transaction
                   2747: # times and course titles for all courseids
                   2748: #
                   2749:     my %courseidbuffer=();
1.921     raeburn  2750:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2751:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2752: 		          &escape($courselogs{$crsid}),
                   2753: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2754: 	    delete $courselogs{$crsid};
                   2755:         } else {
                   2756:             &logthis('Failed to flush log buffer for '.$crsid);
                   2757:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2758:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2759:                         " exceeded maximum size, deleting.</font>");
                   2760:                delete $courselogs{$crsid};
                   2761:             }
1.352     www      2762:         }
1.920     raeburn  2763:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2764:             'description' => $coursedescrbuf{$crsid},
                   2765:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2766:             'type'        => $coursetypebuf{$crsid},
                   2767:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2768:         };
1.191     harris41 2769:     }
1.352     www      2770: #
                   2771: # Write course id database (reverse lookup) to homeserver of courses 
                   2772: # Is used in pickcourse
                   2773: #
1.840     albertel 2774:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2775:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2776:                                     $courseidbuffer{$crs_home},
                   2777:                                     $crs_home,'timeonly');
1.352     www      2778:     }
                   2779: #
                   2780: # File accesses
                   2781: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2782: #
1.449     matthew  2783:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2784:         if ($entry =~ /___count$/) {
                   2785:             my ($dom,$name);
1.807     albertel 2786:             ($dom,$name,undef)=
1.811     albertel 2787: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2788:             if (! defined($dom) || $dom eq '' || 
                   2789:                 ! defined($name) || $name eq '') {
1.620     albertel 2790:                 my $cid = $env{'request.course.id'};
                   2791:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2792:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2793:             }
1.450     matthew  2794:             my $value = $accesshash{$entry};
                   2795:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2796:             my %temphash=($url => $value);
1.449     matthew  2797:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2798:             if ($result eq 'ok') {
                   2799:                 delete $accesshash{$entry};
                   2800:             } elsif ($result eq 'unknown_cmd') {
                   2801:                 # Target server has old code running on it.
1.450     matthew  2802:                 my %temphash=($entry => $value);
1.449     matthew  2803:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2804:                     delete $accesshash{$entry};
                   2805:                 }
                   2806:             }
                   2807:         } else {
1.811     albertel 2808:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2809:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2810:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2811:                 delete $accesshash{$entry};
                   2812:             }
1.185     www      2813:         }
1.191     harris41 2814:     }
1.352     www      2815: #
                   2816: # Roles
                   2817: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2818: #
1.800     albertel 2819:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2820:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2821: 	    split(/\:/,$entry);
                   2822:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2823:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2824:                 $rudom,$runame) eq 'ok') {
                   2825: 	    delete $userrolehash{$entry};
                   2826:         }
                   2827:     }
1.662     raeburn  2828: #
                   2829: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2830: #
                   2831:     my %domrolebuffer = ();
1.1000    raeburn  2832:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2833:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2834:         if ($domrolebuffer{$rudom}) {
                   2835:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2836:                       '='.&escape($domainrolehash{$entry});
                   2837:         } else {
                   2838:             $domrolebuffer{$rudom}.=&escape($entry).
                   2839:                       '='.&escape($domainrolehash{$entry});
                   2840:         }
                   2841:         delete $domainrolehash{$entry};
                   2842:     }
                   2843:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2844: 	my %servers = &get_servers($dom,'library');
                   2845: 	foreach my $tryserver (keys(%servers)) {
                   2846: 	    unless (&reply('domroleput:'.$dom.':'.
                   2847: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2848: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2849: 	    }
1.662     raeburn  2850:         }
                   2851:     }
1.186     www      2852:     $dumpcount++;
1.157     www      2853: }
                   2854: 
                   2855: sub courselog {
                   2856:     my $what=shift;
1.158     www      2857:     $what=time.':'.$what;
1.620     albertel 2858:     unless ($env{'request.course.id'}) { return ''; }
                   2859:     $coursedombuf{$env{'request.course.id'}}=
                   2860:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2861:     $coursenumbuf{$env{'request.course.id'}}=
                   2862:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2863:     $coursehombuf{$env{'request.course.id'}}=
                   2864:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2865:     $coursedescrbuf{$env{'request.course.id'}}=
                   2866:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2867:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2868:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2869:     $courseownerbuf{$env{'request.course.id'}}=
                   2870:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2871:     $coursetypebuf{$env{'request.course.id'}}=
                   2872:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2873:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2874: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2875:     } else {
1.620     albertel 2876: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2877:     }
1.620     albertel 2878:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2879: 	&flushcourselogs();
                   2880:     }
1.158     www      2881: }
                   2882: 
                   2883: sub courseacclog {
                   2884:     my $fnsymb=shift;
1.620     albertel 2885:     unless ($env{'request.course.id'}) { return ''; }
                   2886:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2887:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2888:         $what.=':POST';
1.583     matthew  2889:         # FIXME: Probably ought to escape things....
1.800     albertel 2890: 	foreach my $key (keys(%env)) {
                   2891:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2892:                 my $formitem = $1;
                   2893:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2894:                     $what.=':'.$formitem.'='.$env{$key};
                   2895:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2896:                     $what.=':'.$formitem.'='.$env{$key};
                   2897:                 }
1.158     www      2898:             }
1.191     harris41 2899:         }
1.583     matthew  2900:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2901:         # FIXME: We should not be depending on a form parameter that someone
                   2902:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2903:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2904:             $what.= ':POST';
                   2905:             # FIXME: Probably ought to escape things....
                   2906:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2907:                                  'crsdiscuss') {
1.620     albertel 2908:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2909:             }
                   2910:         }
1.158     www      2911:     }
                   2912:     &courselog($what);
1.149     www      2913: }
                   2914: 
1.185     www      2915: sub countacc {
                   2916:     my $url=&declutter(shift);
1.458     matthew  2917:     return if (! defined($url) || $url eq '');
1.620     albertel 2918:     unless ($env{'request.course.id'}) { return ''; }
                   2919:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2920:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2921:     $accesshash{$key}++;
1.185     www      2922: }
1.349     www      2923: 
1.361     www      2924: sub linklog {
                   2925:     my ($from,$to)=@_;
                   2926:     $from=&declutter($from);
                   2927:     $to=&declutter($to);
                   2928:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2929:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2930: }
                   2931:   
1.349     www      2932: sub userrolelog {
                   2933:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2934:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2935:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2936:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2937:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2938:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2939:        $userrolehash
                   2940:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2941:                     =$tend.':'.$tstart;
1.662     raeburn  2942:     }
1.898     albertel 2943:     if (($env{'request.role'} =~ /dc\./) &&
                   2944: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2945: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2946: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2947:          ($trole=~/^co/))) {
1.898     albertel 2948:        $userrolehash
                   2949:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2950:                     =$tend.':'.$tstart;
                   2951:     }
1.662     raeburn  2952:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2953:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2954:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2955:         ($trole=~/^sc/)) {
                   2956:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2957:        $domainrolehash
                   2958:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2959:                     = $tend.':'.$tstart;
                   2960:     }
1.351     www      2961: }
                   2962: 
1.957     raeburn  2963: sub courserolelog {
                   2964:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2965:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2966:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2967:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2968:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2969:         ($trole eq 'co')) {
1.957     raeburn  2970:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2971:             my $cdom = $1;
                   2972:             my $cnum = $2;
                   2973:             my $sec = $3;
                   2974:             my $namespace = 'rolelog';
                   2975:             my %storehash = (
                   2976:                                role    => $trole,
                   2977:                                start   => $tstart,
                   2978:                                end     => $tend,
                   2979:                                selfenroll => $selfenroll,
                   2980:                                context    => $context,
                   2981:                             );
                   2982:             if ($trole eq 'gr') {
                   2983:                 $namespace = 'groupslog';
                   2984:                 $storehash{'group'} = $sec;
                   2985:             } else {
                   2986:                 $storehash{'section'} = $sec;
                   2987:             }
                   2988:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2989:             if (($trole ne 'st') || ($sec ne '')) {
                   2990:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2991:             }
1.957     raeburn  2992:         }
                   2993:     }
                   2994:     return;
                   2995: }
                   2996: 
1.351     www      2997: sub get_course_adv_roles {
1.948     raeburn  2998:     my ($cid,$codes) = @_;
1.620     albertel 2999:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3000:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3001:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3002:     my %nothide=();
1.800     albertel 3003:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3004:         if ($user !~ /:/) {
                   3005: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3006:         } else {
                   3007:             $nothide{$user}=1;
                   3008:         }
1.470     www      3009:     }
1.351     www      3010:     my %returnhash=();
                   3011:     my %dumphash=
                   3012:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3013:     my $now=time;
1.997     raeburn  3014:     my %privileged;
1.1000    raeburn  3015:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3016: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3017:         if (($tstart) && ($tstart<0)) { next; }
                   3018:         if (($tend) && ($tend<$now)) { next; }
                   3019:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3020:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3021: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3022:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3023:             my %dompersonnel =
1.998     raeburn  3024:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3025:             $privileged{$domain} = {};
                   3026:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3027:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3028:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3029:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3030:                         $privileged{$udom}{$uname} = 1;
                   3031:                     }
                   3032:                 }
                   3033:             }
                   3034:         }
                   3035:         if ((exists($privileged{$domain}{$username})) && 
                   3036:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3037: 	if ($role eq 'cr') { next; }
1.948     raeburn  3038:         if ($codes) {
                   3039:             if ($section) { $role .= ':'.$section; }
                   3040:             if ($returnhash{$role}) {
                   3041:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3042:             } else {
                   3043:                 $returnhash{$role}=$username.':'.$domain;
                   3044:             }
1.351     www      3045:         } else {
1.988     raeburn  3046:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3047:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3048:             if ($returnhash{$key}) {
                   3049: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3050:             } else {
                   3051:                 $returnhash{$key}=$username.':'.$domain;
                   3052:             }
1.351     www      3053:         }
1.948     raeburn  3054:     }
1.400     www      3055:     return %returnhash;
                   3056: }
                   3057: 
                   3058: sub get_my_roles {
1.937     raeburn  3059:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3060:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3061:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3062:     my (%dumphash,%nothide);
1.858     raeburn  3063:     if ($context eq 'userroles') { 
1.1056.4.10  raeburn  3064:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3065:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3066:     } else {
                   3067:         %dumphash=
1.400     www      3068:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3069:         if ($hidepriv) {
                   3070:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3071:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3072:                 if ($user !~ /:/) {
                   3073:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3074:                 } else {
                   3075:                     $nothide{$user} = 1;
                   3076:                 }
                   3077:             }
                   3078:         }
1.858     raeburn  3079:     }
1.400     www      3080:     my %returnhash=();
                   3081:     my $now=time;
1.999     raeburn  3082:     my %privileged;
1.800     albertel 3083:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3084:         my ($role,$tend,$tstart);
                   3085:         if ($context eq 'userroles') {
                   3086: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3087:         } else {
                   3088:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3089:         }
1.400     www      3090:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3091:         my $status = 'active';
1.939     raeburn  3092:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3093:             $status = 'previous';
                   3094:         } 
                   3095:         if (($tstart) && ($now<$tstart)) {
                   3096:             $status = 'future';
                   3097:         }
                   3098:         if (ref($types) eq 'ARRAY') {
                   3099:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3100:                 next;
                   3101:             } 
                   3102:         } else {
                   3103:             if ($status ne 'active') {
                   3104:                 next;
                   3105:             }
                   3106:         }
1.867     raeburn  3107:         my ($rolecode,$username,$domain,$section,$area);
                   3108:         if ($context eq 'userroles') {
                   3109:             ($area,$rolecode) = split(/_/,$entry);
                   3110:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3111:         } else {
                   3112:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3113:         }
1.832     raeburn  3114:         if (ref($roledoms) eq 'ARRAY') {
                   3115:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3116:                 next;
                   3117:             }
                   3118:         }
                   3119:         if (ref($roles) eq 'ARRAY') {
                   3120:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3121:                 if ($role =~ /^cr\//) {
                   3122:                     if (!grep(/^cr$/,@{$roles})) {
                   3123:                         next;
                   3124:                     }
                   3125:                 } else {
                   3126:                     next;
                   3127:                 }
1.832     raeburn  3128:             }
1.867     raeburn  3129:         }
1.937     raeburn  3130:         if ($hidepriv) {
1.999     raeburn  3131:             if ($context eq 'userroles') {
                   3132:                 if ((&privileged($username,$domain)) &&
                   3133:                     (!$nothide{$username.':'.$domain})) {
                   3134:                     next;
                   3135:                 }
                   3136:             } else {
                   3137:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3138:                     my %dompersonnel =
                   3139:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3140:                     $privileged{$domain} = {};
                   3141:                     if (keys(%dompersonnel)) {
                   3142:                         foreach my $server (keys(%dompersonnel)) {
                   3143:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3144:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3145:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3146:                                     $privileged{$udom}{$uname} = $trole;
                   3147:                                 }
                   3148:                             }
                   3149:                         }
                   3150:                     }
                   3151:                 }
                   3152:                 if (exists($privileged{$domain}{$username})) {
                   3153:                     if (!$nothide{$username.':'.$domain}) {
                   3154:                         next;
                   3155:                     }
                   3156:                 }
1.937     raeburn  3157:             }
                   3158:         }
1.933     raeburn  3159:         if ($withsec) {
                   3160:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3161:                 $tstart.':'.$tend;
                   3162:         } else {
                   3163:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3164:         }
1.832     raeburn  3165:     }
1.373     www      3166:     return %returnhash;
1.399     www      3167: }
                   3168: 
                   3169: # ----------------------------------------------------- Frontpage Announcements
                   3170: #
                   3171: #
                   3172: 
                   3173: sub postannounce {
                   3174:     my ($server,$text)=@_;
1.844     albertel 3175:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3176:     unless ($text=~/\w/) { $text=''; }
                   3177:     return &reply('setannounce:'.&escape($text),$server);
                   3178: }
                   3179: 
                   3180: sub getannounce {
1.448     albertel 3181: 
                   3182:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3183: 	my $announcement='';
1.800     albertel 3184: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3185: 	close($fh);
1.399     www      3186: 	if ($announcement=~/\w/) { 
                   3187: 	    return 
                   3188:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3189:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3190: 	} else {
                   3191: 	    return '';
                   3192: 	}
                   3193:     } else {
                   3194: 	return '';
                   3195:     }
1.351     www      3196: }
1.353     www      3197: 
                   3198: # ---------------------------------------------------------- Course ID routines
                   3199: # Deal with domain's nohist_courseid.db files
                   3200: #
                   3201: 
                   3202: sub courseidput {
1.921     raeburn  3203:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3204:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3205:     my $outcome;
                   3206:     if ($caller eq 'timeonly') {
                   3207:         my $cids = '';
                   3208:         foreach my $item (keys(%$storehash)) {
                   3209:             $cids.=&escape($item).'&';
                   3210:         }
                   3211:         $cids=~s/\&$//;
                   3212:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3213:                           $coursehome);       
                   3214:     } else {
                   3215:         my $items = '';
                   3216:         foreach my $item (keys(%$storehash)) {
                   3217:             $items.= &escape($item).'='.
                   3218:                      &freeze_escape($$storehash{$item}).'&';
                   3219:         }
                   3220:         $items=~s/\&$//;
                   3221:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3222:                           $coursehome);
1.918     raeburn  3223:     }
                   3224:     if ($outcome eq 'unknown_cmd') {
                   3225:         my $what;
                   3226:         foreach my $cid (keys(%$storehash)) {
                   3227:             $what .= &escape($cid).'=';
1.921     raeburn  3228:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3229:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3230:             }
                   3231:             $what =~ s/\:$/&/;
                   3232:         }
                   3233:         $what =~ s/\&$//;  
                   3234:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3235:     } else {
                   3236:         return $outcome;
                   3237:     }
1.353     www      3238: }
                   3239: 
                   3240: sub courseiddump {
1.921     raeburn  3241:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3242:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3243:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3244:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3245:     my $as_hash = 1;
                   3246:     my %returnhash;
                   3247:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3248:     my %libserv = &all_library();
                   3249:     foreach my $tryserver (keys(%libserv)) {
                   3250:         if ( (  $hostidflag == 1 
                   3251: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3252: 	     || (!defined($hostidflag)) ) {
                   3253: 
1.918     raeburn  3254: 	    if (($domfilter eq '') ||
                   3255: 		(&host_domain($tryserver) eq $domfilter)) {
                   3256:                 my $rep = 
                   3257:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3258:                          $sincefilter.':'.&escape($descfilter).':'.
                   3259:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3260:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3261:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3262:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3263:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3264:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3265:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3266:                          &escape($creationcontext).':'.$domcloner,
                   3267:                          $tryserver);
1.918     raeburn  3268:                 my @pairs=split(/\&/,$rep);
                   3269:                 foreach my $item (@pairs) {
                   3270:                     my ($key,$value)=split(/\=/,$item,2);
                   3271:                     $key = &unescape($key);
                   3272:                     next if ($key =~ /^error: 2 /);
                   3273:                     my $result = &thaw_unescape($value);
                   3274:                     if (ref($result) eq 'HASH') {
                   3275:                         $returnhash{$key}=$result;
                   3276:                     } else {
1.921     raeburn  3277:                         my @responses = split(/:/,$value);
                   3278:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3279:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3280:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3281:                         }
1.1008    raeburn  3282:                     }
1.353     www      3283:                 }
                   3284:             }
                   3285:         }
                   3286:     }
                   3287:     return %returnhash;
                   3288: }
                   3289: 
1.1055    raeburn  3290: sub courselastaccess {
                   3291:     my ($cdom,$cnum,$hostidref) = @_;
                   3292:     my %returnhash;
                   3293:     if ($cdom && $cnum) {
                   3294:         my $chome = &homeserver($cnum,$cdom);
                   3295:         if ($chome ne 'no_host') {
                   3296:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3297:             &extract_lastaccess(\%returnhash,$rep);
                   3298:         }
                   3299:     } else {
                   3300:         if (!$cdom) { $cdom=''; }
                   3301:         my %libserv = &all_library();
                   3302:         foreach my $tryserver (keys(%libserv)) {
                   3303:             if (ref($hostidref) eq 'ARRAY') {
                   3304:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3305:             } 
                   3306:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3307:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3308:                 &extract_lastaccess(\%returnhash,$rep);
                   3309:             }
                   3310:         }
                   3311:     }
                   3312:     return %returnhash;
                   3313: }
                   3314: 
                   3315: sub extract_lastaccess {
                   3316:     my ($returnhash,$rep) = @_;
                   3317:     if (ref($returnhash) eq 'HASH') {
                   3318:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3319:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3320:                  $rep eq '') {
                   3321:             my @pairs=split(/\&/,$rep);
                   3322:             foreach my $item (@pairs) {
                   3323:                 my ($key,$value)=split(/\=/,$item,2);
                   3324:                 $key = &unescape($key);
                   3325:                 next if ($key =~ /^error: 2 /);
                   3326:                 $returnhash->{$key} = &thaw_unescape($value);
                   3327:             }
                   3328:         }
                   3329:     }
                   3330:     return;
                   3331: }
                   3332: 
1.658     raeburn  3333: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3334: 
                   3335: sub dcmailput {
1.685     raeburn  3336:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3337:     my $status = &Apache::lonnet::critical(
1.740     www      3338:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3339:        &escape($message),$server);
1.662     raeburn  3340:     return $status;
                   3341: }
                   3342: 
1.658     raeburn  3343: sub dcmaildump {
                   3344:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3345:     my %returnhash=();
1.846     albertel 3346: 
                   3347:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3348:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3349:                                                          &escape($enddate).':';
                   3350: 	my @esc_senders=map { &escape($_)} @$senders;
                   3351: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3352: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3353:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3354:             if (($key) && ($value)) {
                   3355:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3356:             }
                   3357:         }
                   3358:     }
                   3359:     return %returnhash;
                   3360: }
1.662     raeburn  3361: # ---------------------------------------------------------- Domain roles
                   3362: 
                   3363: sub get_domain_roles {
                   3364:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3365:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3366:         $startdate = '.';
                   3367:     }
1.1018    raeburn  3368:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3369:         $enddate = '.';
                   3370:     }
1.922     raeburn  3371:     my $rolelist;
                   3372:     if (ref($roles) eq 'ARRAY') {
                   3373:         $rolelist = join(':',@{$roles});
                   3374:     }
1.662     raeburn  3375:     my %personnel = ();
1.841     albertel 3376: 
                   3377:     my %servers = &get_servers($dom,'library');
                   3378:     foreach my $tryserver (keys(%servers)) {
                   3379: 	%{$personnel{$tryserver}}=();
                   3380: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3381: 					    &escape($startdate).':'.
                   3382: 					    &escape($enddate).':'.
                   3383: 					    &escape($rolelist), $tryserver))) {
                   3384: 	    my ($key,$value) = split(/\=/,$line,2);
                   3385: 	    if (($key) && ($value)) {
                   3386: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3387: 	    }
                   3388: 	}
1.662     raeburn  3389:     }
                   3390:     return %personnel;
                   3391: }
1.658     raeburn  3392: 
1.149     www      3393: # ----------------------------------------------------------- Check out an item
                   3394: 
1.504     albertel 3395: sub get_first_access {
                   3396:     my ($type,$argsymb)=@_;
1.790     albertel 3397:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3398:     if ($argsymb) { $symb=$argsymb; }
                   3399:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3400:     if ($type eq 'course') {
                   3401: 	$res='course';
                   3402:     } elsif ($type eq 'map') {
1.588     albertel 3403: 	$res=&symbread($map);
                   3404:     } else {
                   3405: 	$res=$symb;
                   3406:     }
                   3407:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3408:     return $times{"$courseid\0$res"};
1.504     albertel 3409: }
                   3410: 
                   3411: sub set_first_access {
                   3412:     my ($type)=@_;
1.790     albertel 3413:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3414:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3415:     if ($type eq 'course') {
                   3416: 	$res='course';
                   3417:     } elsif ($type eq 'map') {
1.588     albertel 3418: 	$res=&symbread($map);
                   3419:     } else {
                   3420: 	$res=$symb;
                   3421:     }
                   3422:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3423:     if (!$firstaccess) {
1.588     albertel 3424: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3425:     }
                   3426:     return 'already_set';
1.504     albertel 3427: }
                   3428: 
1.149     www      3429: sub checkout {
                   3430:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3431:     my $now=time;
                   3432:     my $lonhost=$perlvar{'lonHostID'};
                   3433:     my $infostr=&escape(
1.234     www      3434:                  'CHECKOUTTOKEN&'.
1.149     www      3435:                  $tuname.'&'.
                   3436:                  $tudom.'&'.
                   3437:                  $tcrsid.'&'.
                   3438:                  $symb.'&'.
                   3439: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3440:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3441:     if ($token=~/^error\:/) { 
1.672     albertel 3442:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3443:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3444:                  "</font>");
                   3445:         return ''; 
                   3446:     }
                   3447: 
1.149     www      3448:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3449:     $token=~tr/a-z/A-Z/;
                   3450: 
1.153     www      3451:     my %infohash=('resource.0.outtoken' => $token,
                   3452:                   'resource.0.checkouttime' => $now,
                   3453:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3454: 
                   3455:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3456:        return '';
1.151     www      3457:     } else {
1.672     albertel 3458:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3459:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3460:                  "</font>");
1.149     www      3461:     }    
                   3462: 
                   3463:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3464:                          &escape('Checkout '.$infostr.' - '.
                   3465:                                                  $token)) ne 'ok') {
                   3466: 	return '';
1.151     www      3467:     } else {
1.672     albertel 3468:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3469:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3470:                  "</font>");
1.149     www      3471:     }
1.151     www      3472:     return $token;
1.149     www      3473: }
                   3474: 
                   3475: # ------------------------------------------------------------ Check in an item
                   3476: 
                   3477: sub checkin {
                   3478:     my $token=shift;
1.150     www      3479:     my $now=time;
                   3480:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3481:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3482:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3483:     $dtoken=~s/\W/\_/g;
1.234     www      3484:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3485:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3486: 
1.154     www      3487:     unless (($tuname) && ($tudom)) {
                   3488:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3489:         return '';
                   3490:     }
                   3491:     
                   3492:     unless (&allowed('mgr',$tcrsid)) {
                   3493:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3494:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3495:         return '';
                   3496:     }
                   3497: 
1.153     www      3498:     my %infohash=('resource.0.intoken' => $token,
                   3499:                   'resource.0.checkintime' => $now,
                   3500:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3501: 
                   3502:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3503:        return '';
                   3504:     }    
                   3505: 
                   3506:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3507:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3508: 	return '';
                   3509:     }
                   3510: 
                   3511:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3512: }
                   3513: 
                   3514: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3515: 
                   3516: sub expirespread {
                   3517:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3518:     my $cid=$env{'request.course.id'}; 
1.110     www      3519:     if ($cid) {
                   3520:        my $now=time;
                   3521:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3522:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3523:                             $env{'course.'.$cid.'.num'}.
1.110     www      3524: 	        	    ':nohist_expirationdates:'.
                   3525:                             &escape($key).'='.$now,
1.620     albertel 3526:                             $env{'course.'.$cid.'.home'})
1.110     www      3527:     }
                   3528:     return 'ok';
1.14      www      3529: }
                   3530: 
1.109     www      3531: # ----------------------------------------------------- Devalidate Spreadsheets
                   3532: 
                   3533: sub devalidate {
1.325     www      3534:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3535:     my $cid=$env{'request.course.id'}; 
1.109     www      3536:     if ($cid) {
1.391     matthew  3537:         # delete the stored spreadsheets for
                   3538:         # - the student level sheet of this user in course's homespace
                   3539:         # - the assessment level sheet for this resource 
                   3540:         #   for this user in user's homespace
1.553     albertel 3541: 	# - current conditional state info
1.325     www      3542: 	my $key=$uname.':'.$udom.':';
1.109     www      3543:         my $status=
1.299     matthew  3544: 	    &del('nohist_calculatedsheets',
1.391     matthew  3545: 		 [$key.'studentcalc:'],
1.620     albertel 3546: 		 $env{'course.'.$cid.'.domain'},
                   3547: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3548: 		.' '.
                   3549: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3550: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3551:         unless ($status eq 'ok ok') {
                   3552:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3553:                     $uname.' at '.$udom.' for '.
1.109     www      3554: 		    $symb.': '.$status);
1.133     albertel 3555:         }
1.553     albertel 3556: 	&delenv('user.state.'.$cid);
1.109     www      3557:     }
                   3558: }
                   3559: 
1.265     albertel 3560: sub get_scalar {
                   3561:     my ($string,$end) = @_;
                   3562:     my $value;
                   3563:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3564: 	$value = $1;
                   3565:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3566: 	$value = $1;
                   3567:     }
                   3568:     return &unescape($value);
                   3569: }
                   3570: 
                   3571: sub array2str {
                   3572:   my (@array) = @_;
                   3573:   my $result=&arrayref2str(\@array);
                   3574:   $result=~s/^__ARRAY_REF__//;
                   3575:   $result=~s/__END_ARRAY_REF__$//;
                   3576:   return $result;
                   3577: }
                   3578: 
1.204     albertel 3579: sub arrayref2str {
                   3580:   my ($arrayref) = @_;
1.265     albertel 3581:   my $result='__ARRAY_REF__';
1.204     albertel 3582:   foreach my $elem (@$arrayref) {
1.265     albertel 3583:     if(ref($elem) eq 'ARRAY') {
                   3584:       $result.=&arrayref2str($elem).'&';
                   3585:     } elsif(ref($elem) eq 'HASH') {
                   3586:       $result.=&hashref2str($elem).'&';
                   3587:     } elsif(ref($elem)) {
                   3588:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3589:     } else {
                   3590:       $result.=&escape($elem).'&';
                   3591:     }
                   3592:   }
                   3593:   $result=~s/\&$//;
1.265     albertel 3594:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3595:   return $result;
                   3596: }
                   3597: 
1.168     albertel 3598: sub hash2str {
1.204     albertel 3599:   my (%hash) = @_;
                   3600:   my $result=&hashref2str(\%hash);
1.265     albertel 3601:   $result=~s/^__HASH_REF__//;
                   3602:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3603:   return $result;
                   3604: }
                   3605: 
                   3606: sub hashref2str {
                   3607:   my ($hashref)=@_;
1.265     albertel 3608:   my $result='__HASH_REF__';
1.800     albertel 3609:   foreach my $key (sort(keys(%$hashref))) {
                   3610:     if (ref($key) eq 'ARRAY') {
                   3611:       $result.=&arrayref2str($key).'=';
                   3612:     } elsif (ref($key) eq 'HASH') {
                   3613:       $result.=&hashref2str($key).'=';
                   3614:     } elsif (ref($key)) {
1.265     albertel 3615:       $result.='=';
1.800     albertel 3616:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3617:     } else {
1.800     albertel 3618: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3619:     }
                   3620: 
1.800     albertel 3621:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3622:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3623:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3624:       $result.=&hashref2str($hashref->{$key}).'&';
                   3625:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3626:        $result.='&';
1.800     albertel 3627:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3628:     } else {
1.800     albertel 3629:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3630:     }
                   3631:   }
1.168     albertel 3632:   $result=~s/\&$//;
1.265     albertel 3633:   $result .= '__END_HASH_REF__';
1.168     albertel 3634:   return $result;
                   3635: }
                   3636: 
                   3637: sub str2hash {
1.265     albertel 3638:     my ($string)=@_;
                   3639:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3640:     return %$hash;
                   3641: }
                   3642: 
                   3643: sub str2hashref {
1.168     albertel 3644:   my ($string) = @_;
1.265     albertel 3645: 
                   3646:   my %hash;
                   3647: 
                   3648:   if($string !~ /^__HASH_REF__/) {
                   3649:       if (! ($string eq '' || !defined($string))) {
                   3650: 	  $hash{'error'}='Not hash reference';
                   3651:       }
                   3652:       return (\%hash, $string);
                   3653:   }
                   3654: 
                   3655:   $string =~ s/^__HASH_REF__//;
                   3656: 
                   3657:   while($string !~ /^__END_HASH_REF__/) {
                   3658:       #key
                   3659:       my $key='';
                   3660:       if($string =~ /^__HASH_REF__/) {
                   3661:           ($key, $string)=&str2hashref($string);
                   3662:           if(defined($key->{'error'})) {
                   3663:               $hash{'error'}='Bad data';
                   3664:               return (\%hash, $string);
                   3665:           }
                   3666:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3667:           ($key, $string)=&str2arrayref($string);
                   3668:           if($key->[0] eq 'Array reference error') {
                   3669:               $hash{'error'}='Bad data';
                   3670:               return (\%hash, $string);
                   3671:           }
                   3672:       } else {
                   3673:           $string =~ s/^(.*?)=//;
1.267     albertel 3674: 	  $key=&unescape($1);
1.265     albertel 3675:       }
                   3676:       $string =~ s/^=//;
                   3677: 
                   3678:       #value
                   3679:       my $value='';
                   3680:       if($string =~ /^__HASH_REF__/) {
                   3681:           ($value, $string)=&str2hashref($string);
                   3682:           if(defined($value->{'error'})) {
                   3683:               $hash{'error'}='Bad data';
                   3684:               return (\%hash, $string);
                   3685:           }
                   3686:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3687:           ($value, $string)=&str2arrayref($string);
                   3688:           if($value->[0] eq 'Array reference error') {
                   3689:               $hash{'error'}='Bad data';
                   3690:               return (\%hash, $string);
                   3691:           }
                   3692:       } else {
                   3693: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3694:       }
                   3695:       $string =~ s/^&//;
                   3696: 
                   3697:       $hash{$key}=$value;
1.204     albertel 3698:   }
1.265     albertel 3699: 
                   3700:   $string =~ s/^__END_HASH_REF__//;
                   3701: 
                   3702:   return (\%hash, $string);
1.204     albertel 3703: }
                   3704: 
                   3705: sub str2array {
1.265     albertel 3706:     my ($string)=@_;
                   3707:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3708:     return @$array;
                   3709: }
                   3710: 
                   3711: sub str2arrayref {
1.204     albertel 3712:   my ($string) = @_;
1.265     albertel 3713:   my @array;
                   3714: 
                   3715:   if($string !~ /^__ARRAY_REF__/) {
                   3716:       if (! ($string eq '' || !defined($string))) {
                   3717: 	  $array[0]='Array reference error';
                   3718:       }
                   3719:       return (\@array, $string);
                   3720:   }
                   3721: 
                   3722:   $string =~ s/^__ARRAY_REF__//;
                   3723: 
                   3724:   while($string !~ /^__END_ARRAY_REF__/) {
                   3725:       my $value='';
                   3726:       if($string =~ /^__HASH_REF__/) {
                   3727:           ($value, $string)=&str2hashref($string);
                   3728:           if(defined($value->{'error'})) {
                   3729:               $array[0] ='Array reference error';
                   3730:               return (\@array, $string);
                   3731:           }
                   3732:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3733:           ($value, $string)=&str2arrayref($string);
                   3734:           if($value->[0] eq 'Array reference error') {
                   3735:               $array[0] ='Array reference error';
                   3736:               return (\@array, $string);
                   3737:           }
                   3738:       } else {
                   3739: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3740:       }
                   3741:       $string =~ s/^&//;
                   3742: 
                   3743:       push(@array, $value);
1.191     harris41 3744:   }
1.265     albertel 3745: 
                   3746:   $string =~ s/^__END_ARRAY_REF__//;
                   3747: 
                   3748:   return (\@array, $string);
1.168     albertel 3749: }
                   3750: 
1.167     albertel 3751: # -------------------------------------------------------------------Temp Store
                   3752: 
1.168     albertel 3753: sub tmpreset {
                   3754:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3755:   if (!$symb) {
                   3756:     $symb=&symbread();
1.620     albertel 3757:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3758:   }
                   3759:   $symb=escape($symb);
                   3760: 
1.620     albertel 3761:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3762:   $namespace=~s/\//\_/g;
                   3763:   $namespace=~s/\W//g;
                   3764: 
1.620     albertel 3765:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3766:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3767:   if ($domain eq 'public' && $stuname eq 'public') {
                   3768:       $stuname=$ENV{'REMOTE_ADDR'};
                   3769:   }
1.168     albertel 3770:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3771:   my %hash;
                   3772:   if (tie(%hash,'GDBM_File',
                   3773: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3774: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3775:     foreach my $key (keys(%hash)) {
1.180     albertel 3776:       if ($key=~ /:$symb/) {
1.168     albertel 3777: 	delete($hash{$key});
                   3778:       }
                   3779:     }
                   3780:   }
                   3781: }
                   3782: 
1.167     albertel 3783: sub tmpstore {
1.168     albertel 3784:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3785: 
                   3786:   if (!$symb) {
                   3787:     $symb=&symbread();
1.620     albertel 3788:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3789:   }
                   3790:   $symb=escape($symb);
                   3791: 
                   3792:   if (!$namespace) {
                   3793:     # I don't think we would ever want to store this for a course.
                   3794:     # it seems this will only be used if we don't have a course.
1.620     albertel 3795:     #$namespace=$env{'request.course.id'};
1.168     albertel 3796:     #if (!$namespace) {
1.620     albertel 3797:       $namespace=$env{'request.state'};
1.168     albertel 3798:     #}
                   3799:   }
                   3800:   $namespace=~s/\//\_/g;
                   3801:   $namespace=~s/\W//g;
1.620     albertel 3802:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3803:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3804:   if ($domain eq 'public' && $stuname eq 'public') {
                   3805:       $stuname=$ENV{'REMOTE_ADDR'};
                   3806:   }
1.168     albertel 3807:   my $now=time;
                   3808:   my %hash;
                   3809:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3810:   if (tie(%hash,'GDBM_File',
                   3811: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3812: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3813:     $hash{"version:$symb"}++;
                   3814:     my $version=$hash{"version:$symb"};
                   3815:     my $allkeys=''; 
                   3816:     foreach my $key (keys(%$storehash)) {
                   3817:       $allkeys.=$key.':';
1.591     albertel 3818:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3819:     }
                   3820:     $hash{"$version:$symb:timestamp"}=$now;
                   3821:     $allkeys.='timestamp';
                   3822:     $hash{"$version:keys:$symb"}=$allkeys;
                   3823:     if (untie(%hash)) {
                   3824:       return 'ok';
                   3825:     } else {
                   3826:       return "error:$!";
                   3827:     }
                   3828:   } else {
                   3829:     return "error:$!";
                   3830:   }
                   3831: }
1.167     albertel 3832: 
1.168     albertel 3833: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3834: 
1.168     albertel 3835: sub tmprestore {
                   3836:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3837: 
1.168     albertel 3838:   if (!$symb) {
                   3839:     $symb=&symbread();
1.620     albertel 3840:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3841:   }
                   3842:   $symb=escape($symb);
                   3843: 
1.620     albertel 3844:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3845: 
1.620     albertel 3846:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3847:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3848:   if ($domain eq 'public' && $stuname eq 'public') {
                   3849:       $stuname=$ENV{'REMOTE_ADDR'};
                   3850:   }
1.168     albertel 3851:   my %returnhash;
                   3852:   $namespace=~s/\//\_/g;
                   3853:   $namespace=~s/\W//g;
                   3854:   my %hash;
                   3855:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3856:   if (tie(%hash,'GDBM_File',
                   3857: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3858: 	  &GDBM_READER(),0640)) {
1.168     albertel 3859:     my $version=$hash{"version:$symb"};
                   3860:     $returnhash{'version'}=$version;
                   3861:     my $scope;
                   3862:     for ($scope=1;$scope<=$version;$scope++) {
                   3863:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3864:       my @keys=split(/:/,$vkeys);
                   3865:       my $key;
                   3866:       $returnhash{"$scope:keys"}=$vkeys;
                   3867:       foreach $key (@keys) {
1.591     albertel 3868: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3869: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3870:       }
                   3871:     }
1.168     albertel 3872:     if (!(untie(%hash))) {
                   3873:       return "error:$!";
                   3874:     }
                   3875:   } else {
                   3876:     return "error:$!";
                   3877:   }
                   3878:   return %returnhash;
1.167     albertel 3879: }
                   3880: 
1.9       www      3881: # ----------------------------------------------------------------------- Store
                   3882: 
                   3883: sub store {
1.124     www      3884:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3885:     my $home='';
                   3886: 
1.168     albertel 3887:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3888: 
1.213     www      3889:     $symb=&symbclean($symb);
1.122     albertel 3890:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3891: 
1.620     albertel 3892:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3893:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3894: 
                   3895:     &devalidate($symb,$stuname,$domain);
1.109     www      3896: 
                   3897:     $symb=escape($symb);
1.187     www      3898:     if (!$namespace) { 
1.620     albertel 3899:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3900:           return ''; 
                   3901:        } 
                   3902:     }
1.620     albertel 3903:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3904: 
                   3905:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3906:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3907: 
1.12      www      3908:     my $namevalue='';
1.800     albertel 3909:     foreach my $key (keys(%$storehash)) {
                   3910:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3911:     }
1.12      www      3912:     $namevalue=~s/\&$//;
1.187     www      3913:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3914:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3915: }
                   3916: 
1.47      www      3917: # -------------------------------------------------------------- Critical Store
                   3918: 
                   3919: sub cstore {
1.124     www      3920:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3921:     my $home='';
                   3922: 
1.168     albertel 3923:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3924: 
1.213     www      3925:     $symb=&symbclean($symb);
1.122     albertel 3926:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3927: 
1.620     albertel 3928:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3929:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3930: 
                   3931:     &devalidate($symb,$stuname,$domain);
1.109     www      3932: 
                   3933:     $symb=escape($symb);
1.187     www      3934:     if (!$namespace) { 
1.620     albertel 3935:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3936:           return ''; 
                   3937:        } 
                   3938:     }
1.620     albertel 3939:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3940: 
                   3941:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3942:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3943: 
1.47      www      3944:     my $namevalue='';
1.800     albertel 3945:     foreach my $key (keys(%$storehash)) {
                   3946:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3947:     }
1.47      www      3948:     $namevalue=~s/\&$//;
1.187     www      3949:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3950:     return critical
                   3951:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3952: }
                   3953: 
1.9       www      3954: # --------------------------------------------------------------------- Restore
                   3955: 
                   3956: sub restore {
1.124     www      3957:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3958:     my $home='';
                   3959: 
1.168     albertel 3960:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3961: 
1.122     albertel 3962:     if (!$symb) {
                   3963:       unless ($symb=escape(&symbread())) { return ''; }
                   3964:     } else {
1.213     www      3965:       $symb=&escape(&symbclean($symb));
1.122     albertel 3966:     }
1.188     www      3967:     if (!$namespace) { 
1.620     albertel 3968:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3969:           return ''; 
                   3970:        } 
                   3971:     }
1.620     albertel 3972:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3973:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3974:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3975:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3976: 
1.12      www      3977:     my %returnhash=();
1.800     albertel 3978:     foreach my $line (split(/\&/,$answer)) {
                   3979: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3980:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3981:     }
1.75      www      3982:     my $version;
                   3983:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3984:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3985:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3986:        }
1.75      www      3987:     }
1.13      www      3988:     return %returnhash;
1.34      www      3989: }
                   3990: 
                   3991: # ---------------------------------------------------------- Course Description
                   3992: 
                   3993: sub coursedescription {
1.731     albertel 3994:     my ($courseid,$args)=@_;
1.34      www      3995:     $courseid=~s/^\///;
1.49      www      3996:     $courseid=~s/\_/\//g;
1.34      www      3997:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3998:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3999:     my $normalid=$cdomain.'_'.$cnum;
                   4000:     # need to always cache even if we get errors otherwise we keep 
                   4001:     # trying and trying and trying to get the course description.
                   4002:     my %envhash=();
                   4003:     my %returnhash=();
1.731     albertel 4004:     
                   4005:     my $expiretime=600;
                   4006:     if ($env{'request.course.id'} eq $normalid) {
                   4007: 	$expiretime=120;
                   4008:     }
                   4009: 
                   4010:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4011:     if (!$args->{'freshen_cache'}
                   4012: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4013: 	foreach my $key (keys(%env)) {
                   4014: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4015: 	    my ($setting) = $1;
                   4016: 	    $returnhash{$setting} = $env{$key};
                   4017: 	}
                   4018: 	return %returnhash;
                   4019:     }
                   4020: 
                   4021:     # get the data agin
                   4022:     if (!$args->{'one_time'}) {
                   4023: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4024:     }
1.811     albertel 4025: 
1.34      www      4026:     if ($chome ne 'no_host') {
1.302     albertel 4027:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4028:        if (!exists($returnhash{'con_lost'})) {
                   4029:            $returnhash{'home'}= $chome;
                   4030: 	   $returnhash{'domain'} = $cdomain;
                   4031: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4032:            if (!defined($returnhash{'type'})) {
                   4033:                $returnhash{'type'} = 'Course';
                   4034:            }
1.130     albertel 4035:            while (my ($name,$value) = each %returnhash) {
1.53      www      4036:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4037:            }
1.270     www      4038:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4039:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4040: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4041:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4042:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4043:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4044:        }
                   4045:     }
1.731     albertel 4046:     if (!$args->{'one_time'}) {
1.949     raeburn  4047: 	&appenv(\%envhash);
1.731     albertel 4048:     }
1.302     albertel 4049:     return %returnhash;
1.461     www      4050: }
                   4051: 
1.1056.4.5  raeburn  4052: sub update_released_required {
                   4053:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4054:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4055:         $cid = $env{'request.course.id'};
                   4056:         $cdom = $env{'course.'.$cid.'.domain'};
                   4057:         $cnum = $env{'course.'.$cid.'.num'};
                   4058:         $chome = $env{'course.'.$cid.'.home'};
                   4059:     }
                   4060:     if ($needsrelease) {
                   4061:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4062:         my $needsupdate;
                   4063:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4064:             $needsupdate = 1;
                   4065:         } else {
                   4066:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4067:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4068:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4069:                 $needsupdate = 1;
                   4070:             }
                   4071:         }
                   4072:         if ($needsupdate) {
                   4073:             my %needshash = (
                   4074:                              'internal.releaserequired' => $needsrelease,
                   4075:                             );
                   4076:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4077:             if ($putresult eq 'ok') {
                   4078:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4079:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4080:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4081:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4082:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4083:                 }
                   4084:             }
                   4085:         }
                   4086:     }
                   4087:     return;
                   4088: }
                   4089: 
1.461     www      4090: # -------------------------------------------------See if a user is privileged
                   4091: 
                   4092: sub privileged {
                   4093:     my ($username,$domain)=@_;
                   4094:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4095: 			&homeserver($username,$domain));
1.1033    raeburn  4096:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4097:         ($rolesdump =~ /^error:/)) {
                   4098:         return 0;
                   4099:     }
1.461     www      4100:     my $now=time;
                   4101:     if ($rolesdump ne '') {
1.800     albertel 4102:         foreach my $entry (split(/&/,$rolesdump)) {
                   4103: 	    if ($entry!~/^rolesdef_/) {
                   4104: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4105: 		$area=~s/\_\w\w$//;
                   4106: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4107: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4108: 		    my $active=1;
                   4109: 		    if ($tend) {
                   4110: 			if ($tend<$now) { $active=0; }
                   4111: 		    }
                   4112: 		    if ($tstart) {
                   4113: 			if ($tstart>$now) { $active=0; }
                   4114: 		    }
                   4115: 		    if ($active) { return 1; }
                   4116: 		}
                   4117: 	    }
                   4118: 	}
                   4119:     }
                   4120:     return 0;
1.9       www      4121: }
1.1       albertel 4122: 
1.103     harris41 4123: # -------------------------------------------------------- Get user privileges
1.11      www      4124: 
                   4125: sub rolesinit {
                   4126:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4127:     my $now=time;
                   4128:     my %userroles = ('user.login.time' => $now);
1.1056.4.10  raeburn  4129:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3  raeburn  4130:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4131:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4132:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4133:         return \%userroles;
                   4134:     }
1.11      www      4135:     my %allroles=();
1.678     raeburn  4136:     my %allgroups=();   
                   4137:     my $group_privs;
1.11      www      4138: 
                   4139:     if ($rolesdump ne '') {
1.800     albertel 4140:         foreach my $entry (split(/&/,$rolesdump)) {
                   4141: 	  if ($entry!~/^rolesdef_/) {
                   4142:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4143: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4144:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4145: 	    if ($role=~/^cr/) { 
1.807     albertel 4146: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4147: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4148: 		    ($tend,$tstart)=split('_',$trest);
                   4149: 		} else {
                   4150: 		    $trole=$role;
                   4151: 		}
1.678     raeburn  4152:             } elsif ($role =~ m|^gr/|) {
                   4153:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4154:                 ($trole,$group_privs) = split(/\//,$trole);
                   4155:                 $group_privs = &unescape($group_privs);
1.587     albertel 4156: 	    } else {
                   4157: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4158: 	    }
1.743     albertel 4159: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4160: 					 $username);
                   4161: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4162:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4163:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4164:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4165: 		my $spec=$trole.'.'.$area;
                   4166: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4167: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4168:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4169:                 } elsif ($trole eq 'gr') {
                   4170:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4171: 		} else {
1.567     raeburn  4172:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4173: 		}
1.12      www      4174:             }
1.662     raeburn  4175:           }
1.191     harris41 4176:         }
1.743     albertel 4177:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4178:         $userroles{'user.adv'}    = $adv;
                   4179: 	$userroles{'user.author'} = $author;
1.620     albertel 4180:         $env{'user.adv'}=$adv;
1.11      www      4181:     }
1.743     albertel 4182:     return \%userroles;  
1.11      www      4183: }
                   4184: 
1.567     raeburn  4185: sub set_arearole {
                   4186:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4187: # log the associated role with the area
                   4188:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4189:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4190: }
                   4191: 
                   4192: sub custom_roleprivs {
                   4193:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4194:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4195:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4196:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4197:         my ($rdummy,$roledef)=
                   4198:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4199:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4200:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4201:             if (defined($syspriv)) {
1.1043    raeburn  4202:                 if ($trest =~ /^$match_community$/) {
                   4203:                     $syspriv =~ s/bre\&S//; 
                   4204:                 }
1.567     raeburn  4205:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4206:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4207:             }
                   4208:             if ($tdomain ne '') {
                   4209:                 if (defined($dompriv)) {
                   4210:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4211:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4212:                 }
                   4213:                 if (($trest ne '') && (defined($coursepriv))) {
                   4214:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4215:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4216:                 }
                   4217:             }
                   4218:         }
                   4219:     }
                   4220: }
                   4221: 
1.678     raeburn  4222: sub group_roleprivs {
                   4223:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4224:     my $access = 1;
                   4225:     my $now = time;
                   4226:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4227:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4228:     if ($access) {
1.811     albertel 4229:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4230:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4231:     }
                   4232: }
1.567     raeburn  4233: 
                   4234: sub standard_roleprivs {
                   4235:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4236:     if (defined($pr{$trole.':s'})) {
                   4237:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4238:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4239:     }
                   4240:     if ($tdomain ne '') {
                   4241:         if (defined($pr{$trole.':d'})) {
                   4242:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4243:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4244:         }
                   4245:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4246:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4247:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4248:         }
                   4249:     }
                   4250: }
                   4251: 
                   4252: sub set_userprivs {
1.1056.4.2  raeburn  4253:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4254:     my $author=0;
                   4255:     my $adv=0;
1.678     raeburn  4256:     my %grouproles = ();
                   4257:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4258:         my @groupkeys;
1.1000    raeburn  4259:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4260:             push(@groupkeys,$role);
                   4261:         }
                   4262:         if (ref($groups_roles) eq 'HASH') {
                   4263:             foreach my $key (keys(%{$groups_roles})) {
                   4264:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4265:                     push(@groupkeys,$key);
                   4266:                 }
                   4267:             }
                   4268:         }
                   4269:         if (@groupkeys > 0) {
                   4270:             foreach my $role (@groupkeys) {
                   4271:                 my ($trole,$area,$sec,$extendedarea);
                   4272:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4273:                     $trole = $1;
                   4274:                     $area = $2;
                   4275:                     $sec = $3;
                   4276:                     $extendedarea = $area.$sec;
                   4277:                     if (exists($$allgroups{$area})) {
                   4278:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4279:                             my $spec = $trole.'.'.$extendedarea;
                   4280:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4281:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4282:                         }
1.678     raeburn  4283:                     }
                   4284:                 }
                   4285:             }
                   4286:         }
                   4287:     }
1.800     albertel 4288:     foreach my $group (keys(%grouproles)) {
                   4289:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4290:     }
1.800     albertel 4291:     foreach my $role (keys(%{$allroles})) {
                   4292:         my %thesepriv;
1.941     raeburn  4293:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4294:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4295:             if ($item ne '') {
                   4296:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4297:                 if ($restrictions eq '') {
                   4298:                     $thesepriv{$privilege}='F';
                   4299:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4300:                     $thesepriv{$privilege}.=$restrictions;
                   4301:                 }
                   4302:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4303:             }
                   4304:         }
                   4305:         my $thesestr='';
1.800     albertel 4306:         foreach my $priv (keys(%thesepriv)) {
                   4307: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4308: 	}
                   4309:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4310:     }
                   4311:     return ($author,$adv);
                   4312: }
                   4313: 
1.994     raeburn  4314: sub role_status {
1.1002    raeburn  4315:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4316:     my @pwhere = ();
                   4317:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4318:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4319:         unless (!defined($$role) || $$role eq '') {
                   4320:             $$where=join('.',@pwhere);
                   4321:             $$trolecode=$$role.'.'.$$where;
                   4322:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4323:             $$tstatus='is';
                   4324:             if ($$tstart && $$tstart>$then) {
                   4325:                 $$tstatus='future';
1.1034    raeburn  4326:                 if ($$tstart<$now) {
                   4327:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4328:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4329:                             my (%allroles,%allgroups,$group_privs,
                   4330:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4331:                             my %userroles = (
                   4332:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4333:                             );
1.1056.4.2  raeburn  4334:                             @rolecodes = ('cm');
1.1002    raeburn  4335:                             my $spec=$$role.'.'.$$where;
                   4336:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4337:                             if ($$role =~ /^cr\//) {
                   4338:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4339:                                 push(@rolecodes,'cr');
1.1002    raeburn  4340:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4341:                                 push(@rolecodes,$$role);
1.1002    raeburn  4342:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4343:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4344:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4345:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4346:                                 $group_privs = &unescape($group_privs);
                   4347:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4348:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4349:                                 if (keys(%course_roles) > 0) {
                   4350:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4351:                                     if ($tdomain ne '' && $tnum ne '') {
                   4352:                                         foreach my $key (keys(%course_roles)) {
                   4353:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4354:                                                 my $crsrole = $1;
                   4355:                                                 my $crssec = $2;
                   4356:                                                 if ($crsrole =~ /^cr/) {
                   4357:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4358:                                                         push(@rolecodes,'cr');
                   4359:                                                     }
                   4360:                                                 } else {
                   4361:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4362:                                                         push(@rolecodes,$crsrole);
                   4363:                                                     }
                   4364:                                                 }
                   4365:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4366:                                                 if ($crssec ne '') {
                   4367:                                                     $rolekey .= '/'.$crssec;
                   4368:                                                 }
                   4369:                                                 $rolekey .= './';
                   4370:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4371:                                             }
                   4372:                                         }
                   4373:                                     }
                   4374:                                 }
1.1002    raeburn  4375:                             } else {
1.1056.4.2  raeburn  4376:                                 push(@rolecodes,$$role);
1.1002    raeburn  4377:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4378:                             }
1.1056.4.2  raeburn  4379:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4380:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4381:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4382:                         }
                   4383:                     }
1.1034    raeburn  4384:                     $$tstatus = 'is';
1.1002    raeburn  4385:                 }
1.994     raeburn  4386:             }
                   4387:             if ($$tend) {
                   4388:                 if ($$tend<$then) {
                   4389:                     $$tstatus='expired';
                   4390:                 } elsif ($$tend<$now) {
                   4391:                     $$tstatus='will_not';
                   4392:                 }
                   4393:             }
                   4394:         }
                   4395:     }
                   4396: }
                   4397: 
                   4398: sub check_adhoc_privs {
1.1056.4.12! raeburn  4399:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4400:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4401:     if ($env{$cckey}) {
                   4402:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4403:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4404:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12! raeburn  4405:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4406:         }
                   4407:     } else {
1.1056.4.12! raeburn  4408:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4409:     }
                   4410: }
                   4411: 
                   4412: sub set_adhoc_privileges {
                   4413: # role can be cc or ca
1.1056.4.12! raeburn  4414:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4415:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4416:     my $spec = $role.'.'.$area;
                   4417:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4418:                                   $env{'user.name'});
                   4419:     my %ccrole = ();
                   4420:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4421:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4422:     &appenv(\%userroles,[$role,'cm']);
                   4423:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12! raeburn  4424:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
        !          4425:         &appenv( {'request.role'        => $spec,
        !          4426:                   'request.role.domain' => $dcdom,
        !          4427:                   'request.course.sec'  => ''
        !          4428:                  }
        !          4429:                );
        !          4430:         my $tadv=0;
        !          4431:         if (&allowed('adv') eq 'F') { $tadv=1; }
        !          4432:         &appenv({'request.role.adv'    => $tadv});
        !          4433:     }
1.994     raeburn  4434: }
                   4435: 
1.12      www      4436: # --------------------------------------------------------------- get interface
                   4437: 
                   4438: sub get {
1.131     albertel 4439:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4440:    my $items='';
1.800     albertel 4441:    foreach my $item (@$storearr) {
                   4442:        $items.=&escape($item).'&';
1.191     harris41 4443:    }
1.12      www      4444:    $items=~s/\&$//;
1.620     albertel 4445:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4446:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4447:    my $uhome=&homeserver($uname,$udomain);
                   4448: 
1.133     albertel 4449:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4450:    my @pairs=split(/\&/,$rep);
1.273     albertel 4451:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4452:      return @pairs;
                   4453:    }
1.15      www      4454:    my %returnhash=();
1.42      www      4455:    my $i=0;
1.800     albertel 4456:    foreach my $item (@$storearr) {
                   4457:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4458:       $i++;
1.191     harris41 4459:    }
1.15      www      4460:    return %returnhash;
1.27      www      4461: }
                   4462: 
                   4463: # --------------------------------------------------------------- del interface
                   4464: 
                   4465: sub del {
1.133     albertel 4466:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4467:    my $items='';
1.800     albertel 4468:    foreach my $item (@$storearr) {
                   4469:        $items.=&escape($item).'&';
1.191     harris41 4470:    }
1.984     neumanie 4471: 
1.27      www      4472:    $items=~s/\&$//;
1.620     albertel 4473:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4474:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4475:    my $uhome=&homeserver($uname,$udomain);
                   4476:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4477: }
                   4478: 
                   4479: # -------------------------------------------------------------- dump interface
                   4480: 
                   4481: sub dump {
1.1056.4.10  raeburn  4482:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4483:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4484:     if (!$uname) { $uname=$env{'user.name'}; }
                   4485:     my $uhome=&homeserver($uname,$udomain);
                   4486:     if ($regexp) {
                   4487: 	$regexp=&escape($regexp);
                   4488:     } else {
                   4489: 	$regexp='.';
                   4490:     }
1.1056.4.10  raeburn  4491:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4492:     my @pairs=split(/\&/,$rep);
                   4493:     my %returnhash=();
                   4494:     foreach my $item (@pairs) {
                   4495: 	my ($key,$value)=split(/=/,$item,2);
                   4496: 	$key = &unescape($key);
                   4497: 	next if ($key =~ /^error: 2 /);
                   4498: 	$returnhash{$key}=&thaw_unescape($value);
                   4499:     }
                   4500:     return %returnhash;
1.407     www      4501: }
                   4502: 
1.717     albertel 4503: # --------------------------------------------------------- dumpstore interface
                   4504: 
                   4505: sub dumpstore {
                   4506:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4507:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4508:    if (!$uname) { $uname=$env{'user.name'}; }
                   4509:    my $uhome=&homeserver($uname,$udomain);
                   4510:    if ($regexp) {
                   4511:        $regexp=&escape($regexp);
                   4512:    } else {
                   4513:        $regexp='.';
                   4514:    }
                   4515:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4516:    my @pairs=split(/\&/,$rep);
                   4517:    my %returnhash=();
                   4518:    foreach my $item (@pairs) {
                   4519:        my ($key,$value)=split(/=/,$item,2);
                   4520:        next if ($key =~ /^error: 2 /);
                   4521:        $returnhash{$key}=&thaw_unescape($value);
                   4522:    }
                   4523:    return %returnhash;
1.717     albertel 4524: }
                   4525: 
1.407     www      4526: # -------------------------------------------------------------- keys interface
                   4527: 
                   4528: sub getkeys {
                   4529:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4530:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4531:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4532:    my $uhome=&homeserver($uname,$udomain);
                   4533:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4534:    my @keyarray=();
1.800     albertel 4535:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4536:       next if ($key =~ /^error: 2 /);
1.800     albertel 4537:       push(@keyarray,&unescape($key));
1.407     www      4538:    }
                   4539:    return @keyarray;
1.318     matthew  4540: }
                   4541: 
1.319     matthew  4542: # --------------------------------------------------------------- currentdump
                   4543: sub currentdump {
1.328     matthew  4544:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4545:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4546:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4547:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4548:    my $uhome = &homeserver($sname,$sdom);
                   4549:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4550:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4551:    #
1.318     matthew  4552:    my %returnhash=();
1.319     matthew  4553:    #
                   4554:    if ($rep eq "unknown_cmd") { 
                   4555:        # an old lond will not know currentdump
                   4556:        # Do a dump and make it look like a currentdump
1.822     albertel 4557:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4558:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4559:        my %hash = @tmp;
                   4560:        @tmp=();
1.424     matthew  4561:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4562:    } else {
                   4563:        my @pairs=split(/\&/,$rep);
1.800     albertel 4564:        foreach my $pair (@pairs) {
                   4565:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4566:            my ($symb,$param) = split(/:/,$key);
                   4567:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4568:                                                         &thaw_unescape($value);
1.319     matthew  4569:        }
1.191     harris41 4570:    }
1.12      www      4571:    return %returnhash;
1.424     matthew  4572: }
                   4573: 
                   4574: sub convert_dump_to_currentdump{
                   4575:     my %hash = %{shift()};
                   4576:     my %returnhash;
                   4577:     # Code ripped from lond, essentially.  The only difference
                   4578:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4579:     # we might run in to problems with parameter names =~ /^v\./
                   4580:     while (my ($key,$value) = each(%hash)) {
                   4581:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4582: 	$symb  = &unescape($symb);
                   4583: 	$param = &unescape($param);
1.424     matthew  4584:         next if ($v eq 'version' || $symb eq 'keys');
                   4585:         next if (exists($returnhash{$symb}) &&
                   4586:                  exists($returnhash{$symb}->{$param}) &&
                   4587:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4588:         $returnhash{$symb}->{$param}=$value;
                   4589:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4590:     }
                   4591:     #
                   4592:     # Remove all of the keys in the hashes which keep track of
                   4593:     # the version of the parameter.
                   4594:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4595:         # use a foreach because we are going to delete from the hash.
                   4596:         foreach my $key (keys(%$param_hash)) {
                   4597:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4598:         }
                   4599:     }
                   4600:     return \%returnhash;
1.12      www      4601: }
                   4602: 
1.627     albertel 4603: # ------------------------------------------------------ critical inc interface
                   4604: 
                   4605: sub cinc {
                   4606:     return &inc(@_,'critical');
                   4607: }
                   4608: 
1.449     matthew  4609: # --------------------------------------------------------------- inc interface
                   4610: 
                   4611: sub inc {
1.627     albertel 4612:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4613:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4614:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4615:     my $uhome=&homeserver($uname,$udomain);
                   4616:     my $items='';
                   4617:     if (! ref($store)) {
                   4618:         # got a single value, so use that instead
                   4619:         $items = &escape($store).'=&';
                   4620:     } elsif (ref($store) eq 'SCALAR') {
                   4621:         $items = &escape($$store).'=&';        
                   4622:     } elsif (ref($store) eq 'ARRAY') {
                   4623:         $items = join('=&',map {&escape($_);} @{$store});
                   4624:     } elsif (ref($store) eq 'HASH') {
                   4625:         while (my($key,$value) = each(%{$store})) {
                   4626:             $items.= &escape($key).'='.&escape($value).'&';
                   4627:         }
                   4628:     }
                   4629:     $items=~s/\&$//;
1.627     albertel 4630:     if ($critical) {
                   4631: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4632:     } else {
                   4633: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4634:     }
1.449     matthew  4635: }
                   4636: 
1.12      www      4637: # --------------------------------------------------------------- put interface
                   4638: 
                   4639: sub put {
1.134     albertel 4640:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4641:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4642:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4643:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4644:    my $items='';
1.800     albertel 4645:    foreach my $item (keys(%$storehash)) {
                   4646:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4647:    }
1.12      www      4648:    $items=~s/\&$//;
1.134     albertel 4649:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4650: }
                   4651: 
1.631     albertel 4652: # ------------------------------------------------------------ newput interface
                   4653: 
                   4654: sub newput {
                   4655:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4656:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4657:    if (!$uname) { $uname=$env{'user.name'}; }
                   4658:    my $uhome=&homeserver($uname,$udomain);
                   4659:    my $items='';
                   4660:    foreach my $key (keys(%$storehash)) {
                   4661:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4662:    }
                   4663:    $items=~s/\&$//;
                   4664:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4665: }
                   4666: 
                   4667: # ---------------------------------------------------------  putstore interface
                   4668: 
1.524     raeburn  4669: sub putstore {
1.715     albertel 4670:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4671:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4672:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4673:    my $uhome=&homeserver($uname,$udomain);
                   4674:    my $items='';
1.715     albertel 4675:    foreach my $key (keys(%$storehash)) {
                   4676:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4677:    }
1.715     albertel 4678:    $items=~s/\&$//;
1.716     albertel 4679:    my $esc_symb=&escape($symb);
                   4680:    my $esc_v=&escape($version);
1.715     albertel 4681:    my $reply =
1.716     albertel 4682:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4683: 	      $uhome);
                   4684:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4685:        # gfall back to way things use to be done
1.715     albertel 4686:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4687: 			    $uname);
1.524     raeburn  4688:    }
1.715     albertel 4689:    return $reply;
                   4690: }
                   4691: 
                   4692: sub old_putstore {
1.716     albertel 4693:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4694:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4695:     if (!$uname) { $uname=$env{'user.name'}; }
                   4696:     my $uhome=&homeserver($uname,$udomain);
                   4697:     my %newstorehash;
1.800     albertel 4698:     foreach my $item (keys(%$storehash)) {
                   4699: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4700: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4701:     }
                   4702:     my $items='';
                   4703:     my %allitems = ();
1.800     albertel 4704:     foreach my $item (keys(%newstorehash)) {
                   4705: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4706: 	    my $key = $1.':keys:'.$2;
                   4707: 	    $allitems{$key} .= $3.':';
                   4708: 	}
1.800     albertel 4709: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4710:     }
1.800     albertel 4711:     foreach my $item (keys(%allitems)) {
                   4712: 	$allitems{$item} =~ s/\:$//;
                   4713: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4714:     }
                   4715:     $items=~s/\&$//;
                   4716:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4717: }
                   4718: 
1.47      www      4719: # ------------------------------------------------------ critical put interface
                   4720: 
                   4721: sub cput {
1.134     albertel 4722:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4723:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4724:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4725:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4726:    my $items='';
1.800     albertel 4727:    foreach my $item (keys(%$storehash)) {
                   4728:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4729:    }
1.47      www      4730:    $items=~s/\&$//;
1.134     albertel 4731:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4732: }
                   4733: 
                   4734: # -------------------------------------------------------------- eget interface
                   4735: 
                   4736: sub eget {
1.133     albertel 4737:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4738:    my $items='';
1.800     albertel 4739:    foreach my $item (@$storearr) {
                   4740:        $items.=&escape($item).'&';
1.191     harris41 4741:    }
1.12      www      4742:    $items=~s/\&$//;
1.620     albertel 4743:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4744:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4745:    my $uhome=&homeserver($uname,$udomain);
                   4746:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4747:    my @pairs=split(/\&/,$rep);
                   4748:    my %returnhash=();
1.42      www      4749:    my $i=0;
1.800     albertel 4750:    foreach my $item (@$storearr) {
                   4751:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4752:       $i++;
1.191     harris41 4753:    }
1.12      www      4754:    return %returnhash;
                   4755: }
                   4756: 
1.667     albertel 4757: # ------------------------------------------------------------ tmpput interface
                   4758: sub tmpput {
1.802     raeburn  4759:     my ($storehash,$server,$context)=@_;
1.667     albertel 4760:     my $items='';
1.800     albertel 4761:     foreach my $item (keys(%$storehash)) {
                   4762: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4763:     }
                   4764:     $items=~s/\&$//;
1.802     raeburn  4765:     if (defined($context)) {
                   4766:         $items .= ':'.&escape($context);
                   4767:     }
1.667     albertel 4768:     return &reply("tmpput:$items",$server);
                   4769: }
                   4770: 
                   4771: # ------------------------------------------------------------ tmpget interface
                   4772: sub tmpget {
1.688     albertel 4773:     my ($token,$server)=@_;
                   4774:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4775:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4776:     my %returnhash;
                   4777:     foreach my $item (split(/\&/,$rep)) {
                   4778: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4779:         next if ($key =~ /^error: 2 /);
1.667     albertel 4780: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4781:     }
                   4782:     return %returnhash;
                   4783: }
                   4784: 
1.688     albertel 4785: # ------------------------------------------------------------ tmpget interface
                   4786: sub tmpdel {
                   4787:     my ($token,$server)=@_;
                   4788:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4789:     return &reply("tmpdel:$token",$server);
                   4790: }
                   4791: 
1.765     albertel 4792: # -------------------------------------------------- portfolio access checking
                   4793: 
                   4794: sub portfolio_access {
1.766     albertel 4795:     my ($requrl) = @_;
1.765     albertel 4796:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4797:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4798:     if ($result) {
                   4799:         my %setters;
                   4800:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4801:             my ($startblock,$endblock) =
                   4802:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4803:             if ($startblock && $endblock) {
                   4804:                 return 'B';
                   4805:             }
                   4806:         } else {
                   4807:             my ($startblock,$endblock) =
                   4808:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4809:             if ($startblock && $endblock) {
                   4810:                 return 'B';
                   4811:             }
                   4812:         }
                   4813:     }
1.765     albertel 4814:     if ($result eq 'ok') {
1.766     albertel 4815:        return 'F';
1.765     albertel 4816:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4817:        return 'A';
1.765     albertel 4818:     }
1.766     albertel 4819:     return '';
1.765     albertel 4820: }
                   4821: 
                   4822: sub get_portfolio_access {
1.767     albertel 4823:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4824: 
                   4825:     if (!ref($access_hash)) {
                   4826: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4827: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4828: 						   $file_name);
                   4829: 	$access_hash = $access_controls{$file_name};
                   4830:     }
                   4831: 
1.765     albertel 4832:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4833:     my $now = time;
                   4834:     if (ref($access_hash) eq 'HASH') {
                   4835:         foreach my $key (keys(%{$access_hash})) {
                   4836:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4837:             if ($start > $now) {
                   4838:                 next;
                   4839:             }
                   4840:             if ($end && $end<$now) {
                   4841:                 next;
                   4842:             }
                   4843:             if ($scope eq 'public') {
                   4844:                 $public = $key;
                   4845:                 last;
                   4846:             } elsif ($scope eq 'guest') {
                   4847:                 $guest = $key;
                   4848:             } elsif ($scope eq 'domains') {
                   4849:                 push(@domains,$key);
                   4850:             } elsif ($scope eq 'users') {
                   4851:                 push(@users,$key);
                   4852:             } elsif ($scope eq 'course') {
                   4853:                 push(@courses,$key);
                   4854:             } elsif ($scope eq 'group') {
                   4855:                 push(@groups,$key);
                   4856:             }
                   4857:         }
                   4858:         if ($public) {
                   4859:             return 'ok';
                   4860:         }
                   4861:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4862:             if ($guest) {
                   4863:                 return $guest;
                   4864:             }
                   4865:         } else {
                   4866:             if (@domains > 0) {
                   4867:                 foreach my $domkey (@domains) {
                   4868:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4869:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4870:                             return 'ok';
                   4871:                         }
                   4872:                     }
                   4873:                 }
                   4874:             }
                   4875:             if (@users > 0) {
                   4876:                 foreach my $userkey (@users) {
1.865     raeburn  4877:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4878:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4879:                             if (ref($item) eq 'HASH') {
                   4880:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4881:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4882:                                     return 'ok';
                   4883:                                 }
                   4884:                             }
                   4885:                         }
                   4886:                     } 
1.765     albertel 4887:                 }
                   4888:             }
                   4889:             my %roleshash;
                   4890:             my @courses_and_groups = @courses;
                   4891:             push(@courses_and_groups,@groups); 
                   4892:             if (@courses_and_groups > 0) {
                   4893:                 my (%allgroups,%allroles); 
                   4894:                 my ($start,$end,$role,$sec,$group);
                   4895:                 foreach my $envkey (%env) {
1.1056.4.1  raeburn  4896:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4897:                         my $cid = $2.'_'.$3; 
                   4898:                         if ($1 eq 'gr') {
                   4899:                             $group = $4;
                   4900:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4901:                         } else {
                   4902:                             if ($4 eq '') {
                   4903:                                 $sec = 'none';
                   4904:                             } else {
                   4905:                                 $sec = $4;
                   4906:                             }
                   4907:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4908:                         }
1.811     albertel 4909:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4910:                         my $cid = $2.'_'.$3;
                   4911:                         if ($4 eq '') {
                   4912:                             $sec = 'none';
                   4913:                         } else {
                   4914:                             $sec = $4;
                   4915:                         }
                   4916:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4917:                     }
                   4918:                 }
                   4919:                 if (keys(%allroles) == 0) {
                   4920:                     return;
                   4921:                 }
                   4922:                 foreach my $key (@courses_and_groups) {
                   4923:                     my %content = %{$$access_hash{$key}};
                   4924:                     my $cnum = $content{'number'};
                   4925:                     my $cdom = $content{'domain'};
                   4926:                     my $cid = $cdom.'_'.$cnum;
                   4927:                     if (!exists($allroles{$cid})) {
                   4928:                         next;
                   4929:                     }    
                   4930:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4931:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4932:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4933:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4934:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4935:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4936:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4937:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4938:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4939:                                         if (grep/^all$/,@sections) {
                   4940:                                             return 'ok';
                   4941:                                         } else {
                   4942:                                             if (grep/^$sec$/,@sections) {
                   4943:                                                 return 'ok';
                   4944:                                             }
                   4945:                                         }
                   4946:                                     }
                   4947:                                 }
                   4948:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4949:                                     if (grep/^none$/,@groups) {
                   4950:                                         return 'ok';
                   4951:                                     }
                   4952:                                 } else {
                   4953:                                     if (grep/^all$/,@groups) {
                   4954:                                         return 'ok';
                   4955:                                     } 
                   4956:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4957:                                         if (grep/^$group$/,@groups) {
                   4958:                                             return 'ok';
                   4959:                                         }
                   4960:                                     }
                   4961:                                 } 
                   4962:                             }
                   4963:                         }
                   4964:                     }
                   4965:                 }
                   4966:             }
                   4967:             if ($guest) {
                   4968:                 return $guest;
                   4969:             }
                   4970:         }
                   4971:     }
                   4972:     return;
                   4973: }
                   4974: 
                   4975: sub course_group_datechecker {
                   4976:     my ($dates,$now,$status) = @_;
                   4977:     my ($start,$end) = split(/\./,$dates);
                   4978:     if (!$start && !$end) {
                   4979:         return 'ok';
                   4980:     }
                   4981:     if (grep/^active$/,@{$status}) {
                   4982:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4983:             return 'ok';
                   4984:         }
                   4985:     }
                   4986:     if (grep/^previous$/,@{$status}) {
                   4987:         if ($end > $now ) {
                   4988:             return 'ok';
                   4989:         }
                   4990:     }
                   4991:     if (grep/^future$/,@{$status}) {
                   4992:         if ($start > $now) {
                   4993:             return 'ok';
                   4994:         }
                   4995:     }
                   4996:     return; 
                   4997: }
                   4998: 
                   4999: sub parse_portfolio_url {
                   5000:     my ($url) = @_;
                   5001: 
                   5002:     my ($type,$udom,$unum,$group,$file_name);
                   5003:     
1.823     albertel 5004:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5005: 	$type = 1;
                   5006:         $udom = $1;
                   5007:         $unum = $2;
                   5008:         $file_name = $3;
1.823     albertel 5009:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5010: 	$type = 2;
                   5011:         $udom = $1;
                   5012:         $unum = $2;
                   5013:         $group = $3;
                   5014:         $file_name = $3.'/'.$4;
                   5015:     }
                   5016:     if (wantarray) {
                   5017: 	return ($type,$udom,$unum,$file_name,$group);
                   5018:     }
                   5019:     return $type;
                   5020: }
                   5021: 
                   5022: sub is_portfolio_url {
                   5023:     my ($url) = @_;
                   5024:     return scalar(&parse_portfolio_url($url));
                   5025: }
                   5026: 
1.798     raeburn  5027: sub is_portfolio_file {
                   5028:     my ($file) = @_;
1.820     raeburn  5029:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5030:         return 1;
                   5031:     }
                   5032:     return;
                   5033: }
                   5034: 
1.976     raeburn  5035: sub usertools_access {
1.1056.4.9  raeburn  5036:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985     raeburn  5037:     my ($access,%tools);
                   5038:     if ($context eq '') {
                   5039:         $context = 'tools';
                   5040:     }
                   5041:     if ($context eq 'requestcourses') {
                   5042:         %tools = (
                   5043:                       official   => 1,
                   5044:                       unofficial => 1,
1.1006    raeburn  5045:                       community  => 1,
1.985     raeburn  5046:                  );
                   5047:     } else {
                   5048:         %tools = (
                   5049:                       aboutme   => 1,
                   5050:                       blog      => 1,
                   5051:                       portfolio => 1,
                   5052:                  );
                   5053:     }
1.976     raeburn  5054:     return if (!defined($tools{$tool}));
                   5055: 
                   5056:     if ((!defined($udom)) || (!defined($uname))) {
                   5057:         $udom = $env{'user.domain'};
                   5058:         $uname = $env{'user.name'};
                   5059:     }
                   5060: 
1.978     raeburn  5061:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5062:         if ($action ne 'reload') {
1.985     raeburn  5063:             if ($context eq 'requestcourses') {
                   5064:                 return $env{'environment.canrequest.'.$tool};
                   5065:             } else {
                   5066:                 return $env{'environment.availabletools.'.$tool};
                   5067:             }
                   5068:         }
1.976     raeburn  5069:     }
                   5070: 
                   5071:     my ($toolstatus,$inststatus);
                   5072: 
1.985     raeburn  5073:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5074:          ($action ne 'reload')) {
                   5075:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5076:         $inststatus = $env{'environment.inststatus'};
                   5077:     } else {
1.1056.4.9  raeburn  5078:         if (ref($userenvref) eq 'HASH') {
                   5079:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5080:             $inststatus = $userenvref->{'inststatus'};
                   5081:         } else {
                   5082:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5083:             $toolstatus = $userenv{$context.'.'.$tool};
                   5084:             $inststatus = $userenv{'inststatus'};
                   5085:         }
1.976     raeburn  5086:     }
                   5087: 
                   5088:     if ($toolstatus ne '') {
                   5089:         if ($toolstatus) {
                   5090:             $access = 1;
                   5091:         } else {
                   5092:             $access = 0;
                   5093:         }
                   5094:         return $access;
                   5095:     }
                   5096: 
1.1056.4.9  raeburn  5097:     my ($is_adv,%domdef);
                   5098:     if (ref($is_advref) eq 'HASH') {
                   5099:         $is_adv = $is_advref->{'is_adv'};
                   5100:     } else {
                   5101:         $is_adv = &is_advanced_user($udom,$uname);
                   5102:     }
                   5103:     if (ref($domdefref) eq 'HASH') {
                   5104:         %domdef = %{$domdefref};
                   5105:     } else {
                   5106:         %domdef = &get_domain_defaults($udom);
                   5107:     }
1.976     raeburn  5108:     if (ref($domdef{$tool}) eq 'HASH') {
                   5109:         if ($is_adv) {
                   5110:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5111:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5112:                     $access = 1;
                   5113:                 } else {
                   5114:                     $access = 0;
                   5115:                 }
                   5116:                 return $access;
                   5117:             }
                   5118:         }
                   5119:         if ($inststatus ne '') {
                   5120:             my ($hasaccess,$hasnoaccess);
                   5121:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5122:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5123:                     if ($domdef{$tool}{$affiliation}) {
                   5124:                         $hasaccess = 1;
                   5125:                     } else {
                   5126:                         $hasnoaccess = 1;
                   5127:                     }
                   5128:                 }
                   5129:             }
                   5130:             if ($hasaccess || $hasnoaccess) {
                   5131:                 if ($hasaccess) {
                   5132:                     $access = 1;
                   5133:                 } elsif ($hasnoaccess) {
                   5134:                     $access = 0; 
                   5135:                 }
                   5136:                 return $access;
                   5137:             }
                   5138:         } else {
                   5139:             if ($domdef{$tool}{'default'} ne '') {
                   5140:                 if ($domdef{$tool}{'default'}) {
                   5141:                     $access = 1;
                   5142:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5143:                     $access = 0;
                   5144:                 }
                   5145:                 return $access;
                   5146:             }
                   5147:         }
                   5148:     } else {
1.985     raeburn  5149:         if ($context eq 'tools') {
                   5150:             $access = 1;
                   5151:         } else {
                   5152:             $access = 0;
                   5153:         }
1.976     raeburn  5154:         return $access;
                   5155:     }
                   5156: }
                   5157: 
1.1050    raeburn  5158: sub is_course_owner {
                   5159:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5160:     if (($udom eq '') || ($uname eq '')) {
                   5161:         $udom = $env{'user.domain'};
                   5162:         $uname = $env{'user.name'};
                   5163:     }
                   5164:     unless (($udom eq '') || ($uname eq '')) {
                   5165:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5166:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5167:                 return 1;
                   5168:             } else {
                   5169:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5170:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5171:                     return 1;
                   5172:                 }
                   5173:             }
                   5174:         }
                   5175:     }
                   5176:     return;
                   5177: }
                   5178: 
1.976     raeburn  5179: sub is_advanced_user {
                   5180:     my ($udom,$uname) = @_;
1.1056.4.10  raeburn  5181:     if ($udom ne '' && $uname ne '') {
                   5182:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5183:             return $env{'user.adv'};
                   5184:         }
                   5185:     }
1.976     raeburn  5186:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5187:     my %allroles;
                   5188:     my $is_adv;
                   5189:     foreach my $role (keys(%roleshash)) {
                   5190:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5191:         my $area = '/'.$tdomain.'/'.$trest;
                   5192:         if ($sec ne '') {
                   5193:             $area .= '/'.$sec;
                   5194:         }
                   5195:         if (($area ne '') && ($trole ne '')) {
                   5196:             my $spec=$trole.'.'.$area;
                   5197:             if ($trole =~ /^cr\//) {
                   5198:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5199:             } elsif ($trole ne 'gr') {
                   5200:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5201:             }
                   5202:         }
                   5203:     }
                   5204:     foreach my $role (keys(%allroles)) {
                   5205:         last if ($is_adv);
                   5206:         foreach my $item (split(/:/,$allroles{$role})) {
                   5207:             if ($item ne '') {
                   5208:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5209:                 if ($privilege eq 'adv') {
                   5210:                     $is_adv = 1;
                   5211:                     last;
                   5212:                 }
                   5213:             }
                   5214:         }
                   5215:     }
                   5216:     return $is_adv;
                   5217: }
1.798     raeburn  5218: 
1.1035    raeburn  5219: sub check_can_request {
1.1036    raeburn  5220:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5221:     my $canreq = 0;
                   5222:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5223:     my @options = ('approval','validate','autolimit');
                   5224:     my $optregex = join('|',@options);
                   5225:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5226:         foreach my $type (@{$types}) {
                   5227:             if (&usertools_access($env{'user.name'},
                   5228:                                   $env{'user.domain'},
                   5229:                                   $type,undef,'requestcourses')) {
                   5230:                 $canreq ++;
1.1036    raeburn  5231:                 if (ref($request_domains) eq 'HASH') {
                   5232:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5233:                 }
1.1035    raeburn  5234:                 if ($dom eq $env{'user.domain'}) {
                   5235:                     $can_request->{$type} = 1;
                   5236:                 }
                   5237:             }
                   5238:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5239:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5240:                 if (@curr > 0) {
1.1036    raeburn  5241:                     foreach my $item (@curr) {
                   5242:                         if (ref($request_domains) eq 'HASH') {
                   5243:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5244:                             if ($otherdom ne '') {
                   5245:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5246:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5247:                                         push(@{$request_domains->{$type}},$otherdom);
                   5248:                                     }
                   5249:                                 } else {
                   5250:                                     push(@{$request_domains->{$type}},$otherdom);
                   5251:                                 }
                   5252:                             }
                   5253:                         }
                   5254:                     }
                   5255:                     unless($dom eq $env{'user.domain'}) {
                   5256:                         $canreq ++;
1.1035    raeburn  5257:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5258:                             $can_request->{$type} = 1;
                   5259:                         }
                   5260:                     }
                   5261:                 }
                   5262:             }
                   5263:         }
                   5264:     }
                   5265:     return $canreq;
                   5266: }
                   5267: 
1.341     www      5268: # ---------------------------------------------- Custom access rule evaluation
                   5269: 
                   5270: sub customaccess {
                   5271:     my ($priv,$uri)=@_;
1.807     albertel 5272:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5273:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5274:     $udom = &LONCAPA::clean_domain($udom);
                   5275:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5276:     my $access=0;
1.800     albertel 5277:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5278: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5279: 	if ($type eq 'user') {
                   5280: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5281: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5282: 		if ($tdom) {
                   5283: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5284: 		}
1.896     albertel 5285: 		if ($tuname) {
                   5286: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5287: 		}
                   5288: 		$access=($effect eq 'allow');
                   5289: 		last;
                   5290: 	    }
                   5291: 	} else {
                   5292: 	    if ($role) {
                   5293: 		if ($role ne $urole) { next; }
                   5294: 	    }
                   5295: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5296: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5297: 		if ($tdom) {
                   5298: 		    if ($tdom ne $udom) { next; }
                   5299: 		}
                   5300: 		if ($tcrs) {
                   5301: 		    if ($tcrs ne $ucrs) { next; }
                   5302: 		}
                   5303: 		if ($tsec) {
                   5304: 		    if ($tsec ne $usec) { next; }
                   5305: 		}
                   5306: 		$access=($effect eq 'allow');
                   5307: 		last;
                   5308: 	    }
                   5309: 	    if ($realm eq '' && $role eq '') {
                   5310: 		$access=($effect eq 'allow');
                   5311: 	    }
1.402     bowersj2 5312: 	}
1.341     www      5313:     }
                   5314:     return $access;
                   5315: }
                   5316: 
1.103     harris41 5317: # ------------------------------------------------- Check for a user privilege
1.12      www      5318: 
                   5319: sub allowed {
1.810     raeburn  5320:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5321:     my $ver_orguri=$uri;
1.439     www      5322:     $uri=&deversion($uri);
1.152     www      5323:     my $orguri=$uri;
1.52      www      5324:     $uri=&declutter($uri);
1.809     raeburn  5325: 
1.810     raeburn  5326:     if ($priv eq 'evb') {
                   5327: # Evade communication block restrictions for specified role in a course
                   5328:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5329:             return $1;
                   5330:         } else {
                   5331:             return;
                   5332:         }
                   5333:     }
                   5334: 
1.620     albertel 5335:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5336: # Free bre access to adm and meta resources
1.775     albertel 5337:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5338: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5339: 	&& ($priv eq 'bre')) {
1.14      www      5340: 	return 'F';
1.159     www      5341:     }
                   5342: 
1.545     banghart 5343: # Free bre access to user's own portfolio contents
1.714     raeburn  5344:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5345:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5346: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5347:         my %setters;
                   5348:         my ($startblock,$endblock) = 
                   5349:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5350:         if ($startblock && $endblock) {
                   5351:             return 'B';
                   5352:         } else {
                   5353:             return 'F';
                   5354:         }
1.545     banghart 5355:     }
                   5356: 
1.762     raeburn  5357: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5358:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5359:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5360:         if (exists($env{'request.course.id'})) {
                   5361:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5362:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5363:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5364:                 my $courseprivid=$env{'request.course.id'};
                   5365:                 $courseprivid=~s/\_/\//;
                   5366:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5367:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5368:                     return $1; 
1.762     raeburn  5369:                 } else {
                   5370:                     if ($env{'request.course.sec'}) {
                   5371:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5372:                     }
                   5373:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5374:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5375:                         return $2;
                   5376:                     }
1.714     raeburn  5377:                 }
                   5378:             }
                   5379:         }
                   5380:     }
                   5381: 
1.159     www      5382: # Free bre to public access
                   5383: 
                   5384:     if ($priv eq 'bre') {
1.238     www      5385:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5386: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5387:            return 'F'; 
                   5388:         }
1.238     www      5389:         if ($copyright eq 'priv') {
                   5390:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5391: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5392: 		return '';
                   5393:             }
                   5394:         }
                   5395:         if ($copyright eq 'domain') {
                   5396:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5397: 	    unless (($env{'user.domain'} eq $1) ||
                   5398:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5399: 		return '';
                   5400:             }
1.262     matthew  5401:         }
1.620     albertel 5402:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5403:             # Library role, so allow browsing of resources in this domain.
                   5404:             return 'F';
1.238     www      5405:         }
1.341     www      5406:         if ($copyright eq 'custom') {
                   5407: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5408:         }
1.14      www      5409:     }
1.264     matthew  5410:     # Domain coordinator is trying to create a course
1.620     albertel 5411:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5412:         # uri is the requested domain in this case.
                   5413:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5414:         # a role of dc for the domain in question.
1.620     albertel 5415:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5416:     }
1.29      www      5417: 
1.52      www      5418:     my $thisallowed='';
                   5419:     my $statecond=0;
                   5420:     my $courseprivid='';
                   5421: 
1.1039    raeburn  5422:     my $ownaccess;
1.1043    raeburn  5423:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5424:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5425:         if ($uri eq '') {
                   5426:             $ownaccess = 1;
                   5427:         } else {
                   5428:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5429:                 my $udom = $env{'user.domain'};
                   5430:                 my $uname = $env{'user.name'};
                   5431:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5432:                     $ownaccess = 1;
1.1040    raeburn  5433:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5434:                     unless ($uri =~ m{\.\./}) {
                   5435:                         $ownaccess = 1;
                   5436:                     }
                   5437:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5438:                     my $now = time;
                   5439:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5440:                         my $adom = $1;
                   5441:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5442:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5443:                                 my ($start,$end) = split('.',$env{$key});
                   5444:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5445:                                     $ownaccess = 1;
                   5446:                                     last;
                   5447:                                 }
                   5448:                             }
                   5449:                         }
                   5450:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5451:                         my $adom = $1;
                   5452:                         my $aname = $2;
1.1042    raeburn  5453:                         foreach my $role ('ca','aa') { 
                   5454:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5455:                                 my ($start,$end) =
                   5456:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5457:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5458:                                     $ownaccess = 1;
                   5459:                                     last;
                   5460:                                 }
1.1039    raeburn  5461:                             }
                   5462:                         }
                   5463:                     }
                   5464:                 }
                   5465:             }
                   5466:         }
                   5467:     }
                   5468: 
1.52      www      5469: # Course
                   5470: 
1.620     albertel 5471:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5472:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5473:             $thisallowed.=$1;
                   5474:         }
1.52      www      5475:     }
1.29      www      5476: 
1.52      www      5477: # Domain
                   5478: 
1.620     albertel 5479:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5480:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5481:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5482:             $thisallowed.=$1;
                   5483:         }
1.12      www      5484:     }
1.52      www      5485: 
                   5486: # Course: uri itself is a course
1.66      www      5487:     my $courseuri=$uri;
                   5488:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5489:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5490: 
1.620     albertel 5491:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5492:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5493:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5494:             $thisallowed.=$1;
                   5495:         }
1.12      www      5496:     }
1.29      www      5497: 
1.665     albertel 5498: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5499: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5500:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5501: 	$thisallowed='';
1.671     raeburn  5502:         my ($match)=&is_on_map($uri);
                   5503:         if ($match) {
                   5504:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5505:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5506:                 $thisallowed.=$1;
                   5507:             }
                   5508:         } else {
1.705     albertel 5509:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5510:             if ($refuri) {
                   5511:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5512:                     $thisallowed='F';
1.671     raeburn  5513:                 } else {
                   5514:                     $refuri=&declutter($refuri);
                   5515:                     my ($match) = &is_on_map($refuri);
                   5516:                     if ($match) {
                   5517:                         $thisallowed='F';
                   5518:                     }
1.669     raeburn  5519:                 }
1.671     raeburn  5520:             }
                   5521:         }
1.314     www      5522:     }
1.492     albertel 5523: 
1.766     albertel 5524:     if ($priv eq 'bre'
                   5525: 	&& $thisallowed ne 'F' 
                   5526: 	&& $thisallowed ne '2'
                   5527: 	&& &is_portfolio_url($uri)) {
                   5528: 	$thisallowed = &portfolio_access($uri);
                   5529:     }
                   5530:     
1.52      www      5531: # Full access at system, domain or course-wide level? Exit.
1.29      www      5532:     if ($thisallowed=~/F/) {
                   5533: 	return 'F';
                   5534:     }
                   5535: 
1.52      www      5536: # If this is generating or modifying users, exit with special codes
1.29      www      5537: 
1.643     www      5538:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5539: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5540: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5541: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5542: 	    unless ($auname) { return $thisallowed; }
                   5543: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5544: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5545: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5546: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5547: 	}
1.52      www      5548: 	return $thisallowed;
                   5549:     }
                   5550: #
1.103     harris41 5551: # Gathered so far: system, domain and course wide privileges
1.52      www      5552: #
                   5553: # Course: See if uri or referer is an individual resource that is part of 
                   5554: # the course
                   5555: 
1.620     albertel 5556:     if ($env{'request.course.id'}) {
1.232     www      5557: 
1.620     albertel 5558:        $courseprivid=$env{'request.course.id'};
                   5559:        if ($env{'request.course.sec'}) {
                   5560:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5561:        }
                   5562:        $courseprivid=~s/\_/\//;
                   5563:        my $checkreferer=1;
1.232     www      5564:        my ($match,$cond)=&is_on_map($uri);
                   5565:        if ($match) {
                   5566:            $statecond=$cond;
1.620     albertel 5567:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5568:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5569:                $thisallowed.=$1;
                   5570:                $checkreferer=0;
                   5571:            }
1.29      www      5572:        }
1.83      www      5573:        
1.148     www      5574:        if ($checkreferer) {
1.620     albertel 5575: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5576:             unless ($refuri) {
1.800     albertel 5577:                 foreach my $key (keys(%env)) {
                   5578: 		    if ($key=~/^httpref\..*\*/) {
                   5579: 			my $pattern=$key;
1.156     www      5580:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5581:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5582:                         $pattern=~s/\//\\\//g;
1.152     www      5583:                         if ($orguri=~/$pattern/) {
1.800     albertel 5584: 			    $refuri=$env{$key};
1.148     www      5585:                         }
                   5586:                     }
1.191     harris41 5587:                 }
1.148     www      5588:             }
1.232     www      5589: 
1.148     www      5590:          if ($refuri) { 
1.152     www      5591: 	  $refuri=&declutter($refuri);
1.232     www      5592:           my ($match,$cond)=&is_on_map($refuri);
                   5593:             if ($match) {
                   5594:               my $refstatecond=$cond;
1.620     albertel 5595:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5596:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5597:                   $thisallowed.=$1;
1.53      www      5598:                   $uri=$refuri;
                   5599:                   $statecond=$refstatecond;
1.52      www      5600:               }
                   5601:           }
1.148     www      5602:         }
1.29      www      5603:        }
1.52      www      5604:    }
1.29      www      5605: 
1.52      www      5606: #
1.103     harris41 5607: # Gathered now: all privileges that could apply, and condition number
1.52      www      5608: # 
                   5609: #
                   5610: # Full or no access?
                   5611: #
1.29      www      5612: 
1.52      www      5613:     if ($thisallowed=~/F/) {
                   5614: 	return 'F';
                   5615:     }
1.29      www      5616: 
1.52      www      5617:     unless ($thisallowed) {
                   5618:         return '';
                   5619:     }
1.29      www      5620: 
1.52      www      5621: # Restrictions exist, deal with them
                   5622: #
                   5623: #   C:according to course preferences
                   5624: #   R:according to resource settings
                   5625: #   L:unless locked
                   5626: #   X:according to user session state
                   5627: #
                   5628: 
                   5629: # Possibly locked functionality, check all courses
1.54      www      5630: # Locks might take effect only after 10 minutes cache expiration for other
                   5631: # courses, and 2 minutes for current course
1.52      www      5632: 
                   5633:     my $envkey;
                   5634:     if ($thisallowed=~/L/) {
1.1000    raeburn  5635:         foreach $envkey (keys(%env)) {
1.54      www      5636:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5637:                my $courseid=$2;
                   5638:                my $roleid=$1.'.'.$2;
1.92      www      5639:                $courseid=~s/^\///;
1.54      www      5640:                my $expiretime=600;
1.620     albertel 5641:                if ($env{'request.role'} eq $roleid) {
1.54      www      5642: 		  $expiretime=120;
                   5643:                }
                   5644: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5645:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5646:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5647: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5648:                }
1.620     albertel 5649:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5650:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5651: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5652:                        &log($env{'user.domain'},$env{'user.name'},
                   5653:                             $env{'user.home'},
1.57      www      5654:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5655:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5656:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5657: 		       return '';
                   5658:                    }
                   5659:                }
1.620     albertel 5660:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5661:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5662: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5663:                        &log($env{'user.domain'},$env{'user.name'},
                   5664:                             $env{'user.home'},
1.57      www      5665:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5666:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5667:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5668: 		       return '';
                   5669:                    }
                   5670:                }
                   5671: 	   }
1.29      www      5672:        }
1.52      www      5673:     }
                   5674:    
                   5675: #
                   5676: # Rest of the restrictions depend on selected course
                   5677: #
                   5678: 
1.620     albertel 5679:     unless ($env{'request.course.id'}) {
1.766     albertel 5680: 	if ($thisallowed eq 'A') {
                   5681: 	    return 'A';
1.814     raeburn  5682:         } elsif ($thisallowed eq 'B') {
                   5683:             return 'B';
1.766     albertel 5684: 	} else {
                   5685: 	    return '1';
                   5686: 	}
1.52      www      5687:     }
1.29      www      5688: 
1.52      www      5689: #
                   5690: # Now user is definitely in a course
                   5691: #
1.53      www      5692: 
                   5693: 
                   5694: # Course preferences
                   5695: 
                   5696:    if ($thisallowed=~/C/) {
1.620     albertel 5697:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5698:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5699:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5700: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5701: 	   if ($priv ne 'pch') { 
                   5702: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5703: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5704: 			$env{'request.course.id'});
                   5705: 	   }
1.237     www      5706:            return '';
                   5707:        }
                   5708: 
1.620     albertel 5709:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5710: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5711: 	   if ($priv ne 'pch') { 
                   5712: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5713: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5714: 			$env{'request.course.id'});
                   5715: 	   }
1.54      www      5716:            return '';
                   5717:        }
1.53      www      5718:    }
                   5719: 
                   5720: # Resource preferences
                   5721: 
                   5722:    if ($thisallowed=~/R/) {
1.620     albertel 5723:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5724:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5725: 	   if ($priv ne 'pch') { 
                   5726: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5727: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5728: 	   }
                   5729: 	   return '';
1.54      www      5730:        }
1.53      www      5731:    }
1.30      www      5732: 
1.246     www      5733: # Restricted by state or randomout?
1.30      www      5734: 
1.52      www      5735:    if ($thisallowed=~/X/) {
1.620     albertel 5736:       if ($env{'acc.randomout'}) {
1.579     albertel 5737: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5738:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5739:             return ''; 
                   5740:          }
1.247     www      5741:       }
                   5742:       if (&condval($statecond)) {
1.52      www      5743: 	 return '2';
                   5744:       } else {
                   5745:          return '';
                   5746:       }
                   5747:    }
1.30      www      5748: 
1.766     albertel 5749:     if ($thisallowed eq 'A') {
                   5750: 	return 'A';
1.814     raeburn  5751:     } elsif ($thisallowed eq 'B') {
                   5752:         return 'B';
1.766     albertel 5753:     }
1.52      www      5754:    return 'F';
1.232     www      5755: }
                   5756: 
1.710     albertel 5757: sub split_uri_for_cond {
                   5758:     my $uri=&deversion(&declutter(shift));
                   5759:     my @uriparts=split(/\//,$uri);
                   5760:     my $filename=pop(@uriparts);
                   5761:     my $pathname=join('/',@uriparts);
                   5762:     return ($pathname,$filename);
                   5763: }
1.232     www      5764: # --------------------------------------------------- Is a resource on the map?
                   5765: 
                   5766: sub is_on_map {
1.710     albertel 5767:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5768:     #Trying to find the conditional for the file
1.620     albertel 5769:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5770: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5771:     if ($match) {
1.289     bowersj2 5772: 	return (1,$1);
                   5773:     } else {
1.434     www      5774: 	return (0,0);
1.289     bowersj2 5775:     }
1.12      www      5776: }
                   5777: 
1.427     www      5778: # --------------------------------------------------------- Get symb from alias
                   5779: 
                   5780: sub get_symb_from_alias {
                   5781:     my $symb=shift;
                   5782:     my ($map,$resid,$url)=&decode_symb($symb);
                   5783: # Already is a symb
                   5784:     if ($url) { return $symb; }
                   5785: # Must be an alias
                   5786:     my $aliassymb='';
                   5787:     my %bighash;
1.620     albertel 5788:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5789:                             &GDBM_READER(),0640)) {
                   5790:         my $rid=$bighash{'mapalias_'.$symb};
                   5791: 	if ($rid) {
                   5792: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5793: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5794: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5795: 	}
                   5796:         untie %bighash;
                   5797:     }
                   5798:     return $aliassymb;
                   5799: }
                   5800: 
1.12      www      5801: # ----------------------------------------------------------------- Define Role
                   5802: 
                   5803: sub definerole {
                   5804:   if (allowed('mcr','/')) {
                   5805:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5806:     foreach my $role (split(':',$sysrole)) {
                   5807: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5808:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5809:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5810: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5811:                return "refused:s:$crole&$cqual"; 
                   5812:             }
                   5813:         }
1.191     harris41 5814:     }
1.800     albertel 5815:     foreach my $role (split(':',$domrole)) {
                   5816: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5817:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5818:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5819: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5820:                return "refused:d:$crole&$cqual"; 
                   5821:             }
                   5822:         }
1.191     harris41 5823:     }
1.800     albertel 5824:     foreach my $role (split(':',$courole)) {
                   5825: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5826:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5827:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5828: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5829:                return "refused:c:$crole&$cqual"; 
                   5830:             }
                   5831:         }
1.191     harris41 5832:     }
1.620     albertel 5833:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5834:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5835: 	        "rolesdef_$rolename=".
                   5836:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5837:     return reply($command,$env{'user.home'});
1.12      www      5838:   } else {
                   5839:     return 'refused';
                   5840:   }
1.105     harris41 5841: }
                   5842: 
                   5843: # ---------------- Make a metadata query against the network of library servers
                   5844: 
                   5845: sub metadata_query {
1.244     matthew  5846:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5847:     my %rhash;
1.845     albertel 5848:     my %libserv = &all_library();
1.244     matthew  5849:     my @server_list = (defined($server_array) ? @$server_array
                   5850:                                               : keys(%libserv) );
                   5851:     for my $server (@server_list) {
1.118     harris41 5852: 	unless ($custom or $customshow) {
                   5853: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5854: 	    $rhash{$server}=$reply;
                   5855: 	}
                   5856: 	else {
                   5857: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5858: 			     &escape($custom).':'.&escape($customshow),
                   5859: 			     $server);
                   5860: 	    $rhash{$server}=$reply;
                   5861: 	}
1.112     harris41 5862:     }
1.118     harris41 5863:     return \%rhash;
1.240     www      5864: }
                   5865: 
                   5866: # ----------------------------------------- Send log queries and wait for reply
                   5867: 
                   5868: sub log_query {
                   5869:     my ($uname,$udom,$query,%filters)=@_;
                   5870:     my $uhome=&homeserver($uname,$udom);
                   5871:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5872:     my $uhost=&hostname($uhome);
1.800     albertel 5873:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5874:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5875:                        $uhome);
1.479     albertel 5876:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5877:     return get_query_reply($queryid);
                   5878: }
                   5879: 
1.818     raeburn  5880: # -------------------------- Update MySQL table for portfolio file
                   5881: 
                   5882: sub update_portfolio_table {
1.821     raeburn  5883:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5884:     if ($group ne '') {
                   5885:         $file_name =~s /^\Q$group\E//;
                   5886:     }
1.818     raeburn  5887:     my $homeserver = &homeserver($uname,$udom);
                   5888:     my $queryid=
1.821     raeburn  5889:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5890:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5891:     my $reply = &get_query_reply($queryid);
                   5892:     return $reply;
                   5893: }
                   5894: 
1.899     raeburn  5895: # -------------------------- Update MySQL allusers table
                   5896: 
                   5897: sub update_allusers_table {
                   5898:     my ($uname,$udom,$names) = @_;
                   5899:     my $homeserver = &homeserver($uname,$udom);
                   5900:     my $queryid=
                   5901:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5902:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5903:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5904:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5905:                'generation='.&escape($names->{'generation'}).'%%'.
                   5906:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5907:                'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4  raeburn  5908:     return;
1.899     raeburn  5909: }
                   5910: 
1.508     raeburn  5911: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5912: 
                   5913: sub fetch_enrollment_query {
1.511     raeburn  5914:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5915:     my $homeserver;
1.547     raeburn  5916:     my $maxtries = 1;
1.508     raeburn  5917:     if ($context eq 'automated') {
                   5918:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5919:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5920:     } else {
                   5921:         $homeserver = &homeserver($cnum,$dom);
                   5922:     }
1.838     albertel 5923:     my $host=&hostname($homeserver);
1.506     raeburn  5924:     my $cmd = '';
1.1000    raeburn  5925:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5926:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5927:     }
                   5928:     $cmd =~ s/%%$//;
                   5929:     $cmd = &escape($cmd);
                   5930:     my $query = 'fetchenrollment';
1.620     albertel 5931:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5932:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5933:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5934:         return 'error: '.$queryid;
                   5935:     }
1.506     raeburn  5936:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5937:     my $tries = 1;
                   5938:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5939:         $reply = &get_query_reply($queryid);
                   5940:         $tries ++;
                   5941:     }
1.526     raeburn  5942:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5943:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5944:     } else {
1.901     albertel 5945:         my @responses = split(/:/,$reply);
1.515     raeburn  5946:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5947:             foreach my $line (@responses) {
                   5948:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5949:                 $$replyref{$key} = $value;
                   5950:             }
                   5951:         } else {
1.506     raeburn  5952:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5953:             foreach my $line (@responses) {
                   5954:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5955:                 $$replyref{$key} = $value;
                   5956:                 if ($value > 0) {
1.800     albertel 5957:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5958:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5959:                         my $destname = $pathname.'/'.$filename;
                   5960:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5961:                         if ($xml_classlist =~ /^error/) {
                   5962:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5963:                         } else {
1.506     raeburn  5964:                             if ( open(FILE,">$destname") ) {
                   5965:                                 print FILE &unescape($xml_classlist);
                   5966:                                 close(FILE);
1.526     raeburn  5967:                             } else {
                   5968:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5969:                             }
                   5970:                         }
                   5971:                     }
                   5972:                 }
                   5973:             }
                   5974:         }
                   5975:         return 'ok';
                   5976:     }
                   5977:     return 'error';
                   5978: }
                   5979: 
1.242     www      5980: sub get_query_reply {
                   5981:     my $queryid=shift;
1.240     www      5982:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5983:     my $reply='';
                   5984:     for (1..100) {
                   5985: 	sleep 2;
                   5986:         if (-e $replyfile.'.end') {
1.448     albertel 5987: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5988: 		$reply = join('',<$fh>);
                   5989: 		close($fh);
1.240     www      5990: 	   } else { return 'error: reply_file_error'; }
1.242     www      5991:            return &unescape($reply);
                   5992: 	}
1.240     www      5993:     }
1.242     www      5994:     return 'timeout:'.$queryid;
1.240     www      5995: }
                   5996: 
                   5997: sub courselog_query {
1.241     www      5998: #
                   5999: # possible filters:
                   6000: # url: url or symb
                   6001: # username
                   6002: # domain
                   6003: # action: view, submit, grade
                   6004: # start: timestamp
                   6005: # end: timestamp
                   6006: #
1.240     www      6007:     my (%filters)=@_;
1.620     albertel 6008:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6009:     if ($filters{'url'}) {
                   6010: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6011:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6012:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6013:     }
1.620     albertel 6014:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6015:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6016:     return &log_query($cname,$cdom,'courselog',%filters);
                   6017: }
                   6018: 
                   6019: sub userlog_query {
1.858     raeburn  6020: #
                   6021: # possible filters:
                   6022: # action: log check role
                   6023: # start: timestamp
                   6024: # end: timestamp
                   6025: #
1.240     www      6026:     my ($uname,$udom,%filters)=@_;
                   6027:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6028: }
                   6029: 
1.506     raeburn  6030: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6031: 
                   6032: sub auto_run {
1.508     raeburn  6033:     my ($cnum,$cdom) = @_;
1.876     raeburn  6034:     my $response = 0;
                   6035:     my $settings;
                   6036:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6037:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6038:         $settings = $domconfig{'autoenroll'};
                   6039:         if ($settings->{'run'} eq '1') {
                   6040:             $response = 1;
                   6041:         }
                   6042:     } else {
1.934     raeburn  6043:         my $homeserver;
                   6044:         if (&is_course($cdom,$cnum)) {
                   6045:             $homeserver = &homeserver($cnum,$cdom);
                   6046:         } else {
                   6047:             $homeserver = &domain($cdom,'primary');
                   6048:         }
                   6049:         if ($homeserver ne 'no_host') {
                   6050:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6051:         }
1.876     raeburn  6052:     }
1.506     raeburn  6053:     return $response;
                   6054: }
1.776     albertel 6055: 
1.506     raeburn  6056: sub auto_get_sections {
1.508     raeburn  6057:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6058:     my $homeserver;
                   6059:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6060:         $homeserver = &homeserver($cnum,$cdom);
                   6061:     }
                   6062:     if (!defined($homeserver)) { 
                   6063:         if ($cdom =~ /^$match_domain$/) {
                   6064:             $homeserver = &domain($cdom,'primary');
                   6065:         }
                   6066:     }
                   6067:     my @secs;
                   6068:     if (defined($homeserver)) {
                   6069:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6070:         unless ($response eq 'refused') {
                   6071:             @secs = split(/:/,$response);
                   6072:         }
1.506     raeburn  6073:     }
                   6074:     return @secs;
                   6075: }
1.776     albertel 6076: 
1.506     raeburn  6077: sub auto_new_course {
1.508     raeburn  6078:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   6079:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  6080:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  6081:     return $response;
                   6082: }
1.776     albertel 6083: 
1.506     raeburn  6084: sub auto_validate_courseID {
1.508     raeburn  6085:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6086:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6087:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6088:     return $response;
                   6089: }
1.776     albertel 6090: 
1.1007    raeburn  6091: sub auto_validate_instcode {
1.1020    raeburn  6092:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6093:     my ($homeserver,$response);
                   6094:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6095:         $homeserver = &homeserver($cnum,$cdom);
                   6096:     }
                   6097:     if (!defined($homeserver)) {
                   6098:         if ($cdom =~ /^$match_domain$/) {
                   6099:             $homeserver = &domain($cdom,'primary');
                   6100:         }
                   6101:     }
1.1056.4.2  raeburn  6102:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6103:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6104:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6105:     return ($outcome,$description);
1.1007    raeburn  6106: }
                   6107: 
1.506     raeburn  6108: sub auto_create_password {
1.873     raeburn  6109:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6110:     my ($homeserver,$response);
1.506     raeburn  6111:     my $create_passwd = 0;
                   6112:     my $authchk = '';
1.873     raeburn  6113:     if ($udom =~ /^$match_domain$/) {
                   6114:         $homeserver = &domain($udom,'primary');
                   6115:     }
                   6116:     if ($homeserver eq '') {
                   6117:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6118:             $homeserver = &homeserver($cnum,$cdom);
                   6119:         }
                   6120:     }
                   6121:     if ($homeserver eq '') {
                   6122:         $authchk = 'nodomain';
1.506     raeburn  6123:     } else {
1.873     raeburn  6124:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6125:         if ($response eq 'refused') {
                   6126:             $authchk = 'refused';
                   6127:         } else {
1.901     albertel 6128:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6129:         }
1.506     raeburn  6130:     }
                   6131:     return ($authparam,$create_passwd,$authchk);
                   6132: }
                   6133: 
1.706     raeburn  6134: sub auto_photo_permission {
                   6135:     my ($cnum,$cdom,$students) = @_;
                   6136:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6137:     my ($outcome,$perm_reqd,$conditions) = 
                   6138: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6139:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6140: 	return (undef,undef);
                   6141:     }
1.706     raeburn  6142:     return ($outcome,$perm_reqd,$conditions);
                   6143: }
                   6144: 
                   6145: sub auto_checkphotos {
                   6146:     my ($uname,$udom,$pid) = @_;
                   6147:     my $homeserver = &homeserver($uname,$udom);
                   6148:     my ($result,$resulttype);
                   6149:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6150: 				   &escape($uname).':'.&escape($pid),
                   6151: 				   $homeserver));
1.709     albertel 6152:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6153: 	return (undef,undef);
                   6154:     }
1.706     raeburn  6155:     if ($outcome) {
                   6156:         ($result,$resulttype) = split(/:/,$outcome);
                   6157:     } 
                   6158:     return ($result,$resulttype);
                   6159: }
                   6160: 
                   6161: sub auto_photochoice {
                   6162:     my ($cnum,$cdom) = @_;
                   6163:     my $homeserver = &homeserver($cnum,$cdom);
                   6164:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6165: 						       &escape($cdom),
                   6166: 						       $homeserver)));
1.709     albertel 6167:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6168: 	return (undef,undef);
                   6169:     }
1.706     raeburn  6170:     return ($update,$comment);
                   6171: }
                   6172: 
                   6173: sub auto_photoupdate {
                   6174:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6175:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6176:     my $host=&hostname($homeserver);
1.706     raeburn  6177:     my $cmd = '';
                   6178:     my $maxtries = 1;
1.800     albertel 6179:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6180:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6181:     }
                   6182:     $cmd =~ s/%%$//;
                   6183:     $cmd = &escape($cmd);
                   6184:     my $query = 'institutionalphotos';
                   6185:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6186:     unless ($queryid=~/^\Q$host\E\_/) {
                   6187:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6188:         return 'error: '.$queryid;
                   6189:     }
                   6190:     my $reply = &get_query_reply($queryid);
                   6191:     my $tries = 1;
                   6192:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6193:         $reply = &get_query_reply($queryid);
                   6194:         $tries ++;
                   6195:     }
                   6196:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6197:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6198:     } else {
                   6199:         my @responses = split(/:/,$reply);
                   6200:         my $outcome = shift(@responses); 
                   6201:         foreach my $item (@responses) {
                   6202:             my ($key,$value) = split(/=/,$item);
                   6203:             $$photo{$key} = $value;
                   6204:         }
                   6205:         return $outcome;
                   6206:     }
                   6207:     return 'error';
                   6208: }
                   6209: 
1.521     raeburn  6210: sub auto_instcode_format {
1.793     albertel 6211:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6212: 	$cat_order) = @_;
1.521     raeburn  6213:     my $courses = '';
1.772     raeburn  6214:     my @homeservers;
1.521     raeburn  6215:     if ($caller eq 'global') {
1.841     albertel 6216: 	my %servers = &get_servers($codedom,'library');
                   6217: 	foreach my $tryserver (keys(%servers)) {
                   6218: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6219: 		push(@homeservers,$tryserver);
                   6220: 	    }
1.584     raeburn  6221:         }
1.1022    raeburn  6222:     } elsif ($caller eq 'requests') {
                   6223:         if ($codedom =~ /^$match_domain$/) {
                   6224:             my $chome = &domain($codedom,'primary');
                   6225:             unless ($chome eq 'no_host') {
                   6226:                 push(@homeservers,$chome);
                   6227:             }
                   6228:         }
1.521     raeburn  6229:     } else {
1.772     raeburn  6230:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6231:     }
1.793     albertel 6232:     foreach my $code (keys(%{$instcodes})) {
                   6233:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6234:     }
                   6235:     chop($courses);
1.772     raeburn  6236:     my $ok_response = 0;
                   6237:     my $response;
                   6238:     while (@homeservers > 0 && $ok_response == 0) {
                   6239:         my $server = shift(@homeservers); 
                   6240:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6241:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6242:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6243: 		split(/:/,$response);
1.772     raeburn  6244:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6245:             push(@{$codetitles},&str2array($codetitles_str));
                   6246:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6247:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6248:             $ok_response = 1;
                   6249:         }
                   6250:     }
                   6251:     if ($ok_response) {
1.521     raeburn  6252:         return 'ok';
1.772     raeburn  6253:     } else {
                   6254:         return $response;
1.521     raeburn  6255:     }
                   6256: }
                   6257: 
1.792     raeburn  6258: sub auto_instcode_defaults {
                   6259:     my ($domain,$returnhash,$code_order) = @_;
                   6260:     my @homeservers;
1.841     albertel 6261: 
                   6262:     my %servers = &get_servers($domain,'library');
                   6263:     foreach my $tryserver (keys(%servers)) {
                   6264: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6265: 	    push(@homeservers,$tryserver);
                   6266: 	}
1.792     raeburn  6267:     }
1.841     albertel 6268: 
1.792     raeburn  6269:     my $response;
1.841     albertel 6270:     foreach my $server (@homeservers) {
1.792     raeburn  6271:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6272:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6273: 	
                   6274: 	foreach my $pair (split(/\&/,$response)) {
                   6275: 	    my ($name,$value)=split(/\=/,$pair);
                   6276: 	    if ($name eq 'code_order') {
                   6277: 		@{$code_order} = split(/\&/,&unescape($value));
                   6278: 	    } else {
                   6279: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6280: 	    }
                   6281: 	}
                   6282: 	return 'ok';
1.792     raeburn  6283:     }
1.841     albertel 6284: 
                   6285:     return $response;
1.1003    raeburn  6286: }
                   6287: 
                   6288: sub auto_possible_instcodes {
1.1007    raeburn  6289:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6290:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6291:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6292:         return;
                   6293:     }
1.1003    raeburn  6294:     my (@homeservers,$uhome);
                   6295:     if (defined(&domain($domain,'primary'))) {
                   6296:         $uhome=&domain($domain,'primary');
                   6297:         push(@homeservers,&domain($domain,'primary'));
                   6298:     } else {
                   6299:         my %servers = &get_servers($domain,'library');
                   6300:         foreach my $tryserver (keys(%servers)) {
                   6301:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6302:                 push(@homeservers,$tryserver);
                   6303:             }
                   6304:         }
                   6305:     }
                   6306:     my $response;
                   6307:     foreach my $server (@homeservers) {
                   6308:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6309:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6310:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6311:             split(':',$response);
                   6312:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6313:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6314:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6315:             my ($name,$value)=split('=',$item);
                   6316:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6317:         }
                   6318:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6319:             my ($name,$value)=split('=',$item);
                   6320:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6321:         }
                   6322:         return 'ok';
                   6323:     }
                   6324:     return $response;
                   6325: }
1.792     raeburn  6326: 
1.1010    raeburn  6327: sub auto_courserequest_checks {
                   6328:     my ($dom) = @_;
1.1020    raeburn  6329:     my ($homeserver,%validations);
                   6330:     if ($dom =~ /^$match_domain$/) {
                   6331:         $homeserver = &domain($dom,'primary');
                   6332:     }
                   6333:     unless ($homeserver eq 'no_host') {
                   6334:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6335:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6336:             my @items = split(/&/,$response);
                   6337:             foreach my $item (@items) {
                   6338:                 my ($key,$value) = split('=',$item);
                   6339:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6340:             }
                   6341:         }
                   6342:     }
1.1010    raeburn  6343:     return %validations; 
                   6344: }
                   6345: 
1.1020    raeburn  6346: sub auto_courserequest_validation {
                   6347:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6348:     my ($homeserver,$response);
                   6349:     if ($dom =~ /^$match_domain$/) {
                   6350:         $homeserver = &domain($dom,'primary');
                   6351:     }
                   6352:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6353:           
1.1020    raeburn  6354:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6355:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6356:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6357:                                     $homeserver));
                   6358:     }
                   6359:     return $response;
                   6360: }
                   6361: 
1.777     albertel 6362: sub auto_validate_class_sec {
1.918     raeburn  6363:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6364:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6365:     my $ownerlist;
                   6366:     if (ref($owners) eq 'ARRAY') {
                   6367:         $ownerlist = join(',',@{$owners});
                   6368:     } else {
                   6369:         $ownerlist = $owners;
                   6370:     }
1.773     raeburn  6371:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6372:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6373:     return $response;
                   6374: }
                   6375: 
1.679     raeburn  6376: # ------------------------------------------------------- Course Group routines
                   6377: 
                   6378: sub get_coursegroups {
1.809     raeburn  6379:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6380:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6381: }
                   6382: 
1.679     raeburn  6383: sub modify_coursegroup {
                   6384:     my ($cdom,$cnum,$groupsettings) = @_;
                   6385:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6386: }
                   6387: 
1.809     raeburn  6388: sub toggle_coursegroup_status {
                   6389:     my ($cdom,$cnum,$group,$action) = @_;
                   6390:     my ($from_namespace,$to_namespace);
                   6391:     if ($action eq 'delete') {
                   6392:         $from_namespace = 'coursegroups';
                   6393:         $to_namespace = 'deleted_groups';
                   6394:     } else {
                   6395:         $from_namespace = 'deleted_groups';
                   6396:         $to_namespace = 'coursegroups';
                   6397:     }
                   6398:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6399:     if (my $tmp = &error(%curr_group)) {
                   6400:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6401:         return ('read error',$tmp);
                   6402:     } else {
                   6403:         my %savedsettings = %curr_group; 
1.809     raeburn  6404:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6405:         my $deloutcome;
                   6406:         if ($result eq 'ok') {
1.809     raeburn  6407:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6408:         } else {
                   6409:             return ('write error',$result);
                   6410:         }
                   6411:         if ($deloutcome eq 'ok') {
                   6412:             return 'ok';
                   6413:         } else {
                   6414:             return ('delete error',$deloutcome);
                   6415:         }
                   6416:     }
                   6417: }
                   6418: 
1.679     raeburn  6419: sub modify_group_roles {
1.957     raeburn  6420:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6421:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6422:     my $role = 'gr/'.&escape($userprivs);
                   6423:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6424:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6425:     if ($result eq 'ok') {
                   6426:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6427:     }
1.679     raeburn  6428:     return $result;
                   6429: }
                   6430: 
                   6431: sub modify_coursegroup_membership {
                   6432:     my ($cdom,$cnum,$membership) = @_;
                   6433:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6434:     return $result;
                   6435: }
                   6436: 
1.682     raeburn  6437: sub get_active_groups {
                   6438:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6439:     my $now = time;
                   6440:     my %groups = ();
                   6441:     foreach my $key (keys(%env)) {
1.811     albertel 6442:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6443:             my ($start,$end) = split(/\./,$env{$key});
                   6444:             if (($end!=0) && ($end<$now)) { next; }
                   6445:             if (($start!=0) && ($start>$now)) { next; }
                   6446:             if ($1 eq $cdom && $2 eq $cnum) {
                   6447:                 $groups{$3} = $env{$key} ;
                   6448:             }
                   6449:         }
                   6450:     }
                   6451:     return %groups;
                   6452: }
                   6453: 
1.683     raeburn  6454: sub get_group_membership {
                   6455:     my ($cdom,$cnum,$group) = @_;
                   6456:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6457: }
                   6458: 
                   6459: sub get_users_groups {
                   6460:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6461:     my @usersgroups;
1.683     raeburn  6462:     my $cachetime=1800;
                   6463: 
                   6464:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6465:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6466:     if (defined($cached)) {
1.734     albertel 6467:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6468:     } else {  
                   6469:         $grouplist = '';
1.816     raeburn  6470:         my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  6471:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6472:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6473:         my $access_end = $env{'course.'.$courseid.
                   6474:                               '.default_enrollment_end_date'};
                   6475:         my $now = time;
                   6476:         foreach my $key (keys(%roleshash)) {
                   6477:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6478:                 my $group = $1;
                   6479:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6480:                     my $start = $2;
                   6481:                     my $end = $1;
                   6482:                     if ($start == -1) { next; } # deleted from group
                   6483:                     if (($start!=0) && ($start>$now)) { next; }
                   6484:                     if (($end!=0) && ($end<$now)) {
                   6485:                         if ($access_end && $access_end < $now) {
                   6486:                             if ($access_end - $end < 86400) {
                   6487:                                 push(@usersgroups,$group);
1.733     raeburn  6488:                             }
                   6489:                         }
1.817     raeburn  6490:                         next;
1.733     raeburn  6491:                     }
1.817     raeburn  6492:                     push(@usersgroups,$group);
1.683     raeburn  6493:                 }
                   6494:             }
                   6495:         }
1.817     raeburn  6496:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6497:         $grouplist = join(':',@usersgroups);
                   6498:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6499:     }
1.733     raeburn  6500:     return @usersgroups;
1.683     raeburn  6501: }
                   6502: 
                   6503: sub devalidate_getgroups_cache {
                   6504:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6505:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6506: 
1.683     raeburn  6507:     my $hashid="$udom:$uname:$courseid";
                   6508:     &devalidate_cache_new('getgroups',$hashid);
                   6509: }
                   6510: 
1.12      www      6511: # ------------------------------------------------------------------ Plain Text
                   6512: 
                   6513: sub plaintext {
1.988     raeburn  6514:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6515:     if ($short =~ m{^cr/}) {
1.758     albertel 6516: 	return (split('/',$short))[-1];
                   6517:     }
1.742     raeburn  6518:     if (!defined($cid)) {
                   6519:         $cid = $env{'request.course.id'};
                   6520:     }
                   6521:     my %rolenames = (
1.1008    raeburn  6522:                       Course    => 'std',
                   6523:                       Community => 'alt1',
1.742     raeburn  6524:                     );
1.1037    raeburn  6525:     if ($cid ne '') {
                   6526:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6527:             unless ($forcedefault) {
                   6528:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6529:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6530:                 return &Apache::lonlocal::mt($roletext);
                   6531:             }
                   6532:         }
                   6533:     }
                   6534:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6535:         (defined($rolenames{$type})) && 
                   6536:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6537:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6538:     } elsif ($cid ne '') {
                   6539:         my $crstype = $env{'course.'.$cid.'.type'};
                   6540:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6541:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6542:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6543:         }
1.742     raeburn  6544:     }
1.1037    raeburn  6545:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6546: }
                   6547: 
                   6548: # ----------------------------------------------------------------- Assign Role
                   6549: 
                   6550: sub assignrole {
1.957     raeburn  6551:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6552:         $context)=@_;
1.21      www      6553:     my $mrole;
                   6554:     if ($role =~ /^cr\//) {
1.393     www      6555:         my $cwosec=$url;
1.811     albertel 6556:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6557: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6558:            my $refused = 1;
                   6559:            if ($context eq 'requestcourses') {
                   6560:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6561:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6562:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6563:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6564:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6565:                            if ($crsenv{'internal.courseowner'} eq
                   6566:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6567:                                $refused = '';
                   6568:                            }
                   6569:                        }
                   6570:                    }
                   6571:                }
                   6572:            }
                   6573:            if ($refused) {
                   6574:                &logthis('Refused custom assignrole: '.
                   6575:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6576:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6577:                return 'refused';
                   6578:            }
1.104     www      6579:         }
1.21      www      6580:         $mrole='cr';
1.678     raeburn  6581:     } elsif ($role =~ /^gr\//) {
                   6582:         my $cwogrp=$url;
1.811     albertel 6583:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6584:         unless (&allowed('mdg',$cwogrp)) {
                   6585:             &logthis('Refused group assignrole: '.
                   6586:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6587:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6588:             return 'refused';
                   6589:         }
                   6590:         $mrole='gr';
1.21      www      6591:     } else {
1.82      www      6592:         my $cwosec=$url;
1.811     albertel 6593:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6594:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6595:             my $refused;
                   6596:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6597:                 if (!(&allowed('c'.$role,$url))) {
                   6598:                     $refused = 1;
                   6599:                 }
                   6600:             } else {
                   6601:                 $refused = 1;
                   6602:             }
1.947     raeburn  6603:             if ($refused) {
1.1045    raeburn  6604:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6605:                 if (!$selfenroll && $context eq 'course') {
                   6606:                     my %crsenv;
                   6607:                     if ($role eq 'cc' || $role eq 'co') {
                   6608:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6609:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6610:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6611:                                 if ($crsenv{'internal.courseowner'} eq 
                   6612:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6613:                                     $refused = '';
                   6614:                                 }
                   6615:                             }
                   6616:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6617:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6618:                                 if ($crsenv{'internal.courseowner'} eq 
                   6619:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6620:                                     $refused = '';
                   6621:                                 }
                   6622:                             }
                   6623:                         }
                   6624:                     }
                   6625:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6626:                     $refused = '';
1.1017    raeburn  6627:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6628:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6629:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6630:                         my $wrongcc;
                   6631:                         if ($cnum =~ /^$match_community$/) {
                   6632:                             $wrongcc = 1 if ($role eq 'cc');
                   6633:                         } else {
                   6634:                             $wrongcc = 1 if ($role eq 'co');
                   6635:                         }
                   6636:                         unless ($wrongcc) {
                   6637:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6638:                             if ($crsenv{'internal.courseowner'} eq 
                   6639:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6640:                                 $refused = '';
                   6641:                             }
1.1017    raeburn  6642:                         }
                   6643:                     }
                   6644:                 }
                   6645:                 if ($refused) {
1.947     raeburn  6646:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6647:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6648: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6649:                     return 'refused';
                   6650:                 }
1.932     raeburn  6651:             }
1.104     www      6652:         }
1.21      www      6653:         $mrole=$role;
                   6654:     }
1.620     albertel 6655:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6656:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6657:     if ($end) { $command.='_'.$end; }
1.21      www      6658:     if ($start) {
                   6659: 	if ($end) { 
1.81      www      6660:            $command.='_'.$start; 
1.21      www      6661:         } else {
1.81      www      6662:            $command.='_0_'.$start;
1.21      www      6663:         }
                   6664:     }
1.739     raeburn  6665:     my $origstart = $start;
                   6666:     my $origend = $end;
1.957     raeburn  6667:     my $delflag;
1.357     www      6668: # actually delete
                   6669:     if ($deleteflag) {
1.373     www      6670: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6671: # modify command to delete the role
1.620     albertel 6672:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6673:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6674: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6675: # set start and finish to negative values for userrolelog
                   6676:            $start=-1;
                   6677:            $end=-1;
1.957     raeburn  6678:            $delflag = 1;
1.357     www      6679:         }
                   6680:     }
                   6681: # send command
1.349     www      6682:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6683: # log new user role if status is ok
1.349     www      6684:     if ($answer eq 'ok') {
1.663     raeburn  6685: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6686: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6687:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6688:         unless ($role =~ /^gr/) {
                   6689:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6690:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6691:         }
1.1053    raeburn  6692:         if ($role eq 'cc') {
                   6693:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6694:         }
1.349     www      6695:     }
                   6696:     return $answer;
1.169     harris41 6697: }
                   6698: 
1.1053    raeburn  6699: sub autoupdate_coowners {
                   6700:     my ($url,$end,$start,$uname,$udom) = @_;
                   6701:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6702:     if (($cdom ne '') && ($cnum ne '')) {
                   6703:         my $now = time;
                   6704:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6705:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6706:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6707:             my $instcode = $coursehash{'internal.coursecode'};
                   6708:             if ($instcode ne '') {
1.1056    raeburn  6709:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6710:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6711:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6712:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6713:                         if ($result eq 'valid') {
                   6714:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6715:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6716:                                     push(@newcoowners,$coowner);
                   6717:                                 }
                   6718:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6719:                                     push(@newcoowners,$uname.':'.$udom);
                   6720:                                 }
                   6721:                                 @newcoowners = sort(@newcoowners);
                   6722:                             } else {
                   6723:                                 push(@newcoowners,$uname.':'.$udom);
                   6724:                             }
                   6725:                         } else {
                   6726:                             if ($coursehash{'internal.co-owners'}) {
                   6727:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6728:                                     unless ($coowner eq $uname.':'.$udom) {
                   6729:                                         push(@newcoowners,$coowner);
                   6730:                                     }
                   6731:                                 }
                   6732:                                 unless (@newcoowners > 0) {
                   6733:                                     $delcoowners = 1;
                   6734:                                     $coowners = '';
                   6735:                                 }
                   6736:                             }
                   6737:                         }
                   6738:                         if (@newcoowners || $delcoowners) {
                   6739:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6740:                                             $delcoowners,@newcoowners);
                   6741:                         }
                   6742:                     }
                   6743:                 }
                   6744:             }
                   6745:         }
                   6746:     }
                   6747: }
                   6748: 
                   6749: sub store_coowners {
                   6750:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6751:     my $cid = $cdom.'_'.$cnum;
                   6752:     my ($coowners,$delresult,$putresult);
                   6753:     if (@newcoowners) {
                   6754:         $coowners = join(',',@newcoowners);
                   6755:         my %coownershash = (
                   6756:                             'internal.co-owners' => $coowners,
                   6757:                            );
                   6758:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6759:         if ($putresult eq 'ok') {
                   6760:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6761:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6762:             }
                   6763:         }
                   6764:     }
                   6765:     if ($delcoowners) {
                   6766:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6767:         if ($delresult eq 'ok') {
                   6768:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6769:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6770:             }
                   6771:         }
                   6772:     }
                   6773:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6774:         my %crsinfo =
                   6775:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6776:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6777:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6778:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6779:         }
                   6780:     }
                   6781: }
                   6782: 
1.169     harris41 6783: # -------------------------------------------------- Modify user authentication
1.197     www      6784: # Overrides without validation
                   6785: 
1.169     harris41 6786: sub modifyuserauth {
                   6787:     my ($udom,$uname,$umode,$upass)=@_;
                   6788:     my $uhome=&homeserver($uname,$udom);
1.197     www      6789:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6790:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6791:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6792:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6793:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6794: 		     &escape($upass),$uhome);
1.620     albertel 6795:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6796:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6797:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6798:     &log($udom,,$uname,$uhome,
1.620     albertel 6799:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6800:                                      $env{'user.name'}.', '.$umode.
1.197     www      6801:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6802:     unless ($reply eq 'ok') {
1.197     www      6803:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6804: 	return 'error: '.$reply;
                   6805:     }   
1.170     harris41 6806:     return 'ok';
1.80      www      6807: }
                   6808: 
1.81      www      6809: # --------------------------------------------------------------- Modify a user
1.80      www      6810: 
1.81      www      6811: sub modifyuser {
1.206     matthew  6812:     my ($udom,    $uname, $uid,
                   6813:         $umode,   $upass, $first,
                   6814:         $middle,  $last,  $gene,
1.1056.4.1  raeburn  6815:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6816:     $udom= &LONCAPA::clean_domain($udom);
                   6817:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  raeburn  6818:     my $showcandelete = 'none';
                   6819:     if (ref($candelete) eq 'ARRAY') {
                   6820:         if (@{$candelete} > 0) {
                   6821:             $showcandelete = join(', ',@{$candelete});
                   6822:         }
                   6823:     }
1.81      www      6824:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6825:              $umode.', '.$first.', '.$middle.', '.
1.1056.4.1  raeburn  6826:              $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6827:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6828:                                      ' desiredhome not specified'). 
1.620     albertel 6829:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6830:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6831:     my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4  raeburn  6832:     my $newuser;
                   6833:     if ($uhome eq 'no_host') {
                   6834:         $newuser = 1;
                   6835:     }
1.80      www      6836: # ----------------------------------------------------------------- Create User
1.406     albertel 6837:     if (($uhome eq 'no_host') && 
                   6838: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6839:         my $unhome='';
1.844     albertel 6840:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6841:             $unhome = $desiredhome;
1.620     albertel 6842: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6843: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6844:         } else { # load balancing routine for determining $unhome
1.81      www      6845:             my $loadm=10000000;
1.841     albertel 6846: 	    my %servers = &get_servers($udom,'library');
                   6847: 	    foreach my $tryserver (keys(%servers)) {
                   6848: 		my $answer=reply('load',$tryserver);
                   6849: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6850: 		    $loadm=$answer;
                   6851: 		    $unhome=$tryserver;
                   6852: 		}
1.80      www      6853: 	    }
                   6854:         }
                   6855:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6856: 	    return 'error: unable to find a home server for '.$uname.
                   6857:                    ' in domain '.$udom;
1.80      www      6858:         }
                   6859:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6860:                          &escape($upass),$unhome);
                   6861: 	unless ($reply eq 'ok') {
                   6862:             return 'error: '.$reply;
                   6863:         }   
1.230     stredwic 6864:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6865:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6866: 	    return 'error: unable verify users home machine.';
1.80      www      6867:         }
1.209     matthew  6868:     }   # End of creation of new user
1.80      www      6869: # ---------------------------------------------------------------------- Add ID
                   6870:     if ($uid) {
                   6871:        $uid=~tr/A-Z/a-z/;
                   6872:        my %uidhash=&idrget($udom,$uname);
1.196     www      6873:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6874:          && (!$forceid)) {
1.80      www      6875: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6876: 	      return 'error: user id "'.$uid.'" does not match '.
                   6877:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6878:           }
                   6879:        } else {
                   6880: 	  &idput($udom,($uname => $uid));
                   6881:        }
                   6882:     }
                   6883: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6884:     my @tmp=&get('environment',
1.899     raeburn  6885: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6886:                     'permanentemail','inststatus'],
1.134     albertel 6887: 		   $udom,$uname);
1.1056.4.4  raeburn  6888:     my (%names,%oldnames);
1.313     matthew  6889:     if ($tmp[0] =~ m/^error:.*/) { 
                   6890:         %names=(); 
                   6891:     } else {
                   6892:         %names = @tmp;
1.1056.4.4  raeburn  6893:         %oldnames = %names;
1.313     matthew  6894:     }
1.1056.4.6  raeburn  6895: #
1.1056.4.1  raeburn  6896: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6897: # of users did not contain them), do not overwrite existing values
                   6898: # unless field is in $candelete array ref.  
                   6899: #
                   6900: 
                   6901:     my @fields = ('firstname','middlename','lastname','generation',
                   6902:                   'permanentemail','id');
                   6903:     my %newvalues;
                   6904:     if (ref($candelete) eq 'ARRAY') {
                   6905:         foreach my $field (@fields) {
                   6906:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6907:                 if ($field eq 'firstname') {
                   6908:                     $names{$field} = $first;
                   6909:                 } elsif ($field eq 'middlename') {
                   6910:                     $names{$field} = $middle;
                   6911:                 } elsif ($field eq 'lastname') {
                   6912:                     $names{$field} = $last;
                   6913:                 } elsif ($field eq 'generation') { 
                   6914:                     $names{$field} = $gene;
                   6915:                 } elsif ($field eq 'permanentemail') {
                   6916:                     $names{$field} = $email;
                   6917:                 } elsif ($field eq 'id') {
                   6918:                     $names{$field}  = $uid;
                   6919:                 }
                   6920:             }
                   6921:         }
                   6922:     }
1.388     www      6923:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6924:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6925:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6926:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6927:     if ($email) {
                   6928:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6929:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6930:     }
1.899     raeburn  6931:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6932:     if (defined($inststatus)) {
                   6933:         $names{'inststatus'} = '';
                   6934:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6935:         if (ref($usertypes) eq 'HASH') {
                   6936:             my @okstatuses; 
                   6937:             foreach my $item (split(/:/,$inststatus)) {
                   6938:                 if (defined($usertypes->{$item})) {
                   6939:                     push(@okstatuses,$item);  
                   6940:                 }
                   6941:             }
                   6942:             if (@okstatuses) {
                   6943:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6944:             }
                   6945:         }
                   6946:     }
1.1056.4.4  raeburn  6947:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6948:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  raeburn  6949:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6950:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6951:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6952:     } else {
                   6953:         $logmsg .= ' during self creation';
                   6954:     }
1.1056.4.4  raeburn  6955:     my $changed;
                   6956:     if ($newuser) {
                   6957:         $changed = 1;
                   6958:     } else {
                   6959:         foreach my $field (@fields) {
                   6960:             if ($names{$field} ne $oldnames{$field}) {
                   6961:                 $changed = 1;
                   6962:                 last;
                   6963:             }
                   6964:         }
                   6965:     }
                   6966:     unless ($changed) {
                   6967:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6968:         &logthis($logmsg);
                   6969:         return 'ok';
                   6970:     }
                   6971:     my $reply = &put('environment', \%names, $udom,$uname);
                   6972:     if ($reply ne 'ok') {
                   6973:         return 'error: '.$reply;
                   6974:     }
1.1056.4.11  raeburn  6975:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   6976:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   6977:     }
1.1056.4.4  raeburn  6978:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6979:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6980:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6981:     &logthis($logmsg);
1.134     albertel 6982:     return 'ok';
1.80      www      6983: }
                   6984: 
1.81      www      6985: # -------------------------------------------------------------- Modify student
1.80      www      6986: 
1.81      www      6987: sub modifystudent {
                   6988:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6989:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6990:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6991:     if (!$cid) {
1.620     albertel 6992: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6993: 	    return 'not_in_class';
                   6994: 	}
1.80      www      6995:     }
                   6996: # --------------------------------------------------------------- Make the user
1.81      www      6997:     my $reply=&modifyuser
1.209     matthew  6998: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6999:          $desiredhome,$email,$inststatus);
1.80      www      7000:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7001:     # This will cause &modify_student_enrollment to get the uid from the
                   7002:     # students environment
                   7003:     $uid = undef if (!$forceid);
1.455     albertel 7004:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7005: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7006:     return $reply;
                   7007: }
                   7008: 
                   7009: sub modify_student_enrollment {
1.957     raeburn  7010:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7011:     my ($cdom,$cnum,$chome);
                   7012:     if (!$cid) {
1.620     albertel 7013: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7014: 	    return 'not_in_class';
                   7015: 	}
1.620     albertel 7016: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7017: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7018:     } else {
                   7019: 	($cdom,$cnum)=split(/_/,$cid);
                   7020:     }
1.620     albertel 7021:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7022:     if (!$chome) {
1.457     raeburn  7023: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7024:     }
1.455     albertel 7025:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7026:     # Make sure the user exists
1.81      www      7027:     my $uhome=&homeserver($uname,$udom);
                   7028:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7029: 	return 'error: no such user';
                   7030:     }
1.297     matthew  7031:     # Get student data if we were not given enough information
                   7032:     if (!defined($first)  || $first  eq '' || 
                   7033:         !defined($last)   || $last   eq '' || 
                   7034:         !defined($uid)    || $uid    eq '' || 
                   7035:         !defined($middle) || $middle eq '' || 
                   7036:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7037:         # They did not supply us with enough data to enroll the student, so
                   7038:         # we need to pick up more information.
1.297     matthew  7039:         my %tmp = &get('environment',
1.294     matthew  7040:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7041:                        ,$udom,$uname);
                   7042: 
1.800     albertel 7043:         #foreach my $key (keys(%tmp)) {
                   7044:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7045:         #}
1.294     matthew  7046:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7047:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7048:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7049:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7050:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7051:     }
1.556     albertel 7052:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7053:     my $reply=cput('classlist',
                   7054: 		   {"$uname:$udom" => 
1.515     raeburn  7055: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7056: 		   $cdom,$cnum);
1.81      www      7057:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7058: 	return 'error: '.$reply;
1.652     albertel 7059:     } else {
                   7060: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7061:     }
1.297     matthew  7062:     # Add student role to user
1.83      www      7063:     my $uurl='/'.$cid;
1.81      www      7064:     $uurl=~s/\_/\//g;
                   7065:     if ($usec) {
                   7066: 	$uurl.='/'.$usec;
                   7067:     }
1.957     raeburn  7068:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7069: }
                   7070: 
1.556     albertel 7071: sub format_name {
                   7072:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7073:     my $name;
                   7074:     if ($first ne 'lastname') {
                   7075: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7076:     } else {
                   7077: 	if ($lastname=~/\S/) {
                   7078: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7079: 	    $name=~s/\s+,/,/;
                   7080: 	} else {
                   7081: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7082: 	}
                   7083:     }
                   7084:     $name=~s/^\s+//;
                   7085:     $name=~s/\s+$//;
                   7086:     $name=~s/\s+/ /g;
                   7087:     return $name;
                   7088: }
                   7089: 
1.84      www      7090: # ------------------------------------------------- Write to course preferences
                   7091: 
                   7092: sub writecoursepref {
                   7093:     my ($courseid,%prefs)=@_;
                   7094:     $courseid=~s/^\///;
                   7095:     $courseid=~s/\_/\//g;
                   7096:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7097:     my $chome=homeserver($cnum,$cdomain);
                   7098:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7099: 	return 'error: no such course';
                   7100:     }
                   7101:     my $cstring='';
1.800     albertel 7102:     foreach my $pref (keys(%prefs)) {
                   7103: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7104:     }
1.84      www      7105:     $cstring=~s/\&$//;
                   7106:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7107: }
                   7108: 
                   7109: # ---------------------------------------------------------- Make/modify course
                   7110: 
                   7111: sub createcourse {
1.741     raeburn  7112:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7113:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7114:     $url=&declutter($url);
                   7115:     my $cid='';
1.1028    raeburn  7116:     if ($context eq 'requestcourses') {
                   7117:         my $can_create = 0;
                   7118:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7119:         if ($udom eq $ownerdom) {
                   7120:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7121:                                   $context)) {
                   7122:                 $can_create = 1;
                   7123:             }
                   7124:         } else {
                   7125:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7126:                                            $category);
                   7127:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7128:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7129:                 if (@curr > 0) {
                   7130:                     my @options = qw(approval validate autolimit);
                   7131:                     my $optregex = join('|',@options);
                   7132:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7133:                         $can_create = 1;
                   7134:                     }
                   7135:                 }
                   7136:             }
                   7137:         }
                   7138:         if ($can_create) {
                   7139:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7140:                 unless (&allowed('ccc',$udom)) {
                   7141:                     return 'refused'; 
                   7142:                 }
1.1017    raeburn  7143:             }
                   7144:         } else {
                   7145:             return 'refused';
                   7146:         }
1.1028    raeburn  7147:     } elsif (!&allowed('ccc',$udom)) {
                   7148:         return 'refused';
1.84      www      7149:     }
1.1011    raeburn  7150: # --------------------------------------------------------------- Get Unique ID
                   7151:     my $uname;
                   7152:     if ($cnum =~ /^$match_courseid$/) {
                   7153:         my $chome=&homeserver($cnum,$udom,'true');
                   7154:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7155:             $uname = $cnum;
                   7156:         } else {
1.1038    raeburn  7157:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7158:         }
                   7159:     } else {
1.1038    raeburn  7160:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7161:     }
                   7162:     return $uname if ($uname =~ /^error/);
                   7163: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7164:     if (!defined($course_server)) {
                   7165:         if (defined(&domain($udom,'primary'))) {
                   7166:             $course_server = &domain($udom,'primary');
                   7167:         } else {
                   7168:             $course_server = $env{'user.home'}; 
                   7169:         }
                   7170:     }
                   7171:     my %host_servers =
                   7172:         &Apache::lonnet::get_servers($udom,'library');
                   7173:     unless ($host_servers{$course_server}) {
                   7174:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7175:     }
1.84      www      7176: # ------------------------------------------------------------- Make the course
                   7177:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7178:                       $course_server);
1.84      www      7179:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7180:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7181:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7182: 	return 'error: no such course';
                   7183:     }
1.271     www      7184: # ----------------------------------------------------------------- Course made
1.516     raeburn  7185: # log existence
1.1029    raeburn  7186:     my $now = time;
1.918     raeburn  7187:     my $newcourse = {
                   7188:                     $udom.'_'.$uname => {
1.921     raeburn  7189:                                      description => $description,
                   7190:                                      inst_code   => $inst_code,
                   7191:                                      owner       => $course_owner,
                   7192:                                      type        => $crstype,
1.1029    raeburn  7193:                                      creator     => $env{'user.name'}.':'.
                   7194:                                                     $env{'user.domain'},
                   7195:                                      created     => $now,
                   7196:                                      context     => $context,
1.918     raeburn  7197:                                                 },
                   7198:                     };
1.921     raeburn  7199:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7200: # set toplevel url
1.271     www      7201:     my $topurl=$url;
                   7202:     unless ($nonstandard) {
                   7203: # ------------------------------------------ For standard courses, make top url
                   7204:         my $mapurl=&clutter($url);
1.278     www      7205:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7206:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7207: <map>
                   7208: <resource id="1" type="start"></resource>
                   7209: <resource id="2" src="$mapurl"></resource>
                   7210: <resource id="3" type="finish"></resource>
                   7211: <link index="1" from="1" to="2"></link>
                   7212: <link index="2" from="2" to="3"></link>
                   7213: </map>
                   7214: ENDINITMAP
                   7215:         $topurl=&declutter(
1.638     albertel 7216:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7217:                           );
                   7218:     }
                   7219: # ----------------------------------------------------------- Write preferences
1.84      www      7220:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7221:                      ('description'              => $description,
                   7222:                       'url'                      => $topurl,
                   7223:                       'internal.creator'         => $env{'user.name'}.':'.
                   7224:                                                     $env{'user.domain'},
                   7225:                       'internal.created'         => $now,
                   7226:                       'internal.creationcontext' => $context)
                   7227:                     );
1.84      www      7228:     return '/'.$udom.'/'.$uname;
                   7229: }
                   7230: 
1.1011    raeburn  7231: # ------------------------------------------------------------------- Create ID
                   7232: sub generate_coursenum {
1.1038    raeburn  7233:     my ($udom,$crstype) = @_;
1.1011    raeburn  7234:     my $domdesc = &domain($udom);
                   7235:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7236:     my $first;
                   7237:     if ($crstype eq 'Community') {
                   7238:         $first = '0';
                   7239:     } else {
                   7240:         $first = int(1+rand(9)); 
                   7241:     } 
                   7242:     my $uname=$first.
1.1011    raeburn  7243:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7244:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7245:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7246: # ----------------------------------------------- Make sure that does not exist
                   7247:     my $uhome=&homeserver($uname,$udom,'true');
                   7248:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7249:         if ($crstype eq 'Community') {
                   7250:             $first = '0';
                   7251:         } else {
                   7252:             $first = int(1+rand(9));
                   7253:         }
                   7254:         $uname=$first.
1.1011    raeburn  7255:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7256:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7257:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7258:         $uhome=&homeserver($uname,$udom,'true');
                   7259:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7260:             return 'error: unable to generate unique course-ID';
                   7261:         }
                   7262:     }
                   7263:     return $uname;
                   7264: }
                   7265: 
1.813     albertel 7266: sub is_course {
                   7267:     my ($cdom,$cnum) = @_;
                   7268:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7269: 				undef,'.');
1.813     albertel 7270:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7271:         return 1;
                   7272:     }
                   7273:     return 0;
                   7274: }
                   7275: 
1.1015    raeburn  7276: sub store_userdata {
                   7277:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7278:     my $result;
1.1016    raeburn  7279:     if ($datakey ne '') {
1.1013    raeburn  7280:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7281:             if ($udom eq '' || $uname eq '') {
                   7282:                 $udom = $env{'user.domain'};
                   7283:                 $uname = $env{'user.name'};
                   7284:             }
                   7285:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7286:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7287:                 $result = 'error: no_host';
                   7288:             } else {
                   7289:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7290:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7291: 
                   7292:                 my $namevalue='';
                   7293:                 foreach my $key (keys(%{$storehash})) {
                   7294:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7295:                 }
                   7296:                 $namevalue=~s/\&$//;
                   7297:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7298:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7299:             }
                   7300:         } else {
                   7301:             $result = 'error: data to store was not a hash reference'; 
                   7302:         }
                   7303:     } else {
                   7304:         $result= 'error: invalid requestkey'; 
                   7305:     }
                   7306:     return $result;
                   7307: }
                   7308: 
1.21      www      7309: # ---------------------------------------------------------- Assign Custom Role
                   7310: 
                   7311: sub assigncustomrole {
1.957     raeburn  7312:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7313:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7314:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7315: }
                   7316: 
                   7317: # ----------------------------------------------------------------- Revoke Role
                   7318: 
                   7319: sub revokerole {
1.957     raeburn  7320:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7321:     my $now=time;
1.965     raeburn  7322:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7323: }
                   7324: 
                   7325: # ---------------------------------------------------------- Revoke Custom Role
                   7326: 
                   7327: sub revokecustomrole {
1.957     raeburn  7328:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7329:     my $now=time;
1.357     www      7330:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7331:            $deleteflag,$selfenroll,$context);
1.17      www      7332: }
                   7333: 
1.533     banghart 7334: # ------------------------------------------------------------ Disk usage
1.535     albertel 7335: sub diskusage {
1.955     raeburn  7336:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7337:     $directorypath =~ s/\/$//;
                   7338:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7339:                        .&escape($getpropath).':'.&escape($uname).':'
                   7340:                        .&escape($udom),homeserver($uname,$udom));
                   7341:     if ($listing eq 'unknown_cmd') {
                   7342:         if ($getpropath) {
                   7343:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7344:         }
                   7345:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7346:     }
1.514     albertel 7347:     return $listing;
1.512     banghart 7348: }
                   7349: 
1.566     banghart 7350: sub is_locked {
                   7351:     my ($file_name, $domain, $user) = @_;
                   7352:     my @check;
                   7353:     my $is_locked;
                   7354:     push @check, $file_name;
1.613     albertel 7355:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7356: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7357:     my ($tmp)=keys(%locked);
                   7358:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7359:     
1.566     banghart 7360:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7361:         $is_locked = 'false';
                   7362:         foreach my $entry (@{$locked{$file_name}}) {
                   7363:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7364:                $is_locked = 'true';
                   7365:                last;
1.745     raeburn  7366:            }
                   7367:        }
1.566     banghart 7368:     } else {
                   7369:         $is_locked = 'false';
                   7370:     }
                   7371: }
                   7372: 
1.759     albertel 7373: sub declutter_portfile {
                   7374:     my ($file) = @_;
1.833     albertel 7375:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7376:     return $file;
                   7377: }
                   7378: 
1.559     banghart 7379: # ------------------------------------------------------------- Mark as Read Only
                   7380: 
                   7381: sub mark_as_readonly {
                   7382:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7383:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7384:     my ($tmp)=keys(%current_permissions);
                   7385:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7386:     foreach my $file (@{$files}) {
1.759     albertel 7387: 	$file = &declutter_portfile($file);
1.561     banghart 7388:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7389:     }
1.613     albertel 7390:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7391:     return;
                   7392: }
                   7393: 
1.572     banghart 7394: # ------------------------------------------------------------Save Selected Files
                   7395: 
                   7396: sub save_selected_files {
                   7397:     my ($user, $path, @files) = @_;
                   7398:     my $filename = $user."savedfiles";
1.573     banghart 7399:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7400:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7401:     foreach my $file (@files) {
1.620     albertel 7402:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7403:     }
                   7404:     foreach my $file (@other_files) {
1.574     banghart 7405:         print (OUT $file."\n");
1.572     banghart 7406:     }
1.574     banghart 7407:     close (OUT);
1.572     banghart 7408:     return 'ok';
                   7409: }
                   7410: 
1.574     banghart 7411: sub clear_selected_files {
                   7412:     my ($user) = @_;
                   7413:     my $filename = $user."savedfiles";
                   7414:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7415:     print (OUT undef);
                   7416:     close (OUT);
                   7417:     return ("ok");    
                   7418: }
                   7419: 
1.572     banghart 7420: sub files_in_path {
                   7421:     my ($user, $path) = @_;
                   7422:     my $filename = $user."savedfiles";
                   7423:     my %return_files;
1.574     banghart 7424:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7425:     while (my $line_in = <IN>) {
1.574     banghart 7426:         chomp ($line_in);
                   7427:         my @paths_and_file = split (m!/!, $line_in);
                   7428:         my $file_part = pop (@paths_and_file);
                   7429:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7430:         $path_part.='/';
                   7431:         my $path_and_file = $path_part.$file_part;
                   7432:         if ($path_part eq $path) {
                   7433:             $return_files{$file_part}= 'selected';
                   7434:         }
                   7435:     }
1.574     banghart 7436:     close (IN);
                   7437:     return (\%return_files);
1.572     banghart 7438: }
                   7439: 
                   7440: # called in portfolio select mode, to show files selected NOT in current directory
                   7441: sub files_not_in_path {
                   7442:     my ($user, $path) = @_;
                   7443:     my $filename = $user."savedfiles";
                   7444:     my @return_files;
                   7445:     my $path_part;
1.800     albertel 7446:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7447:     while (my $line = <IN>) {
1.572     banghart 7448:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7449:         my @paths_and_file = split(m|/|, $line);
                   7450:         my $file_part = pop(@paths_and_file);
                   7451:         chomp($file_part);
                   7452:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7453:         $path_part .= '/';
                   7454:         my $path_and_file = $path_part.$file_part;
                   7455:         if ($path_part ne $path) {
1.800     albertel 7456:             push(@return_files, ($path_and_file));
1.572     banghart 7457:         }
                   7458:     }
1.800     albertel 7459:     close(OUT);
1.574     banghart 7460:     return (@return_files);
1.572     banghart 7461: }
                   7462: 
1.745     raeburn  7463: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7464: 
1.745     raeburn  7465: sub get_portfile_permissions {
                   7466:     my ($domain,$user) = @_;
1.613     albertel 7467:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7468:     my ($tmp)=keys(%current_permissions);
                   7469:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7470:     return \%current_permissions;
                   7471: }
                   7472: 
                   7473: #---------------------------------------------Get portfolio file access controls
                   7474: 
1.749     raeburn  7475: sub get_access_controls {
1.745     raeburn  7476:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7477:     my %access;
                   7478:     my $real_file = $file;
                   7479:     $file =~ s/\.meta$//;
1.745     raeburn  7480:     if (defined($file)) {
1.749     raeburn  7481:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7482:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7483:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7484:             }
                   7485:         }
1.745     raeburn  7486:     } else {
1.749     raeburn  7487:         foreach my $key (keys(%{$current_permissions})) {
                   7488:             if ($key =~ /\0accesscontrol$/) {
                   7489:                 if (defined($group)) {
                   7490:                     if ($key !~ m-^\Q$group\E/-) {
                   7491:                         next;
                   7492:                     }
                   7493:                 }
                   7494:                 my ($fullpath) = split(/\0/,$key);
                   7495:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7496:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7497:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7498:                     }
                   7499:                 }
                   7500:             }
                   7501:         }
                   7502:     }
                   7503:     return %access;
                   7504: }
                   7505: 
                   7506: sub modify_access_controls {
                   7507:     my ($file_name,$changes,$domain,$user)=@_;
                   7508:     my ($outcome,$deloutcome);
                   7509:     my %store_permissions;
                   7510:     my %new_values;
                   7511:     my %new_control;
                   7512:     my %translation;
                   7513:     my @deletions = ();
                   7514:     my $now = time;
                   7515:     if (exists($$changes{'activate'})) {
                   7516:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7517:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7518:             my $numnew = scalar(@newitems);
                   7519:             for (my $i=0; $i<$numnew; $i++) {
                   7520:                 my $newkey = $newitems[$i];
                   7521:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7522:                 if ($newkey =~ /^\d+:/) { 
                   7523:                     $newkey =~ s/^(\d+)/$newid/;
                   7524:                     $translation{$1} = $newid;
                   7525:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7526:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7527:                     $translation{$1} = $newid;
                   7528:                 }
1.749     raeburn  7529:                 $new_values{$file_name."\0".$newkey} = 
                   7530:                                           $$changes{'activate'}{$newitems[$i]};
                   7531:                 $new_control{$newkey} = $now;
                   7532:             }
                   7533:         }
                   7534:     }
                   7535:     my %todelete;
                   7536:     my %changed_items;
                   7537:     foreach my $action ('delete','update') {
                   7538:         if (exists($$changes{$action})) {
                   7539:             if (ref($$changes{$action}) eq 'HASH') {
                   7540:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7541:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7542:                     if ($action eq 'delete') { 
                   7543:                         $todelete{$itemnum} = 1;
                   7544:                     } else {
                   7545:                         $changed_items{$itemnum} = $key;
                   7546:                     }
                   7547:                 }
1.745     raeburn  7548:             }
                   7549:         }
1.749     raeburn  7550:     }
                   7551:     # get lock on access controls for file.
                   7552:     my $lockhash = {
                   7553:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7554:                                                        ':'.$env{'user.domain'},
                   7555:                    }; 
                   7556:     my $tries = 0;
                   7557:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7558:    
                   7559:     while (($gotlock ne 'ok') && $tries <3) {
                   7560:         $tries ++;
                   7561:         sleep 1;
                   7562:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7563:     }
                   7564:     if ($gotlock eq 'ok') {
                   7565:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7566:         my ($tmp)=keys(%curr_permissions);
                   7567:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7568:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7569:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7570:             if (ref($curr_controls) eq 'HASH') {
                   7571:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7572:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7573:                     if (defined($todelete{$itemnum})) {
                   7574:                         push(@deletions,$file_name."\0".$control_item);
                   7575:                     } else {
                   7576:                         if (defined($changed_items{$itemnum})) {
                   7577:                             $new_control{$changed_items{$itemnum}} = $now;
                   7578:                             push(@deletions,$file_name."\0".$control_item);
                   7579:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7580:                         } else {
                   7581:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7582:                         }
                   7583:                     }
1.745     raeburn  7584:                 }
                   7585:             }
                   7586:         }
1.970     raeburn  7587:         my ($group);
                   7588:         if (&is_course($domain,$user)) {
                   7589:             ($group,my $file) = split(/\//,$file_name,2);
                   7590:         }
1.749     raeburn  7591:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7592:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7593:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7594:         #  remove lock
                   7595:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7596:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7597:         my $sqlresult =
1.970     raeburn  7598:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7599:                                     $group);
1.749     raeburn  7600:     } else {
                   7601:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7602:     }
1.749     raeburn  7603:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7604: }
                   7605: 
1.827     raeburn  7606: sub make_public_indefinitely {
                   7607:     my ($requrl) = @_;
                   7608:     my $now = time;
                   7609:     my $action = 'activate';
                   7610:     my $aclnum = 0;
                   7611:     if (&is_portfolio_url($requrl)) {
                   7612:         my (undef,$udom,$unum,$file_name,$group) =
                   7613:             &parse_portfolio_url($requrl);
                   7614:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7615:         my %access_controls = &get_access_controls($current_perms,
                   7616:                                                    $group,$file_name);
                   7617:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7618:             my ($num,$scope,$end,$start) = 
                   7619:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7620:             if ($scope eq 'public') {
                   7621:                 if ($start <= $now && $end == 0) {
                   7622:                     $action = 'none';
                   7623:                 } else {
                   7624:                     $action = 'update';
                   7625:                     $aclnum = $num;
                   7626:                 }
                   7627:                 last;
                   7628:             }
                   7629:         }
                   7630:         if ($action eq 'none') {
                   7631:              return 'ok';
                   7632:         } else {
                   7633:             my %changes;
                   7634:             my $newend = 0;
                   7635:             my $newstart = $now;
                   7636:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7637:             $changes{$action}{$newkey} = {
                   7638:                 type => 'public',
                   7639:                 time => {
                   7640:                     start => $newstart,
                   7641:                     end   => $newend,
                   7642:                 },
                   7643:             };
                   7644:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7645:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7646:             return $outcome;
                   7647:         }
                   7648:     } else {
                   7649:         return 'invalid';
                   7650:     }
                   7651: }
                   7652: 
1.745     raeburn  7653: #------------------------------------------------------Get Marked as Read Only
                   7654: 
                   7655: sub get_marked_as_readonly {
                   7656:     my ($domain,$user,$what,$group) = @_;
                   7657:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7658:     my @readonly_files;
1.629     banghart 7659:     my $cmp1=$what;
                   7660:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7661:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7662:         if (defined($group)) {
                   7663:             if ($file_name !~ m-^\Q$group\E/-) {
                   7664:                 next;
                   7665:             }
                   7666:         }
1.561     banghart 7667:         if (ref($value) eq "ARRAY"){
                   7668:             foreach my $stored_what (@{$value}) {
1.629     banghart 7669:                 my $cmp2=$stored_what;
1.759     albertel 7670:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7671:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7672:                 }
1.629     banghart 7673:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7674:                     push(@readonly_files, $file_name);
1.745     raeburn  7675:                     last;
1.563     banghart 7676:                 } elsif (!defined($what)) {
                   7677:                     push(@readonly_files, $file_name);
1.745     raeburn  7678:                     last;
1.561     banghart 7679:                 }
                   7680:             }
1.745     raeburn  7681:         }
1.561     banghart 7682:     }
                   7683:     return @readonly_files;
                   7684: }
1.577     banghart 7685: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7686: 
1.577     banghart 7687: sub get_marked_as_readonly_hash {
1.745     raeburn  7688:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7689:     my %readonly_files;
1.745     raeburn  7690:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7691:         if (defined($group)) {
                   7692:             if ($file_name !~ m-^\Q$group\E/-) {
                   7693:                 next;
                   7694:             }
                   7695:         }
1.577     banghart 7696:         if (ref($value) eq "ARRAY"){
                   7697:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7698:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7699:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7700:                         if ($lock_descriptor eq 'graded') {
                   7701:                             $readonly_files{$file_name} = 'graded';
                   7702:                         } elsif ($lock_descriptor eq 'handback') {
                   7703:                             $readonly_files{$file_name} = 'handback';
                   7704:                         } else {
                   7705:                             if (!exists($readonly_files{$file_name})) {
                   7706:                                 $readonly_files{$file_name} = 'locked';
                   7707:                             }
                   7708:                         }
1.745     raeburn  7709:                     }
1.750     banghart 7710:                 } 
1.577     banghart 7711:             }
                   7712:         } 
                   7713:     }
                   7714:     return %readonly_files;
                   7715: }
1.559     banghart 7716: # ------------------------------------------------------------ Unmark as Read Only
                   7717: 
                   7718: sub unmark_as_readonly {
1.629     banghart 7719:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7720:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7721:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7722:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7723:     my $symb_crs = $what;
                   7724:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7725:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7726:     my ($tmp)=keys(%current_permissions);
                   7727:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7728:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7729:     foreach my $file (@readonly_files) {
1.759     albertel 7730: 	my $clean_file = &declutter_portfile($file);
                   7731: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7732: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7733:         my @new_locks;
                   7734:         my @del_keys;
                   7735:         if (ref($current_locks) eq "ARRAY"){
                   7736:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7737:                 my $compare=$locker;
1.749     raeburn  7738:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7739:                     $compare=join('',@{$locker});
1.746     raeburn  7740:                     if ($compare ne $symb_crs) {
                   7741:                         push(@new_locks, $locker);
                   7742:                     }
1.563     banghart 7743:                 }
                   7744:             }
1.650     albertel 7745:             if (scalar(@new_locks) > 0) {
1.563     banghart 7746:                 $current_permissions{$file} = \@new_locks;
                   7747:             } else {
                   7748:                 push(@del_keys, $file);
1.613     albertel 7749:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7750:                 delete($current_permissions{$file});
1.563     banghart 7751:             }
                   7752:         }
1.561     banghart 7753:     }
1.613     albertel 7754:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7755:     return;
                   7756: }
1.512     banghart 7757: 
1.17      www      7758: # ------------------------------------------------------------ Directory lister
                   7759: 
                   7760: sub dirlist {
1.955     raeburn  7761:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7762:     $uri=~s/^\///;
                   7763:     $uri=~s/\/$//;
1.253     stredwic 7764:     my ($udom, $uname);
1.955     raeburn  7765:     if ($getuserdir) {
1.253     stredwic 7766:         $udom = $userdomain;
                   7767:         $uname = $username;
1.955     raeburn  7768:     } else {
                   7769:         (undef,$udom,$uname)=split(/\//,$uri);
                   7770:         if(defined($userdomain)) {
                   7771:             $udom = $userdomain;
                   7772:         }
                   7773:         if(defined($username)) {
                   7774:             $uname = $username;
                   7775:         }
1.253     stredwic 7776:     }
1.955     raeburn  7777:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7778: 
1.955     raeburn  7779:     $dirRoot = $perlvar{'lonDocRoot'};
                   7780:     if (defined($getpropath)) {
                   7781:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7782:         $dirRoot =~ s/\/$//;
1.955     raeburn  7783:     } elsif (defined($getuserdir)) {
                   7784:         my $subdir=$uname.'__';
                   7785:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7786:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7787:                    ."/$udom/$subdir/$uname";
                   7788:     } elsif (defined($alternateRoot)) {
                   7789:         $dirRoot = $alternateRoot;
1.751     banghart 7790:     }
1.253     stredwic 7791: 
                   7792:     if($udom) {
                   7793:         if($uname) {
1.955     raeburn  7794:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7795:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7796:                               .':'.&escape($uname).':'.&escape($udom),
                   7797:                               &homeserver($uname,$udom));
                   7798:             if ($listing eq 'unknown_cmd') {
                   7799:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7800:                                   &homeserver($uname,$udom));
                   7801:             } else {
                   7802:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7803:             }
1.605     matthew  7804:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7805:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7806: 				  &homeserver($uname,$udom));
1.605     matthew  7807:                 @listing_results = split(/:/,$listing);
                   7808:             } else {
                   7809:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7810:             }
                   7811:             return @listing_results;
1.955     raeburn  7812:         } elsif(!$alternateRoot) {
1.800     albertel 7813:             my %allusers;
1.841     albertel 7814: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7815:  	    foreach my $tryserver (keys(%servers)) {
                   7816:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7817:                                   &escape($udom),$tryserver);
                   7818:                 if ($listing eq 'unknown_cmd') {
                   7819: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7820: 				      $udom, $tryserver);
                   7821:                 } else {
                   7822:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7823:                 }
1.841     albertel 7824: 		if ($listing eq 'unknown_cmd') {
                   7825: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7826: 				      $udom, $tryserver);
                   7827: 		    @listing_results = split(/:/,$listing);
                   7828: 		} else {
                   7829: 		    @listing_results =
                   7830: 			map { &unescape($_); } split(/:/,$listing);
                   7831: 		}
                   7832: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7833: 		    $listing_results[0] ne 'empty'       &&
                   7834: 		    $listing_results[0] ne 'con_lost') {
                   7835: 		    foreach my $line (@listing_results) {
                   7836: 			my ($entry) = split(/&/,$line,2);
                   7837: 			$allusers{$entry} = 1;
                   7838: 		    }
                   7839: 		}
1.253     stredwic 7840:             }
                   7841:             my $alluserstr='';
1.800     albertel 7842:             foreach my $user (sort(keys(%allusers))) {
                   7843:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7844:             }
                   7845:             $alluserstr=~s/:$//;
                   7846:             return split(/:/,$alluserstr);
                   7847:         } else {
1.800     albertel 7848:             return ('missing user name');
1.253     stredwic 7849:         }
1.955     raeburn  7850:     } elsif(!defined($getpropath)) {
1.841     albertel 7851:         my @all_domains = sort(&all_domains());
1.955     raeburn  7852:         foreach my $domain (@all_domains) {
                   7853:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7854:         }
                   7855:         return @all_domains;
                   7856:     } else {
1.800     albertel 7857:         return ('missing domain');
1.275     stredwic 7858:     }
                   7859: }
                   7860: 
                   7861: # --------------------------------------------- GetFileTimestamp
                   7862: # This function utilizes dirlist and returns the date stamp for
                   7863: # when it was last modified.  It will also return an error of -1
                   7864: # if an error occurs
                   7865: 
                   7866: sub GetFileTimestamp {
1.955     raeburn  7867:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7868:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7869:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7870:     my ($fileStat) = 
                   7871:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7872:                                  undef,$getuserdir);
1.275     stredwic 7873:     my @stats = split('&', $fileStat);
                   7874:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7875:         # @stats contains first the filename, then the stat output
                   7876:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7877:     } else {
                   7878:         return -1;
1.253     stredwic 7879:     }
1.26      www      7880: }
                   7881: 
1.712     albertel 7882: sub stat_file {
                   7883:     my ($uri) = @_;
1.787     albertel 7884:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7885: 
1.955     raeburn  7886:     my ($udom,$uname,$file);
1.712     albertel 7887:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7888: 	($udom,$uname,$file) =
1.811     albertel 7889: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7890: 	$file = 'userfiles/'.$file;
                   7891:     }
                   7892:     if ($uri =~ m-^/res/-) {
                   7893: 	($udom,$uname) = 
1.807     albertel 7894: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7895: 	$file = $uri;
                   7896:     }
                   7897: 
                   7898:     if (!$udom || !$uname || !$file) {
                   7899: 	# unable to handle the uri
                   7900: 	return ();
                   7901:     }
1.956     raeburn  7902:     my $getpropath;
                   7903:     if ($file =~ /^userfiles\//) {
                   7904:         $getpropath = 1;
                   7905:     }
1.955     raeburn  7906:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7907:     my @stats = split('&', $result);
1.721     banghart 7908:     
1.712     albertel 7909:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7910: 	shift(@stats); #filename is first
                   7911: 	return @stats;
                   7912:     }
                   7913:     return ();
                   7914: }
                   7915: 
1.26      www      7916: # -------------------------------------------------------- Value of a Condition
                   7917: 
1.713     albertel 7918: # gets the value of a specific preevaluated condition
                   7919: #    stored in the string  $env{user.state.<cid>}
                   7920: # or looks up a condition reference in the bighash and if if hasn't
                   7921: # already been evaluated recurses into docondval to get the value of
                   7922: # the condition, then memoizing it to 
                   7923: #   $env{user.state.<cid>.<condition>}
1.40      www      7924: sub directcondval {
                   7925:     my $number=shift;
1.620     albertel 7926:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7927: 	&Apache::lonuserstate::evalstate();
                   7928:     }
1.713     albertel 7929:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7930: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7931:     } elsif ($number =~ /^_/) {
                   7932: 	my $sub_condition;
                   7933: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7934: 		&GDBM_READER(),0640)) {
                   7935: 	    $sub_condition=$bighash{'conditions'.$number};
                   7936: 	    untie(%bighash);
                   7937: 	}
                   7938: 	my $value = &docondval($sub_condition);
1.949     raeburn  7939: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7940: 	return $value;
                   7941:     }
1.620     albertel 7942:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7943:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7944:     } else {
                   7945:        return 2;
                   7946:     }
                   7947: }
                   7948: 
1.713     albertel 7949: # get the collection of conditions for this resource
1.26      www      7950: sub condval {
                   7951:     my $condidx=shift;
1.54      www      7952:     my $allpathcond='';
1.713     albertel 7953:     foreach my $cond (split(/\|/,$condidx)) {
                   7954: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7955: 	    $allpathcond.=
                   7956: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7957: 	}
1.191     harris41 7958:     }
1.54      www      7959:     $allpathcond=~s/\|$//;
1.713     albertel 7960:     return &docondval($allpathcond);
                   7961: }
                   7962: 
                   7963: #evaluates an expression of conditions
                   7964: sub docondval {
                   7965:     my ($allpathcond) = @_;
                   7966:     my $result=0;
                   7967:     if ($env{'request.course.id'}
                   7968: 	&& defined($allpathcond)) {
                   7969: 	my $operand='|';
                   7970: 	my @stack;
                   7971: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7972: 	    if ($chunk eq '(') {
                   7973: 		push @stack,($operand,$result);
                   7974: 	    } elsif ($chunk eq ')') {
                   7975: 		my $before=pop @stack;
                   7976: 		if (pop @stack eq '&') {
                   7977: 		    $result=$result>$before?$before:$result;
                   7978: 		} else {
                   7979: 		    $result=$result>$before?$result:$before;
                   7980: 		}
                   7981: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7982: 		$operand=$chunk;
                   7983: 	    } else {
                   7984: 		my $new=directcondval($chunk);
                   7985: 		if ($operand eq '&') {
                   7986: 		    $result=$result>$new?$new:$result;
                   7987: 		} else {
                   7988: 		    $result=$result>$new?$result:$new;
                   7989: 		}
                   7990: 	    }
                   7991: 	}
1.26      www      7992:     }
                   7993:     return $result;
1.421     albertel 7994: }
                   7995: 
                   7996: # ---------------------------------------------------- Devalidate courseresdata
                   7997: 
                   7998: sub devalidatecourseresdata {
                   7999:     my ($coursenum,$coursedomain)=@_;
                   8000:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8001:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8002: }
                   8003: 
1.763     www      8004: 
1.200     www      8005: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8006: #
                   8007: #  Parameters:
                   8008: #      $coursenum    - Number of the course.
                   8009: #      $coursedomain - Domain at which the course was created.
                   8010: #  Returns:
                   8011: #     A hash of the course parameters along (I think) with timestamps
                   8012: #     and version info.
1.877     foxr     8013: 
1.624     albertel 8014: sub get_courseresdata {
                   8015:     my ($coursenum,$coursedomain)=@_;
1.200     www      8016:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8017:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8018:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8019:     my %dumpreply;
1.417     albertel 8020:     unless (defined($cached)) {
1.624     albertel 8021: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8022: 	$result=\%dumpreply;
1.251     albertel 8023: 	my ($tmp) = keys(%dumpreply);
                   8024: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8025: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8026: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8027: 	    return $tmp;
1.416     albertel 8028: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8029: 	    $result=undef;
1.599     albertel 8030: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8031: 	}
                   8032:     }
1.624     albertel 8033:     return $result;
                   8034: }
                   8035: 
1.633     albertel 8036: sub devalidateuserresdata {
                   8037:     my ($uname,$udom)=@_;
                   8038:     my $hashid="$udom:$uname";
                   8039:     &devalidate_cache_new('userres',$hashid);
                   8040: }
                   8041: 
1.624     albertel 8042: sub get_userresdata {
                   8043:     my ($uname,$udom)=@_;
                   8044:     #most student don\'t have any data set, check if there is some data
                   8045:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8046: 
                   8047:     my $hashid="$udom:$uname";
                   8048:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8049:     if (!defined($cached)) {
                   8050: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8051: 	$result=\%resourcedata;
                   8052: 	&do_cache_new('userres',$hashid,$result,600);
                   8053:     }
                   8054:     my ($tmp)=keys(%$result);
                   8055:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8056: 	return $result;
                   8057:     }
                   8058:     #error 2 occurs when the .db doesn't exist
                   8059:     if ($tmp!~/error: 2 /) {
1.672     albertel 8060: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8061: 		 " Trying to get resource data for ".
                   8062: 		 $uname." at ".$udom.": ".
                   8063: 		 $tmp."</font>");
                   8064:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8065: 	#&EXT_cache_set($udom,$uname);
                   8066: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8067: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8068:     }
                   8069:     return $tmp;
                   8070: }
1.879     foxr     8071: #----------------------------------------------- resdata - return resource data
                   8072: #  Purpose:
                   8073: #    Return resource data for either users or for a course.
                   8074: #  Parameters:
                   8075: #     $name      - Course/user name.
                   8076: #     $domain    - Name of the domain the user/course is registered on.
                   8077: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8078: #     @which     - Array of names of resources desired.
                   8079: #  Returns:
                   8080: #     The value of the first reasource in @which that is found in the
                   8081: #     resource hash.
                   8082: #  Exceptional Conditions:
                   8083: #     If the $type passed in is not valid (not the string 'course' or 
                   8084: #     'user', an undefined  reference is returned.
                   8085: #     If none of the resources are found, an undef is returned
1.624     albertel 8086: sub resdata {
                   8087:     my ($name,$domain,$type,@which)=@_;
                   8088:     my $result;
                   8089:     if ($type eq 'course') {
                   8090: 	$result=&get_courseresdata($name,$domain);
                   8091:     } elsif ($type eq 'user') {
                   8092: 	$result=&get_userresdata($name,$domain);
                   8093:     }
                   8094:     if (!ref($result)) { return $result; }    
1.251     albertel 8095:     foreach my $item (@which) {
1.927     albertel 8096: 	if (defined($result->{$item->[0]})) {
                   8097: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8098: 	}
1.250     albertel 8099:     }
1.291     albertel 8100:     return undef;
1.200     www      8101: }
                   8102: 
1.379     matthew  8103: #
                   8104: # EXT resource caching routines
                   8105: #
                   8106: 
                   8107: sub clear_EXT_cache_status {
1.383     albertel 8108:     &delenv('cache.EXT.');
1.379     matthew  8109: }
                   8110: 
                   8111: sub EXT_cache_status {
                   8112:     my ($target_domain,$target_user) = @_;
1.383     albertel 8113:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8114:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8115:         # We know already the user has no data
                   8116:         return 1;
                   8117:     } else {
                   8118:         return 0;
                   8119:     }
                   8120: }
                   8121: 
                   8122: sub EXT_cache_set {
                   8123:     my ($target_domain,$target_user) = @_;
1.383     albertel 8124:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8125:     #&appenv({$cachename => time});
1.379     matthew  8126: }
                   8127: 
1.28      www      8128: # --------------------------------------------------------- Value of a Variable
1.58      www      8129: sub EXT {
1.715     albertel 8130: 
1.395     albertel 8131:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8132:     unless ($varname) { return ''; }
1.218     albertel 8133:     #get real user name/domain, courseid and symb
                   8134:     my $courseid;
1.359     albertel 8135:     my $publicuser;
1.427     www      8136:     if ($symbparm) {
                   8137: 	$symbparm=&get_symb_from_alias($symbparm);
                   8138:     }
1.218     albertel 8139:     if (!($uname && $udom)) {
1.790     albertel 8140:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8141:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8142:     } else {
1.620     albertel 8143: 	$courseid=$env{'request.course.id'};
1.218     albertel 8144:     }
1.48      www      8145:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8146:     my $rest;
1.320     albertel 8147:     if (defined($therest[0])) {
1.48      www      8148:        $rest=join('.',@therest);
                   8149:     } else {
                   8150:        $rest='';
                   8151:     }
1.320     albertel 8152: 
1.57      www      8153:     my $qualifierrest=$qualifier;
                   8154:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8155:     my $spacequalifierrest=$space;
                   8156:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8157:     if ($realm eq 'user') {
1.48      www      8158: # --------------------------------------------------------------- user.resource
                   8159: 	if ($space eq 'resource') {
1.651     albertel 8160: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8161: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8162: 		 &&
1.744     albertel 8163: 		 ($symbparm eq &symbread()) ) {	
                   8164: 		# if we are in the middle of processing the resource the
                   8165: 		# get the value we are planning on committing
                   8166:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8167:                     return $Apache::lonhomework::results{$qualifierrest};
                   8168:                 } else {
                   8169:                     return $Apache::lonhomework::history{$qualifierrest};
                   8170:                 }
1.335     albertel 8171: 	    } else {
1.359     albertel 8172: 		my %restored;
1.620     albertel 8173: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8174: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8175: 		} else {
                   8176: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8177: 		}
1.335     albertel 8178: 		return $restored{$qualifierrest};
                   8179: 	    }
1.48      www      8180: # ----------------------------------------------------------------- user.access
                   8181:         } elsif ($space eq 'access') {
1.218     albertel 8182: 	    # FIXME - not supporting calls for a specific user
1.48      www      8183:             return &allowed($qualifier,$rest);
                   8184: # ------------------------------------------ user.preferences, user.environment
                   8185:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8186: 	    if (($uname eq $env{'user.name'}) &&
                   8187: 		($udom eq $env{'user.domain'})) {
                   8188: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8189: 	    } else {
1.359     albertel 8190: 		my %returnhash;
                   8191: 		if (!$publicuser) {
                   8192: 		    %returnhash=&userenvironment($udom,$uname,
                   8193: 						 $qualifierrest);
                   8194: 		}
1.218     albertel 8195: 		return $returnhash{$qualifierrest};
                   8196: 	    }
1.48      www      8197: # ----------------------------------------------------------------- user.course
                   8198:         } elsif ($space eq 'course') {
1.218     albertel 8199: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8200:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8201: # ------------------------------------------------------------------- user.role
                   8202:         } elsif ($space eq 'role') {
1.218     albertel 8203: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8204:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8205:             if ($qualifier eq 'value') {
                   8206: 		return $role;
                   8207:             } elsif ($qualifier eq 'extent') {
                   8208:                 return $where;
                   8209:             }
                   8210: # ----------------------------------------------------------------- user.domain
                   8211:         } elsif ($space eq 'domain') {
1.218     albertel 8212:             return $udom;
1.48      www      8213: # ------------------------------------------------------------------- user.name
                   8214:         } elsif ($space eq 'name') {
1.218     albertel 8215:             return $uname;
1.48      www      8216: # ---------------------------------------------------- Any other user namespace
1.29      www      8217:         } else {
1.359     albertel 8218: 	    my %reply;
                   8219: 	    if (!$publicuser) {
                   8220: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8221: 	    }
                   8222: 	    return $reply{$qualifierrest};
1.48      www      8223:         }
1.236     www      8224:     } elsif ($realm eq 'query') {
                   8225: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8226:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8227: 						[$spacequalifierrest]);
1.620     albertel 8228: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8229:    } elsif ($realm eq 'request') {
1.48      www      8230: # ------------------------------------------------------------- request.browser
                   8231:         if ($space eq 'browser') {
1.430     www      8232: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8233: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8234: 		    return 1;
                   8235: 		} else {
                   8236: 		    return 0;
                   8237: 		}
                   8238: 	    } else {
1.620     albertel 8239: 		return $env{'browser.'.$qualifier};
1.430     www      8240: 	    }
1.57      www      8241: # ------------------------------------------------------------ request.filename
                   8242:         } else {
1.620     albertel 8243:             return $env{'request.'.$spacequalifierrest};
1.29      www      8244:         }
1.28      www      8245:     } elsif ($realm eq 'course') {
1.48      www      8246: # ---------------------------------------------------------- course.description
1.620     albertel 8247:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8248:     } elsif ($realm eq 'resource') {
1.165     www      8249: 
1.620     albertel 8250: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8251: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8252: 	}
1.693     albertel 8253: 
                   8254: 	if ($space eq 'title') {
                   8255: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8256: 	    return &gettitle($symbparm);
                   8257: 	}
                   8258: 	
                   8259: 	if ($space eq 'map') {
                   8260: 	    my ($map) = &decode_symb($symbparm);
                   8261: 	    return &symbread($map);
                   8262: 	}
1.905     albertel 8263: 	if ($space eq 'filename') {
                   8264: 	    if ($symbparm) {
                   8265: 		return &clutter((&decode_symb($symbparm))[2]);
                   8266: 	    }
                   8267: 	    return &hreflocation('',$env{'request.filename'});
                   8268: 	}
1.693     albertel 8269: 
                   8270: 	my ($section, $group, @groups);
1.593     albertel 8271: 	my ($courselevelm,$courselevel);
1.539     albertel 8272: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8273: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8274: 
1.218     albertel 8275: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8276: 
1.60      www      8277: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8278: 	    my $symbp=$symbparm;
1.735     albertel 8279: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8280: 
                   8281: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8282: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8283: 
1.620     albertel 8284: 	    if (($env{'user.name'} eq $uname) &&
                   8285: 		($env{'user.domain'} eq $udom)) {
                   8286: 		$section=$env{'request.course.sec'};
1.733     raeburn  8287:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8288:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8289: 	    } else {
1.539     albertel 8290: 		if (! defined($usection)) {
1.551     albertel 8291: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8292: 		} else {
                   8293: 		    $section = $usection;
                   8294: 		}
1.733     raeburn  8295:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8296: 	    }
                   8297: 
                   8298: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8299: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8300: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8301: 
1.593     albertel 8302: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8303: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8304: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8305: 
1.60      www      8306: # ----------------------------------------------------------- first, check user
1.624     albertel 8307: 
                   8308: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8309: 				       ([$courselevelr,'resource'],
                   8310: 					[$courselevelm,'map'     ],
                   8311: 					[$courselevel, 'course'  ]));
1.931     albertel 8312: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8313: 
1.594     albertel 8314: # ------------------------------------------------ second, check some of course
1.684     raeburn  8315:             my $coursereply;
1.691     raeburn  8316:             if (@groups > 0) {
                   8317:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8318:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8319:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8320:             }
1.96      www      8321: 
1.684     raeburn  8322: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8323: 				  $env{'course.'.$courseid.'.domain'},
                   8324: 				  'course',
                   8325: 				  ([$seclevelr,   'resource'],
                   8326: 				   [$seclevelm,   'map'     ],
                   8327: 				   [$seclevel,    'course'  ],
                   8328: 				   [$courselevelr,'resource']));
                   8329: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8330: 
1.60      www      8331: # ------------------------------------------------------ third, check map parms
1.218     albertel 8332: 	    my %parmhash=();
                   8333: 	    my $thisparm='';
                   8334: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8335: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8336: 		    &GDBM_READER(),0640)) {
1.218     albertel 8337: 		$thisparm=$parmhash{$symbparm};
                   8338: 		untie(%parmhash);
                   8339: 	    }
1.927     albertel 8340: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8341: 	}
1.594     albertel 8342: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8343: 
1.218     albertel 8344: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8345: 	my $filename;
                   8346: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8347: 	if ($symbparm) {
1.409     www      8348: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8349: 	} else {
1.620     albertel 8350: 	    $filename=$env{'request.filename'};
1.282     albertel 8351: 	}
                   8352: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8353: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8354: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8355: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8356: 
1.927     albertel 8357: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8358: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8359: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8360: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8361: 				     $env{'course.'.$courseid.'.domain'},
                   8362: 				     'course',
1.927     albertel 8363: 				     ([$courselevelm,'map'   ],
                   8364: 				      [$courselevel, 'course']));
                   8365: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8366: 	}
1.145     www      8367: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8368: 	unless ($space eq '0') {
1.336     albertel 8369: 	    my @parts=split(/_/,$space);
                   8370: 	    my $id=pop(@parts);
                   8371: 	    my $part=join('_',@parts);
                   8372: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8373: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8374: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8375: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8376: 	}
1.395     albertel 8377: 	if ($recurse) { return undef; }
                   8378: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8379: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8380: # ---------------------------------------------------- Any other user namespace
                   8381:     } elsif ($realm eq 'environment') {
                   8382: # ----------------------------------------------------------------- environment
1.620     albertel 8383: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8384: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8385: 	} else {
1.770     albertel 8386: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8387: 		return '';
                   8388: 	    }
1.219     albertel 8389: 	    my %returnhash=&userenvironment($udom,$uname,
                   8390: 					    $spacequalifierrest);
                   8391: 	    return $returnhash{$spacequalifierrest};
                   8392: 	}
1.28      www      8393:     } elsif ($realm eq 'system') {
1.48      www      8394: # ----------------------------------------------------------------- system.time
                   8395: 	if ($space eq 'time') {
                   8396: 	    return time;
                   8397:         }
1.696     albertel 8398:     } elsif ($realm eq 'server') {
                   8399: # ----------------------------------------------------------------- system.time
                   8400: 	if ($space eq 'name') {
                   8401: 	    return $ENV{'SERVER_NAME'};
                   8402:         }
1.28      www      8403:     }
1.48      www      8404:     return '';
1.61      www      8405: }
                   8406: 
1.927     albertel 8407: sub get_reply {
                   8408:     my ($reply_value) = @_;
1.940     raeburn  8409:     if (ref($reply_value) eq 'ARRAY') {
                   8410:         if (wantarray) {
                   8411: 	    return @$reply_value;
                   8412:         }
                   8413:         return $reply_value->[0];
                   8414:     } else {
                   8415:         return $reply_value;
1.927     albertel 8416:     }
                   8417: }
                   8418: 
1.691     raeburn  8419: sub check_group_parms {
                   8420:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8421:     my @groupitems = ();
                   8422:     my $resultitem;
1.927     albertel 8423:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8424:     foreach my $group (@{$groups}) {
                   8425:         foreach my $level (@levels) {
1.927     albertel 8426:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8427:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8428:         }
                   8429:     }
                   8430:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8431:                             $env{'course.'.$courseid.'.domain'},
                   8432:                                      'course',@groupitems);
                   8433:     return $coursereply;
                   8434: }
                   8435: 
                   8436: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8437:     my ($courseid,@groups) = @_;
                   8438:     @groups = sort(@groups);
1.691     raeburn  8439:     return @groups;
                   8440: }
                   8441: 
1.395     albertel 8442: sub packages_tab_default {
                   8443:     my ($uri,$varname)=@_;
                   8444:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8445: 
                   8446:     my (@extension,@specifics,$do_default);
                   8447:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8448: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8449: 	if ($pack_type eq 'default') {
                   8450: 	    $do_default=1;
                   8451: 	} elsif ($pack_type eq 'extension') {
                   8452: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8453: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8454: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8455: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8456: 	}
                   8457:     }
                   8458:     # first look for a package that matches the requested part id
                   8459:     foreach my $package (@specifics) {
                   8460: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8461: 	next if ($pack_part ne $part);
                   8462: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8463: 	    return $packagetab{"$pack_type&$name&default"};
                   8464: 	}
                   8465:     }
                   8466:     # look for any possible matching non extension_ package
                   8467:     foreach my $package (@specifics) {
                   8468: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8469: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8470: 	    return $packagetab{"$pack_type&$name&default"};
                   8471: 	}
1.585     albertel 8472: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8473: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8474: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8475: 	}
                   8476:     }
1.738     albertel 8477:     # look for any posible extension_ match
                   8478:     foreach my $package (@extension) {
                   8479: 	my ($package,$pack_type)=@{$package};
                   8480: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8481: 	    return $packagetab{"$pack_type&$name&default"};
                   8482: 	}
                   8483: 	if (defined($packagetab{$package."&$name&default"})) {
                   8484: 	    return $packagetab{$package."&$name&default"};
                   8485: 	}
                   8486:     }
                   8487:     # look for a global default setting
                   8488:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8489: 	return $packagetab{"default&$name&default"};
                   8490:     }
1.395     albertel 8491:     return undef;
                   8492: }
                   8493: 
1.334     albertel 8494: sub add_prefix_and_part {
                   8495:     my ($prefix,$part)=@_;
                   8496:     my $keyroot;
                   8497:     if (defined($prefix) && $prefix !~ /^__/) {
                   8498: 	# prefix that has a part already
                   8499: 	$keyroot=$prefix;
                   8500:     } elsif (defined($prefix)) {
                   8501: 	# prefix that is missing a part
                   8502: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8503:     } else {
                   8504: 	# no prefix at all
                   8505: 	if (defined($part)) { $keyroot='_'.$part; }
                   8506:     }
                   8507:     return $keyroot;
                   8508: }
                   8509: 
1.71      www      8510: # ---------------------------------------------------------------- Get metadata
                   8511: 
1.599     albertel 8512: my %metaentry;
1.71      www      8513: sub metadata {
1.176     www      8514:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8515:     $uri=&declutter($uri);
1.288     albertel 8516:     # if it is a non metadata possible uri return quickly
1.529     albertel 8517:     if (($uri eq '') || 
                   8518: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8519: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8520:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8521: 	return undef;
                   8522:     }
                   8523:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8524: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8525: 	return undef;
1.288     albertel 8526:     }
1.73      www      8527:     my $filename=$uri;
                   8528:     $uri=~s/\.meta$//;
1.172     www      8529: #
                   8530: # Is the metadata already cached?
1.177     www      8531: # Look at timestamp of caching
1.172     www      8532: # Everything is cached by the main uri, libraries are never directly cached
                   8533: #
1.428     albertel 8534:     if (!defined($liburi)) {
1.599     albertel 8535: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8536: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8537:     }
                   8538:     {
1.172     www      8539: #
                   8540: # Is this a recursive call for a library?
                   8541: #
1.599     albertel 8542: #	if (! exists($metacache{$uri})) {
                   8543: #	    $metacache{$uri}={};
                   8544: #	}
1.924     albertel 8545: 	my $cachetime = 60*60;
1.171     www      8546:         if ($liburi) {
                   8547: 	    $liburi=&declutter($liburi);
                   8548:             $filename=$liburi;
1.401     bowersj2 8549:         } else {
1.599     albertel 8550: 	    &devalidate_cache_new('meta',$uri);
                   8551: 	    undef(%metaentry);
1.401     bowersj2 8552: 	}
1.140     www      8553:         my %metathesekeys=();
1.73      www      8554:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8555: 	my $metastring;
1.924     albertel 8556: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8557: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8558: 	    $metastring = 
1.929     albertel 8559: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8560: 					  ('grade_target' => 'meta'));
                   8561: 	    $cachetime = 1; # only want this cached in the child not long term
                   8562: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8563: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8564: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8565: 	    $metastring=&getfile($file);
1.489     albertel 8566: 	}
1.208     albertel 8567:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8568:         my $token;
1.140     www      8569:         undef %metathesekeys;
1.71      www      8570:         while ($token=$parser->get_token) {
1.339     albertel 8571: 	    if ($token->[0] eq 'S') {
                   8572: 		if (defined($token->[2]->{'package'})) {
1.172     www      8573: #
                   8574: # This is a package - get package info
                   8575: #
1.339     albertel 8576: 		    my $package=$token->[2]->{'package'};
                   8577: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8578: 		    if (defined($token->[2]->{'id'})) { 
                   8579: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8580: 		    }
1.599     albertel 8581: 		    if ($metaentry{':packages'}) {
                   8582: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8583: 		    } else {
1.599     albertel 8584: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8585: 		    }
1.736     albertel 8586: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8587: 			my $part=$keyroot;
                   8588: 			$part=~s/^\_//;
1.736     albertel 8589: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8590: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8591: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8592: 			    # ignore package.tab specified default values
                   8593:                             # here &package_tab_default() will fetch those
                   8594: 			    if ($subp eq 'default') { next; }
1.736     albertel 8595: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8596: 			    my $unikey;
                   8597: 			    if ($pack =~ /_0$/) {
                   8598: 				$unikey='parameter_0_'.$name;
                   8599: 				$part=0;
                   8600: 			    } else {
                   8601: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8602: 			    }
1.339     albertel 8603: 			    if ($subp eq 'display') {
                   8604: 				$value.=' [Part: '.$part.']';
                   8605: 			    }
1.599     albertel 8606: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8607: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8608: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8609: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8610: 			    }
1.599     albertel 8611: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8612: 				$metaentry{':'.$unikey}=
                   8613: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8614: 			    }
1.339     albertel 8615: 			}
                   8616: 		    }
                   8617: 		} else {
1.172     www      8618: #
                   8619: # This is not a package - some other kind of start tag
1.339     albertel 8620: #
                   8621: 		    my $entry=$token->[1];
                   8622: 		    my $unikey;
                   8623: 		    if ($entry eq 'import') {
                   8624: 			$unikey='';
                   8625: 		    } else {
                   8626: 			$unikey=$entry;
                   8627: 		    }
                   8628: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8629: 
                   8630: 		    if (defined($token->[2]->{'id'})) { 
                   8631: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8632: 		    }
1.175     www      8633: 
1.339     albertel 8634: 		    if ($entry eq 'import') {
1.175     www      8635: #
                   8636: # Importing a library here
1.339     albertel 8637: #
                   8638: 			if ($depthcount<20) {
                   8639: 			    my $location=$parser->get_text('/import');
                   8640: 			    my $dir=$filename;
                   8641: 			    $dir=~s|[^/]*$||;
                   8642: 			    $location=&filelocation($dir,$location);
1.736     albertel 8643: 			    my $metadata = 
                   8644: 				&metadata($uri,'keys', $location,$unikey,
                   8645: 					  $depthcount+1);
                   8646: 			    foreach my $meta (split(',',$metadata)) {
                   8647: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8648: 				$metathesekeys{$meta}=1;
1.339     albertel 8649: 			    }
                   8650: 			}
                   8651: 		    } else { 
                   8652: 			if (defined($token->[2]->{'name'})) { 
                   8653: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8654: 			}
                   8655: 			$metathesekeys{$unikey}=1;
1.736     albertel 8656: 			foreach my $param (@{$token->[3]}) {
                   8657: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8658: 				$token->[2]->{$param};
1.339     albertel 8659: 			}
                   8660: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8661: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8662: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8663: 		 # only ws inside the tag, and not in default, so use default
                   8664: 		 # as value
1.599     albertel 8665: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8666: 			} elsif ( $internaltext =~ /\S/ ) {
                   8667: 		  # something interesting inside the tag
                   8668: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8669: 			} else {
1.908     albertel 8670: 		  # no interesting values, don't set a default
1.339     albertel 8671: 			}
1.172     www      8672: # end of not-a-package not-a-library import
1.339     albertel 8673: 		    }
1.172     www      8674: # end of not-a-package start tag
1.339     albertel 8675: 		}
1.172     www      8676: # the next is the end of "start tag"
1.339     albertel 8677: 	    }
                   8678: 	}
1.483     albertel 8679: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8680: 	$extension = lc($extension);
                   8681: 	if ($extension eq 'htm') { $extension='html'; }
                   8682: 
1.737     albertel 8683: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8684: 	    #no specific packages #how's our extension
                   8685: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8686: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8687: 					 \%metathesekeys);
                   8688: 	}
1.883     albertel 8689: 
                   8690: 	if (!exists($metaentry{':packages'})
                   8691: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8692: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8693: 		#no specific packages well let's get default then
                   8694: 		if ($key!~/^default&/) { next; }
1.488     albertel 8695: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8696: 					     \%metathesekeys);
                   8697: 	    }
                   8698: 	}
1.338     www      8699: # are there custom rights to evaluate
1.599     albertel 8700: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8701: 
1.338     www      8702:     #
                   8703:     # Importing a rights file here
1.339     albertel 8704:     #
                   8705: 	    unless ($depthcount) {
1.599     albertel 8706: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8707: 		my $dir=$filename;
                   8708: 		$dir=~s|[^/]*$||;
                   8709: 		$location=&filelocation($dir,$location);
1.736     albertel 8710: 		my $rights_metadata =
                   8711: 		    &metadata($uri,'keys',$location,'_rights',
                   8712: 			      $depthcount+1);
                   8713: 		foreach my $rights (split(',',$rights_metadata)) {
                   8714: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8715: 		    $metathesekeys{$rights}=1;
1.339     albertel 8716: 		}
                   8717: 	    }
                   8718: 	}
1.737     albertel 8719: 	# uniqifiy package listing
                   8720: 	my %seen;
                   8721: 	my @uniq_packages =
                   8722: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8723: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8724: 
                   8725: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8726: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8727: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8728: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8729: # this is the end of "was not already recently cached
1.71      www      8730:     }
1.599     albertel 8731:     return $metaentry{':'.$what};
1.261     albertel 8732: }
                   8733: 
1.488     albertel 8734: sub metadata_create_package_def {
1.483     albertel 8735:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8736:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8737:     if ($subp eq 'default') { next; }
                   8738:     
1.599     albertel 8739:     if (defined($metaentry{':packages'})) {
                   8740: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8741:     } else {
1.599     albertel 8742: 	$metaentry{':packages'}=$package;
1.483     albertel 8743:     }
                   8744:     my $value=$packagetab{$key};
                   8745:     my $unikey;
                   8746:     $unikey='parameter_0_'.$name;
1.599     albertel 8747:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8748:     $$metathesekeys{$unikey}=1;
1.599     albertel 8749:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8750: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8751:     }
1.599     albertel 8752:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8753: 	$metaentry{':'.$unikey}=
                   8754: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8755:     }
                   8756: }
                   8757: 
1.261     albertel 8758: sub metadata_generate_part0 {
                   8759:     my ($metadata,$metacache,$uri) = @_;
                   8760:     my %allnames;
1.737     albertel 8761:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8762: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8763: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8764: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8765: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8766: 	    $allnames{$name}=$part;
                   8767: 	  }
                   8768: 	}
                   8769:     }
                   8770:     foreach my $name (keys(%allnames)) {
                   8771:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8772:       my $key=":parameter_0_$name";
1.261     albertel 8773:       $$metacache{"$key.part"}='0';
                   8774:       $$metacache{"$key.name"}=$name;
1.428     albertel 8775:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8776: 					   $allnames{$name}.'_'.$name.
                   8777: 					   '.type'};
1.428     albertel 8778:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8779: 			     '.display'};
1.644     www      8780:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8781:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8782:       $$metacache{"$key.display"}=$olddis;
                   8783:     }
1.71      www      8784: }
                   8785: 
1.764     albertel 8786: # ------------------------------------------------------ Devalidate title cache
                   8787: 
                   8788: sub devalidate_title_cache {
                   8789:     my ($url)=@_;
                   8790:     if (!$env{'request.course.id'}) { return; }
                   8791:     my $symb=&symbread($url);
                   8792:     if (!$symb) { return; }
                   8793:     my $key=$env{'request.course.id'}."\0".$symb;
                   8794:     &devalidate_cache_new('title',$key);
                   8795: }
                   8796: 
1.1014    droeschl 8797: # ------------------------------------------------- Get the title of a course
                   8798: 
                   8799: sub current_course_title {
                   8800:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8801: }
1.301     www      8802: # ------------------------------------------------- Get the title of a resource
                   8803: 
                   8804: sub gettitle {
                   8805:     my $urlsymb=shift;
                   8806:     my $symb=&symbread($urlsymb);
1.534     albertel 8807:     if ($symb) {
1.620     albertel 8808: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8809: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8810: 	if (defined($cached)) { 
                   8811: 	    return $result;
                   8812: 	}
1.534     albertel 8813: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8814: 	my $title='';
1.907     albertel 8815: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8816: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8817: 	} else {
                   8818: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8819: 		    &GDBM_READER(),0640)) {
                   8820: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8821: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8822: 		untie(%bighash);
                   8823: 	    }
1.534     albertel 8824: 	}
                   8825: 	$title=~s/\&colon\;/\:/gs;
                   8826: 	if ($title) {
1.599     albertel 8827: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8828: 	}
                   8829: 	$urlsymb=$url;
                   8830:     }
                   8831:     my $title=&metadata($urlsymb,'title');
                   8832:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8833:     return $title;
1.301     www      8834: }
1.613     albertel 8835: 
1.614     albertel 8836: sub get_slot {
                   8837:     my ($which,$cnum,$cdom)=@_;
                   8838:     if (!$cnum || !$cdom) {
1.790     albertel 8839: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8840: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8841: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8842:     }
1.703     albertel 8843:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8844:     my %slotinfo;
                   8845:     if (exists($remembered{$key})) {
                   8846: 	$slotinfo{$which} = $remembered{$key};
                   8847:     } else {
                   8848: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8849: 	&Apache::lonhomework::showhash(%slotinfo);
                   8850: 	my ($tmp)=keys(%slotinfo);
                   8851: 	if ($tmp=~/^error:/) { return (); }
                   8852: 	$remembered{$key} = $slotinfo{$which};
                   8853:     }
1.616     albertel 8854:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8855: 	return %{$slotinfo{$which}};
                   8856:     }
                   8857:     return $slotinfo{$which};
1.614     albertel 8858: }
1.31      www      8859: # ------------------------------------------------- Update symbolic store links
                   8860: 
                   8861: sub symblist {
                   8862:     my ($mapname,%newhash)=@_;
1.438     www      8863:     $mapname=&deversion(&declutter($mapname));
1.31      www      8864:     my %hash;
1.620     albertel 8865:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8866:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8867:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8868: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8869: 		next if ($url eq 'last_known'
                   8870: 			 && $env{'form.no_update_last_known'});
                   8871: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8872: 						    $newhash{$url}->[1],
                   8873: 						    $newhash{$url}->[0]);
1.191     harris41 8874:             }
1.31      www      8875:             if (untie(%hash)) {
                   8876: 		return 'ok';
                   8877:             }
                   8878:         }
                   8879:     }
                   8880:     return 'error';
1.212     www      8881: }
                   8882: 
                   8883: # --------------------------------------------------------------- Verify a symb
                   8884: 
                   8885: sub symbverify {
1.510     www      8886:     my ($symb,$thisurl)=@_;
                   8887:     my $thisfn=$thisurl;
1.439     www      8888:     $thisfn=&declutter($thisfn);
1.215     www      8889: # direct jump to resource in page or to a sequence - will construct own symbs
                   8890:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8891: # check URL part
1.409     www      8892:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8893: 
1.431     www      8894:     unless ($url eq $thisfn) { return 0; }
1.213     www      8895: 
1.216     www      8896:     $symb=&symbclean($symb);
1.510     www      8897:     $thisurl=&deversion($thisurl);
1.439     www      8898:     $thisfn=&deversion($thisfn);
1.213     www      8899: 
                   8900:     my %bighash;
                   8901:     my $okay=0;
1.431     www      8902: 
1.620     albertel 8903:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8904:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8905:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8906:             $thisurl =~ s/\?.+$//;
                   8907:         }
1.510     www      8908:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8909:         unless ($ids) { 
1.510     www      8910:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8911:         }
                   8912:         if ($ids) {
                   8913: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8914: 	    foreach my $id (split(/\,/,$ids)) {
                   8915: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8916:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8917:                    $symb =~ s/\?.+$//;
                   8918:                }
1.216     www      8919:                if (
                   8920:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8921:    eq $symb) { 
1.620     albertel 8922: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8923: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8924: 		       $okay=1; 
                   8925: 		   }
                   8926: 	       }
1.216     www      8927: 	   }
                   8928:         }
1.213     www      8929: 	untie(%bighash);
                   8930:     }
                   8931:     return $okay;
1.31      www      8932: }
                   8933: 
1.210     www      8934: # --------------------------------------------------------------- Clean-up symb
                   8935: 
                   8936: sub symbclean {
                   8937:     my $symb=shift;
1.568     albertel 8938:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8939: # remove version from map
                   8940:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8941: 
1.210     www      8942: # remove version from URL
                   8943:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8944: 
1.507     www      8945: # remove wrapper
                   8946: 
1.510     www      8947:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8948:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8949:     return $symb;
1.409     www      8950: }
                   8951: 
                   8952: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8953: 
                   8954: sub encode_symb {
                   8955:     my ($map,$resid,$url)=@_;
                   8956:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8957: }
1.409     www      8958: 
                   8959: sub decode_symb {
1.568     albertel 8960:     my $symb=shift;
                   8961:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8962:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8963:     return (&fixversion($map),$resid,&fixversion($url));
                   8964: }
                   8965: 
                   8966: sub fixversion {
                   8967:     my $fn=shift;
1.609     banghart 8968:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8969:     my %bighash;
                   8970:     my $uri=&clutter($fn);
1.620     albertel 8971:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8972: # is this cached?
1.599     albertel 8973:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8974:     if (defined($cached)) { return $result; }
                   8975: # unfortunately not cached, or expired
1.620     albertel 8976:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8977: 	    &GDBM_READER(),0640)) {
                   8978:  	if ($bighash{'version_'.$uri}) {
                   8979:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8980:  	    unless (($version eq 'mostrecent') || 
                   8981: 		    ($version==&getversion($uri))) {
1.440     www      8982:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8983:  	    }
                   8984:  	}
                   8985:  	untie %bighash;
1.413     www      8986:     }
1.599     albertel 8987:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8988: }
                   8989: 
                   8990: sub deversion {
                   8991:     my $url=shift;
                   8992:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8993:     return $url;
1.210     www      8994: }
                   8995: 
1.31      www      8996: # ------------------------------------------------------ Return symb list entry
                   8997: 
                   8998: sub symbread {
1.249     www      8999:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9000:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9001:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9002: # no filename provided? try from environment
1.44      www      9003:     unless ($thisfn) {
1.620     albertel 9004:         if ($env{'request.symb'}) {
                   9005: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9006: 	}
1.620     albertel 9007: 	$thisfn=$env{'request.filename'};
1.44      www      9008:     }
1.569     albertel 9009:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9010: # is that filename actually a symb? Verify, clean, and return
                   9011:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9012: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9013: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9014: 	}
1.242     www      9015:     }
1.44      www      9016:     $thisfn=declutter($thisfn);
1.31      www      9017:     my %hash;
1.37      www      9018:     my %bighash;
                   9019:     my $syval='';
1.620     albertel 9020:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9021:         my $targetfn = $thisfn;
1.609     banghart 9022:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9023:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9024:         }
1.687     albertel 9025: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9026: 	    $targetfn=$1;
                   9027: 	}
1.620     albertel 9028:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9029:                       &GDBM_READER(),0640)) {
1.481     raeburn  9030: 	    $syval=$hash{$targetfn};
1.37      www      9031:             untie(%hash);
                   9032:         }
                   9033: # ---------------------------------------------------------- There was an entry
                   9034:         if ($syval) {
1.601     albertel 9035: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9036: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9037: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9038: 		    #return $env{$cache_str}='';
1.601     albertel 9039: 		#}    
                   9040: 		#$syval.=$1;
                   9041: 	    #}
1.37      www      9042:         } else {
                   9043: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9044:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9045:                             &GDBM_READER(),0640)) {
1.37      www      9046: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9047:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9048:               unless ($ids) { 
                   9049:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9050:               }
                   9051:               unless ($ids) {
                   9052: # alias?
                   9053: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9054:               }
1.37      www      9055:               if ($ids) {
                   9056: # ------------------------------------------------------------------- Has ID(s)
                   9057:                  my @possibilities=split(/\,/,$ids);
1.39      www      9058:                  if ($#possibilities==0) {
                   9059: # ----------------------------------------------- There is only one possibility
1.37      www      9060: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9061: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9062: 						    $resid,$thisfn);
1.249     www      9063:                  } elsif (!$donotrecurse) {
1.39      www      9064: # ------------------------------------------ There is more than one possibility
                   9065:                      my $realpossible=0;
1.800     albertel 9066:                      foreach my $id (@possibilities) {
                   9067: 			 my $file=$bighash{'src_'.$id};
1.39      www      9068:                          if (&allowed('bre',$file)) {
1.800     albertel 9069:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9070:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9071: 				$realpossible++;
1.626     albertel 9072:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9073: 						    $resid,$thisfn);
1.39      www      9074:                             }
                   9075: 			 }
1.191     harris41 9076:                      }
1.39      www      9077: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9078:                  } else {
                   9079:                      $syval='';
1.37      www      9080:                  }
                   9081: 	      }
                   9082:               untie(%bighash)
1.481     raeburn  9083:            }
1.31      www      9084:         }
1.62      www      9085:         if ($syval) {
1.620     albertel 9086: 	    return $env{$cache_str}=$syval;
1.62      www      9087:         }
1.31      www      9088:     }
1.949     raeburn  9089:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9090:     return $env{$cache_str}='';
1.31      www      9091: }
                   9092: 
                   9093: # ---------------------------------------------------------- Return random seed
                   9094: 
1.32      www      9095: sub numval {
                   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;
1.564     albertel 9104:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9105:     return int($txt);
1.368     albertel 9106: }
                   9107: 
1.484     albertel 9108: sub numval2 {
                   9109:     my $txt=shift;
                   9110:     $txt=~tr/A-J/0-9/;
                   9111:     $txt=~tr/a-j/0-9/;
                   9112:     $txt=~tr/K-T/0-9/;
                   9113:     $txt=~tr/k-t/0-9/;
                   9114:     $txt=~tr/U-Z/0-5/;
                   9115:     $txt=~tr/u-z/0-5/;
                   9116:     $txt=~s/\D//g;
                   9117:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9118:     my $total;
                   9119:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9120:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9121:     return int($total);
                   9122: }
                   9123: 
1.575     albertel 9124: sub numval3 {
                   9125:     use integer;
                   9126:     my $txt=shift;
                   9127:     $txt=~tr/A-J/0-9/;
                   9128:     $txt=~tr/a-j/0-9/;
                   9129:     $txt=~tr/K-T/0-9/;
                   9130:     $txt=~tr/k-t/0-9/;
                   9131:     $txt=~tr/U-Z/0-5/;
                   9132:     $txt=~tr/u-z/0-5/;
                   9133:     $txt=~s/\D//g;
                   9134:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9135:     my $total;
                   9136:     foreach my $val (@txts) { $total+=$val; }
                   9137:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9138:     return $total;
                   9139: }
                   9140: 
1.675     albertel 9141: sub digest {
                   9142:     my ($data)=@_;
                   9143:     my $digest=&Digest::MD5::md5($data);
                   9144:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9145:     my ($e,$f);
                   9146:     {
                   9147:         use integer;
                   9148:         $e=($a+$b);
                   9149:         $f=($c+$d);
                   9150:         if ($_64bit) {
                   9151:             $e=(($e<<32)>>32);
                   9152:             $f=(($f<<32)>>32);
                   9153:         }
                   9154:     }
                   9155:     if (wantarray) {
                   9156: 	return ($e,$f);
                   9157:     } else {
                   9158: 	my $g;
                   9159: 	{
                   9160: 	    use integer;
                   9161: 	    $g=($e+$f);
                   9162: 	    if ($_64bit) {
                   9163: 		$g=(($g<<32)>>32);
                   9164: 	    }
                   9165: 	}
                   9166: 	return $g;
                   9167:     }
                   9168: }
                   9169: 
1.368     albertel 9170: sub latest_rnd_algorithm_id {
1.675     albertel 9171:     return '64bit5';
1.366     albertel 9172: }
1.32      www      9173: 
1.503     albertel 9174: sub get_rand_alg {
                   9175:     my ($courseid)=@_;
1.790     albertel 9176:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9177:     if ($courseid) {
1.620     albertel 9178: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9179:     }
                   9180:     return &latest_rnd_algorithm_id();
                   9181: }
                   9182: 
1.562     albertel 9183: sub validCODE {
                   9184:     my ($CODE)=@_;
                   9185:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9186:     return 0;
                   9187: }
                   9188: 
1.491     albertel 9189: sub getCODE {
1.620     albertel 9190:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9191:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9192: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9193: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9194: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9195:     }
                   9196:     return undef;
                   9197: }
                   9198: 
1.31      www      9199: sub rndseed {
1.155     albertel 9200:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9201:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9202:     if (!defined($symb)) {
1.366     albertel 9203: 	unless ($symb=$wsymb) { return time; }
                   9204:     }
                   9205:     if (!$courseid) { $courseid=$wcourseid; }
                   9206:     if (!$domain) { $domain=$wdomain; }
                   9207:     if (!$username) { $username=$wusername }
1.503     albertel 9208:     my $which=&get_rand_alg();
1.803     albertel 9209: 
1.491     albertel 9210:     if (defined(&getCODE())) {
1.675     albertel 9211: 	if ($which eq '64bit5') {
                   9212: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9213: 	} elsif ($which eq '64bit4') {
1.575     albertel 9214: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9215: 	} else {
                   9216: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9217: 	}
1.675     albertel 9218:     } elsif ($which eq '64bit5') {
                   9219: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9220:     } elsif ($which eq '64bit4') {
                   9221: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9222:     } elsif ($which eq '64bit3') {
                   9223: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9224:     } elsif ($which eq '64bit2') {
                   9225: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9226:     } elsif ($which eq '64bit') {
                   9227: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9228:     }
                   9229:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9230: }
                   9231: 
                   9232: sub rndseed_32bit {
                   9233:     my ($symb,$courseid,$domain,$username)=@_;
                   9234:     {
                   9235: 	use integer;
                   9236: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9237: 	my $symbseed=numval($symb) << 22;
                   9238: 	my $namechck=unpack("%32C*",$username) << 17;
                   9239: 	my $nameseed=numval($username) << 12;
                   9240: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9241: 	my $courseseed=unpack("%32C*",$courseid);
                   9242: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9243: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9244: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9245: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9246: 	return $num;
                   9247:     }
                   9248: }
                   9249: 
                   9250: sub rndseed_64bit {
                   9251:     my ($symb,$courseid,$domain,$username)=@_;
                   9252:     {
                   9253: 	use integer;
                   9254: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9255: 	my $symbseed=numval($symb) << 10;
                   9256: 	my $namechck=unpack("%32S*",$username);
                   9257: 	
                   9258: 	my $nameseed=numval($username) << 21;
                   9259: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9260: 	my $courseseed=unpack("%32S*",$courseid);
                   9261: 	
                   9262: 	my $num1=$symbchck+$symbseed+$namechck;
                   9263: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9264: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9265: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9266: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9267: 	return "$num1,$num2";
1.155     albertel 9268:     }
1.366     albertel 9269: }
                   9270: 
1.443     albertel 9271: sub rndseed_64bit2 {
                   9272:     my ($symb,$courseid,$domain,$username)=@_;
                   9273:     {
                   9274: 	use integer;
                   9275: 	# strings need to be an even # of cahracters long, it it is odd the
                   9276:         # last characters gets thrown away
                   9277: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9278: 	my $symbseed=numval($symb) << 10;
                   9279: 	my $namechck=unpack("%32S*",$username.' ');
                   9280: 	
                   9281: 	my $nameseed=numval($username) << 21;
1.501     albertel 9282: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9283: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9284: 	
                   9285: 	my $num1=$symbchck+$symbseed+$namechck;
                   9286: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9287: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9288: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9289: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9290: 	return "$num1,$num2";
                   9291:     }
                   9292: }
                   9293: 
                   9294: sub rndseed_64bit3 {
                   9295:     my ($symb,$courseid,$domain,$username)=@_;
                   9296:     {
                   9297: 	use integer;
                   9298: 	# strings need to be an even # of cahracters long, it it is odd the
                   9299:         # last characters gets thrown away
                   9300: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9301: 	my $symbseed=numval2($symb) << 10;
                   9302: 	my $namechck=unpack("%32S*",$username.' ');
                   9303: 	
                   9304: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9305: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9306: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9307: 	
                   9308: 	my $num1=$symbchck+$symbseed+$namechck;
                   9309: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9310: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9311: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9312: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9313: 	
1.503     albertel 9314: 	return "$num1:$num2";
1.443     albertel 9315:     }
                   9316: }
                   9317: 
1.575     albertel 9318: sub rndseed_64bit4 {
                   9319:     my ($symb,$courseid,$domain,$username)=@_;
                   9320:     {
                   9321: 	use integer;
                   9322: 	# strings need to be an even # of cahracters long, it it is odd the
                   9323:         # last characters gets thrown away
                   9324: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9325: 	my $symbseed=numval3($symb) << 10;
                   9326: 	my $namechck=unpack("%32S*",$username.' ');
                   9327: 	
                   9328: 	my $nameseed=numval3($username) << 21;
                   9329: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9330: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9331: 	
                   9332: 	my $num1=$symbchck+$symbseed+$namechck;
                   9333: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9334: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9335: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9336: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9337: 	
                   9338: 	return "$num1:$num2";
                   9339:     }
                   9340: }
                   9341: 
1.675     albertel 9342: sub rndseed_64bit5 {
                   9343:     my ($symb,$courseid,$domain,$username)=@_;
                   9344:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9345:     return "$num1:$num2";
                   9346: }
                   9347: 
1.366     albertel 9348: sub rndseed_CODE_64bit {
                   9349:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9350:     {
1.366     albertel 9351: 	use integer;
1.443     albertel 9352: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9353: 	my $symbseed=numval2($symb);
1.491     albertel 9354: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9355: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9356: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9357: 	my $num1=$symbseed+$CODEchck;
                   9358: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9359: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9360: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9361: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9362: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9363: 	return "$num1:$num2";
1.366     albertel 9364:     }
                   9365: }
                   9366: 
1.575     albertel 9367: sub rndseed_CODE_64bit4 {
                   9368:     my ($symb,$courseid,$domain,$username)=@_;
                   9369:     {
                   9370: 	use integer;
                   9371: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9372: 	my $symbseed=numval3($symb);
                   9373: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9374: 	my $CODEseed=numval3(&getCODE());
                   9375: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9376: 	my $num1=$symbseed+$CODEchck;
                   9377: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9378: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9379: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9380: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9381: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9382: 	return "$num1:$num2";
                   9383:     }
                   9384: }
                   9385: 
1.675     albertel 9386: sub rndseed_CODE_64bit5 {
                   9387:     my ($symb,$courseid,$domain,$username)=@_;
                   9388:     my $code = &getCODE();
                   9389:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9390:     return "$num1:$num2";
                   9391: }
                   9392: 
1.366     albertel 9393: sub setup_random_from_rndseed {
                   9394:     my ($rndseed)=@_;
1.503     albertel 9395:     if ($rndseed =~/([,:])/) {
                   9396: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9397: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9398:     } else {
                   9399: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9400:     }
1.36      albertel 9401: }
                   9402: 
1.474     albertel 9403: sub latest_receipt_algorithm_id {
1.835     albertel 9404:     return 'receipt3';
1.474     albertel 9405: }
                   9406: 
1.480     www      9407: sub recunique {
                   9408:     my $fucourseid=shift;
                   9409:     my $unique;
1.835     albertel 9410:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9411: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9412: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9413:     } else {
                   9414: 	$unique=$perlvar{'lonReceipt'};
                   9415:     }
                   9416:     return unpack("%32C*",$unique);
                   9417: }
                   9418: 
                   9419: sub recprefix {
                   9420:     my $fucourseid=shift;
                   9421:     my $prefix;
1.835     albertel 9422:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9423: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9424: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9425:     } else {
                   9426: 	$prefix=$perlvar{'lonHostID'};
                   9427:     }
                   9428:     return unpack("%32C*",$prefix);
                   9429: }
                   9430: 
1.76      www      9431: sub ireceipt {
1.474     albertel 9432:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9433: 
                   9434:     my $return =&recprefix($fucourseid).'-';
                   9435: 
                   9436:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9437: 	$env{'request.state'} eq 'construct') {
                   9438: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9439: 	return $return;
                   9440:     }
                   9441: 
1.76      www      9442:     my $cuname=unpack("%32C*",$funame);
                   9443:     my $cudom=unpack("%32C*",$fudom);
                   9444:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9445:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9446:     my $cunique=&recunique($fucourseid);
1.474     albertel 9447:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9448:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9449: 
1.790     albertel 9450: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9451: 			       
                   9452: 	$return.= ($cunique%$cuname+
                   9453: 		   $cunique%$cudom+
                   9454: 		   $cusymb%$cuname+
                   9455: 		   $cusymb%$cudom+
                   9456: 		   $cucourseid%$cuname+
                   9457: 		   $cucourseid%$cudom+
                   9458: 		   $cpart%$cuname+
                   9459: 		   $cpart%$cudom);
                   9460:     } else {
                   9461: 	$return.= ($cunique%$cuname+
                   9462: 		   $cunique%$cudom+
                   9463: 		   $cusymb%$cuname+
                   9464: 		   $cusymb%$cudom+
                   9465: 		   $cucourseid%$cuname+
                   9466: 		   $cucourseid%$cudom);
                   9467:     }
                   9468:     return $return;
1.76      www      9469: }
                   9470: 
                   9471: sub receipt {
1.474     albertel 9472:     my ($part)=@_;
1.790     albertel 9473:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9474:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9475: }
1.260     ng       9476: 
1.790     albertel 9477: sub whichuser {
                   9478:     my ($passedsymb)=@_;
                   9479:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9480:     if (defined($env{'form.grade_symb'})) {
                   9481: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9482: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9483: 	if (!$allowed &&
                   9484: 	    exists($env{'request.course.sec'}) &&
                   9485: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9486: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9487: 			      '/'.$env{'request.course.sec'});
                   9488: 	}
                   9489: 	if ($allowed) {
                   9490: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9491: 	    $courseid=$tmp_courseid;
                   9492: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9493: 	    ($name)=&get_env_multiple('form.grade_username');
                   9494: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9495: 	}
                   9496:     }
                   9497:     if (!$passedsymb) {
                   9498: 	$symb=&symbread();
                   9499:     } else {
                   9500: 	$symb=$passedsymb;
                   9501:     }
                   9502:     $courseid=$env{'request.course.id'};
                   9503:     $domain=$env{'user.domain'};
                   9504:     $name=$env{'user.name'};
                   9505:     if ($name eq 'public' && $domain eq 'public') {
                   9506: 	if (!defined($env{'form.username'})) {
                   9507: 	    $env{'form.username'}.=time.rand(10000000);
                   9508: 	}
                   9509: 	$name.=$env{'form.username'};
                   9510:     }
                   9511:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9512: 
                   9513: }
                   9514: 
1.36      albertel 9515: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9516: # returns either the contents of the file or 
                   9517: # -1 if the file doesn't exist
1.481     raeburn  9518: #
                   9519: # if the target is a file that was uploaded via DOCS, 
                   9520: # a check will be made to see if a current copy exists on the local server,
                   9521: # if it does this will be served, otherwise a copy will be retrieved from
                   9522: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9523: # the local server.   
1.472     albertel 9524: 
1.36      albertel 9525: sub getfile {
1.538     albertel 9526:     my ($file) = @_;
1.609     banghart 9527:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9528:     &repcopy($file);
                   9529:     return &readfile($file);
                   9530: }
                   9531: 
                   9532: sub repcopy_userfile {
                   9533:     my ($file)=@_;
1.609     banghart 9534:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9535:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9536:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9537: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9538:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9539:     if (-e "$file") {
1.828     www      9540: # we already have a local copy, check it out
1.538     albertel 9541: 	my @fileinfo = stat($file);
1.828     www      9542: 	my $rtncode;
                   9543: 	my $info;
1.538     albertel 9544: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9545: 	if ($lwpresp ne 'ok') {
1.828     www      9546: # there is no such file anymore, even though we had a local copy
1.482     albertel 9547: 	    if ($rtncode eq '404') {
1.538     albertel 9548: 		unlink($file);
1.482     albertel 9549: 	    }
                   9550: 	    return -1;
                   9551: 	}
                   9552: 	if ($info < $fileinfo[9]) {
1.828     www      9553: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9554: 	    return 'ok';
1.828     www      9555: 	} else {
                   9556: # the file is outdated, get rid of it
                   9557: 	    unlink($file);
1.482     albertel 9558: 	}
1.828     www      9559:     }
                   9560: # one way or the other, at this point, we don't have the file
                   9561: # construct the correct path for the file
                   9562:     my @parts = ($cdom,$cnum); 
                   9563:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9564: 	push @parts, split(/\//,$1);
                   9565:     }
                   9566:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9567:     foreach my $part (@parts) {
                   9568: 	$path .= '/'.$part;
                   9569: 	if (!-e $path) {
                   9570: 	    mkdir($path,0770);
1.482     albertel 9571: 	}
                   9572:     }
1.828     www      9573: # now the path exists for sure
                   9574: # get a user agent
                   9575:     my $ua=new LWP::UserAgent;
                   9576:     my $transferfile=$file.'.in.transfer';
                   9577: # FIXME: this should flock
                   9578:     if (-e $transferfile) { return 'ok'; }
                   9579:     my $request;
                   9580:     $uri=~s/^\///;
1.980     raeburn  9581:     my $homeserver = &homeserver($cnum,$cdom);
                   9582:     my $protocol = $protocol{$homeserver};
                   9583:     $protocol = 'http' if ($protocol ne 'https');
                   9584:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9585:     my $response=$ua->request($request,$transferfile);
                   9586: # did it work?
                   9587:     if ($response->is_error()) {
                   9588: 	unlink($transferfile);
                   9589: 	&logthis("Userfile repcopy failed for $uri");
                   9590: 	return -1;
                   9591:     }
                   9592: # worked, rename the transfer file
                   9593:     rename($transferfile,$file);
1.607     raeburn  9594:     return 'ok';
1.481     raeburn  9595: }
                   9596: 
1.517     albertel 9597: sub tokenwrapper {
                   9598:     my $uri=shift;
1.980     raeburn  9599:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9600:     $uri=~s|^/||;
1.620     albertel 9601:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9602:     my $token=$1;
1.552     albertel 9603:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9604:     if ($udom && $uname && $file) {
                   9605: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9606:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9607:         my $homeserver = &homeserver($uname,$udom);
                   9608:         my $protocol = $protocol{$homeserver};
                   9609:         $protocol = 'http' if ($protocol ne 'https');
                   9610:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9611:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9612:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9613:     } else {
                   9614:         return '/adm/notfound.html';
                   9615:     }
                   9616: }
                   9617: 
1.828     www      9618: # call with reqtype HEAD: get last modification time
                   9619: # call with reqtype GET: get the file contents
                   9620: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9621: #
1.481     raeburn  9622: sub getuploaded {
                   9623:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9624:     $uri=~s/^\///;
1.980     raeburn  9625:     my $homeserver = &homeserver($cnum,$cdom);
                   9626:     my $protocol = $protocol{$homeserver};
                   9627:     $protocol = 'http' if ($protocol ne 'https');
                   9628:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9629:     my $ua=new LWP::UserAgent;
                   9630:     my $request=new HTTP::Request($reqtype,$uri);
                   9631:     my $response=$ua->request($request);
                   9632:     $$rtncode = $response->code;
1.482     albertel 9633:     if (! $response->is_success()) {
                   9634: 	return 'failed';
                   9635:     }      
                   9636:     if ($reqtype eq 'HEAD') {
1.486     www      9637: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9638:     } elsif ($reqtype eq 'GET') {
                   9639: 	$$info = $response->content;
1.472     albertel 9640:     }
1.482     albertel 9641:     return 'ok';
1.36      albertel 9642: }
                   9643: 
1.481     raeburn  9644: sub readfile {
                   9645:     my $file = shift;
                   9646:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9647:     my $fh;
                   9648:     open($fh,"<$file");
                   9649:     my $a='';
1.800     albertel 9650:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9651:     return $a;
                   9652: }
                   9653: 
1.36      albertel 9654: sub filelocation {
1.590     banghart 9655:     my ($dir,$file) = @_;
                   9656:     my $location;
                   9657:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9658: 
                   9659:     if ($file =~ m-^/adm/-) {
                   9660: 	$file=~s-^/adm/wrapper/-/-;
                   9661: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9662:     }
1.882     albertel 9663: 
1.590     banghart 9664:     if ($file=~m:^/~:) { # is a contruction space reference
                   9665:         $location = $file;
                   9666:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9667:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9668: 	# is a correct contruction space reference
                   9669:         $location = $file;
1.956     raeburn  9670:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9671:         $location = $file;
1.609     banghart 9672:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9673:         my ($udom,$uname,$filename)=
1.811     albertel 9674:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9675:         my $home=&homeserver($uname,$udom);
                   9676:         my $is_me=0;
                   9677:         my @ids=&current_machine_ids();
                   9678:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9679:         if ($is_me) {
1.955     raeburn  9680:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9681:         } else {
                   9682:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9683:   	      $udom.'/'.$uname.'/'.$filename;
                   9684:         }
1.882     albertel 9685:     } elsif ($file =~ m-^/adm/-) {
                   9686: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9687:     } else {
                   9688:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9689:         $file=~s:^/res/:/:;
                   9690:         if ( !( $file =~ m:^/:) ) {
                   9691:             $location = $dir. '/'.$file;
                   9692:         } else {
                   9693:             $location = '/home/httpd/html/res'.$file;
                   9694:         }
1.59      albertel 9695:     }
1.590     banghart 9696:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9697:     while ($location=~m{/\.\./}) {
                   9698: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9699: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9700: 	} else {
                   9701: 	    $location=~ s{/\.\./}{/}g;
                   9702: 	}
                   9703:     } #remove dir/..
1.590     banghart 9704:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9705:     return $location;
1.46      www      9706: }
1.36      albertel 9707: 
1.46      www      9708: sub hreflocation {
                   9709:     my ($dir,$file)=@_;
1.980     raeburn  9710:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9711: 	$file=filelocation($dir,$file);
1.700     albertel 9712:     } elsif ($file=~m-^/adm/-) {
                   9713: 	$file=~s-^/adm/wrapper/-/-;
                   9714: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9715:     }
                   9716:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9717: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9718:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9719: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9720:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9721: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9722: 	    -/uploaded/$1/$2/-x;
1.46      www      9723:     }
1.913     albertel 9724:     if ($file=~ m{^/userfiles/}) {
                   9725: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9726:     }
1.462     albertel 9727:     return $file;
1.465     albertel 9728: }
                   9729: 
                   9730: sub current_machine_domains {
1.853     albertel 9731:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9732: }
                   9733: 
                   9734: sub machine_domains {
                   9735:     my ($hostname) = @_;
1.465     albertel 9736:     my @domains;
1.838     albertel 9737:     my %hostname = &all_hostnames();
1.465     albertel 9738:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9739: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9740: 	if ($hostname eq $name) {
1.844     albertel 9741: 	    push(@domains,&host_domain($id));
1.465     albertel 9742: 	}
                   9743:     }
                   9744:     return @domains;
                   9745: }
                   9746: 
                   9747: sub current_machine_ids {
1.853     albertel 9748:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9749: }
                   9750: 
                   9751: sub machine_ids {
                   9752:     my ($hostname) = @_;
                   9753:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9754:     my @ids;
1.888     albertel 9755:     my %name_to_host = &all_names();
1.889     albertel 9756:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9757: 	return @{ $name_to_host{$hostname} };
                   9758:     }
                   9759:     return;
1.31      www      9760: }
                   9761: 
1.824     raeburn  9762: sub additional_machine_domains {
                   9763:     my @domains;
                   9764:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9765:     while( my $line = <$fh>) {
                   9766:         $line =~ s/\s//g;
                   9767:         push(@domains,$line);
                   9768:     }
                   9769:     return @domains;
                   9770: }
                   9771: 
                   9772: sub default_login_domain {
                   9773:     my $domain = $perlvar{'lonDefDomain'};
                   9774:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9775:     foreach my $posdom (&current_machine_domains(),
                   9776:                         &additional_machine_domains()) {
                   9777:         if (lc($posdom) eq lc($testdomain)) {
                   9778:             $domain=$posdom;
                   9779:             last;
                   9780:         }
                   9781:     }
                   9782:     return $domain;
                   9783: }
                   9784: 
1.31      www      9785: # ------------------------------------------------------------- Declutters URLs
                   9786: 
                   9787: sub declutter {
                   9788:     my $thisfn=shift;
1.569     albertel 9789:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9790:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9791:     $thisfn=~s/^\///;
1.697     albertel 9792:     $thisfn=~s|^adm/wrapper/||;
                   9793:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9794:     $thisfn=~s/^res\///;
1.1032    raeburn  9795:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9796:         $thisfn=~s/\?.+$//;
                   9797:     }
1.268     www      9798:     return $thisfn;
                   9799: }
                   9800: 
                   9801: # ------------------------------------------------------------- Clutter up URLs
                   9802: 
                   9803: sub clutter {
                   9804:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9805:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9806: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9807:        $thisfn='/res'.$thisfn; 
                   9808:     }
1.1031    raeburn  9809:     if ($thisfn !~m|^/adm|) {
                   9810: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9811: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9812: 	} else {
                   9813: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9814: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9815: 	    if ($embstyle eq 'ssi'
                   9816: 		|| ($embstyle eq 'hdn')
                   9817: 		|| ($embstyle eq 'rat')
                   9818: 		|| ($embstyle eq 'prv')
                   9819: 		|| ($embstyle eq 'ign')) {
                   9820: 		#do nothing with these
                   9821: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9822: 		|| ($embstyle eq 'emb')
                   9823: 		|| ($embstyle eq 'wrp')) {
                   9824: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9825: 	    } elsif ($embstyle eq 'unk'
                   9826: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9827: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9828: 	    } else {
1.718     www      9829: #		&logthis("Got a blank emb style");
1.695     albertel 9830: 	    }
1.694     albertel 9831: 	}
                   9832:     }
1.31      www      9833:     return $thisfn;
1.12      www      9834: }
                   9835: 
1.787     albertel 9836: sub clutter_with_no_wrapper {
                   9837:     my $uri = &clutter(shift);
                   9838:     if ($uri =~ m-^/adm/-) {
                   9839: 	$uri =~ s-^/adm/wrapper/-/-;
                   9840: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9841:     }
                   9842:     return $uri;
                   9843: }
                   9844: 
1.557     albertel 9845: sub freeze_escape {
                   9846:     my ($value)=@_;
                   9847:     if (ref($value)) {
                   9848: 	$value=&nfreeze($value);
                   9849: 	return '__FROZEN__'.&escape($value);
                   9850:     }
                   9851:     return &escape($value);
                   9852: }
                   9853: 
1.11      www      9854: 
1.557     albertel 9855: sub thaw_unescape {
                   9856:     my ($value)=@_;
                   9857:     if ($value =~ /^__FROZEN__/) {
                   9858: 	substr($value,0,10,undef);
                   9859: 	$value=&unescape($value);
                   9860: 	return &thaw($value);
                   9861:     }
                   9862:     return &unescape($value);
                   9863: }
                   9864: 
1.436     albertel 9865: sub correct_line_ends {
                   9866:     my ($result)=@_;
                   9867:     $$result =~s/\r\n/\n/mg;
                   9868:     $$result =~s/\r/\n/mg;
1.415     albertel 9869: }
1.1       albertel 9870: # ================================================================ Main Program
                   9871: 
1.184     www      9872: sub goodbye {
1.204     albertel 9873:    &logthis("Starting Shut down");
1.443     albertel 9874: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9875:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9876: #converted
1.599     albertel 9877: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9878:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9879: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9880: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9881: #1.1 only
1.870     albertel 9882: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9883: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9884: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9885: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9886:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9887:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9888:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9889:    &flushcourselogs();
                   9890:    &logthis("Shutting down");
                   9891: }
                   9892: 
1.852     albertel 9893: sub get_dns {
1.869     albertel 9894:     my ($url,$func,$ignore_cache) = @_;
                   9895:     if (!$ignore_cache) {
                   9896: 	my ($content,$cached)=
                   9897: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9898: 	if ($cached) {
                   9899: 	    &$func($content);
                   9900: 	    return;
                   9901: 	}
                   9902:     }
                   9903: 
                   9904:     my %alldns;
1.852     albertel 9905:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9906:     foreach my $dns (<$config>) {
                   9907: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9908:         my $line = $1;
                   9909:         my ($host,$protocol) = split(/:/,$line);
                   9910:         if ($protocol ne 'https') {
                   9911:             $protocol = 'http';
                   9912:         }
                   9913: 	$alldns{$host} = $protocol;
1.869     albertel 9914:     }
                   9915:     while (%alldns) {
                   9916: 	my ($dns) = keys(%alldns);
1.852     albertel 9917: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9918: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9919: 	my $response=$ua->request($request);
1.979     raeburn  9920:         delete($alldns{$dns});
1.852     albertel 9921: 	next if ($response->is_error());
                   9922: 	my @content = split("\n",$response->content);
1.869     albertel 9923: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9924: 	&$func(\@content);
1.869     albertel 9925: 	return;
1.852     albertel 9926:     }
                   9927:     close($config);
1.871     albertel 9928:     my $which = (split('/',$url))[3];
                   9929:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9930:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9931:     my @content = <$config>;
                   9932:     &$func(\@content);
                   9933:     return;
1.852     albertel 9934: }
1.327     albertel 9935: # ------------------------------------------------------------ Read domain file
                   9936: {
1.852     albertel 9937:     my $loaded;
1.846     albertel 9938:     my %domain;
                   9939: 
1.852     albertel 9940:     sub parse_domain_tab {
                   9941: 	my ($lines) = @_;
                   9942: 	foreach my $line (@$lines) {
                   9943: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9944: 
1.846     albertel 9945: 	    chomp($line);
1.852     albertel 9946: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9947: 	    my %this_domain;
                   9948: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9949: 			       'lang_def', 'city', 'longi', 'lati',
                   9950: 			       'primary') {
                   9951: 		$this_domain{$field} = shift(@elements);
                   9952: 	    }
                   9953: 	    $domain{$name} = \%this_domain;
1.852     albertel 9954: 	}
                   9955:     }
1.864     albertel 9956: 
                   9957:     sub reset_domain_info {
                   9958: 	undef($loaded);
                   9959: 	undef(%domain);
                   9960:     }
                   9961: 
1.852     albertel 9962:     sub load_domain_tab {
1.869     albertel 9963: 	my ($ignore_cache) = @_;
                   9964: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9965: 	my $fh;
                   9966: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9967: 	    my @lines = <$fh>;
                   9968: 	    &parse_domain_tab(\@lines);
1.448     albertel 9969: 	}
1.852     albertel 9970: 	close($fh);
                   9971: 	$loaded = 1;
1.327     albertel 9972:     }
1.846     albertel 9973: 
                   9974:     sub domain {
1.852     albertel 9975: 	&load_domain_tab() if (!$loaded);
                   9976: 
1.846     albertel 9977: 	my ($name,$what) = @_;
                   9978: 	return if ( !exists($domain{$name}) );
                   9979: 
                   9980: 	if (!$what) {
                   9981: 	    return $domain{$name}{'description'};
                   9982: 	}
                   9983: 	return $domain{$name}{$what};
                   9984:     }
1.974     raeburn  9985: 
                   9986:     sub domain_info {
                   9987:         &load_domain_tab() if (!$loaded);
                   9988:         return %domain;
                   9989:     }
                   9990: 
1.327     albertel 9991: }
                   9992: 
                   9993: 
1.1       albertel 9994: # ------------------------------------------------------------- Read hosts file
                   9995: {
1.838     albertel 9996:     my %hostname;
1.844     albertel 9997:     my %hostdom;
1.845     albertel 9998:     my %libserv;
1.852     albertel 9999:     my $loaded;
1.888     albertel 10000:     my %name_to_host;
1.1056.4.6  raeburn  10001:     my %internetdom;
1.852     albertel 10002: 
                   10003:     sub parse_hosts_tab {
                   10004: 	my ($file) = @_;
                   10005: 	foreach my $configline (@$file) {
                   10006: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   10007: 	    next if ($configline =~ /^\^/);
                   10008: 	    chomp($configline);
1.1056.4.6  raeburn  10009: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10010: 	    $name=~s/\s//g;
                   10011: 	    if ($id && $domain && $role && $name) {
                   10012: 		$hostname{$id}=$name;
1.888     albertel 10013: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10014: 		$hostdom{$id}=$domain;
                   10015: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10016:                 if (defined($protocol)) {
                   10017:                     if ($protocol eq 'https') {
                   10018:                         $protocol{$id} = $protocol;
                   10019:                     } else {
                   10020:                         $protocol{$id} = 'http'; 
                   10021:                     }
1.968     raeburn  10022:                 } else {
1.969     raeburn  10023:                     $protocol{$id} = 'http';
1.968     raeburn  10024:                 }
1.1056.4.6  raeburn  10025:                 if (defined($intdom)) {
                   10026:                     $internetdom{$id} = $intdom;
                   10027:                 }
1.852     albertel 10028: 	    }
                   10029: 	}
                   10030:     }
1.864     albertel 10031:     
                   10032:     sub reset_hosts_info {
1.897     albertel 10033: 	&purge_remembered();
1.864     albertel 10034: 	&reset_domain_info();
                   10035: 	&reset_hosts_ip_info();
1.892     albertel 10036: 	undef(%name_to_host);
1.864     albertel 10037: 	undef(%hostname);
                   10038: 	undef(%hostdom);
                   10039: 	undef(%libserv);
                   10040: 	undef($loaded);
                   10041:     }
1.1       albertel 10042: 
1.852     albertel 10043:     sub load_hosts_tab {
1.869     albertel 10044: 	my ($ignore_cache) = @_;
                   10045: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10046: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10047: 	my @config = <$config>;
                   10048: 	&parse_hosts_tab(\@config);
                   10049: 	close($config);
                   10050: 	$loaded=1;
1.1       albertel 10051:     }
1.852     albertel 10052: 
1.838     albertel 10053:     sub hostname {
1.852     albertel 10054: 	&load_hosts_tab() if (!$loaded);
                   10055: 
1.838     albertel 10056: 	my ($lonid) = @_;
                   10057: 	return $hostname{$lonid};
                   10058:     }
1.845     albertel 10059: 
1.838     albertel 10060:     sub all_hostnames {
1.852     albertel 10061: 	&load_hosts_tab() if (!$loaded);
                   10062: 
1.838     albertel 10063: 	return %hostname;
                   10064:     }
1.845     albertel 10065: 
1.888     albertel 10066:     sub all_names {
                   10067: 	&load_hosts_tab() if (!$loaded);
                   10068: 
                   10069: 	return %name_to_host;
                   10070:     }
                   10071: 
1.974     raeburn  10072:     sub all_host_domain {
                   10073:         &load_hosts_tab() if (!$loaded);
                   10074:         return %hostdom;
                   10075:     }
                   10076: 
1.845     albertel 10077:     sub is_library {
1.852     albertel 10078: 	&load_hosts_tab() if (!$loaded);
                   10079: 
1.845     albertel 10080: 	return exists($libserv{$_[0]});
                   10081:     }
                   10082: 
                   10083:     sub all_library {
1.852     albertel 10084: 	&load_hosts_tab() if (!$loaded);
                   10085: 
1.845     albertel 10086: 	return %libserv;
                   10087:     }
                   10088: 
1.1056.4.2  raeburn  10089:     sub unique_library {
                   10090:         #2x reverse removes all hostnames that appear more than once
                   10091:         my %unique = reverse &all_library();
                   10092:         return reverse %unique;
                   10093:     }
                   10094: 
1.841     albertel 10095:     sub get_servers {
1.852     albertel 10096: 	&load_hosts_tab() if (!$loaded);
                   10097: 
1.841     albertel 10098: 	my ($domain,$type) = @_;
                   10099: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10100: 	                                          : %hostname;
                   10101: 	my %result;
1.842     albertel 10102: 	if (ref($domain) eq 'ARRAY') {
                   10103: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10104: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10105: 		    $result{$host} = $hostname;
                   10106: 		}
                   10107: 	    }
                   10108: 	} else {
                   10109: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10110: 		if ($hostdom{$host} eq $domain) {
                   10111: 		    $result{$host} = $hostname;
                   10112: 		}
1.841     albertel 10113: 	    }
                   10114: 	}
                   10115: 	return %result;
                   10116:     }
1.845     albertel 10117: 
1.1056.4.2  raeburn  10118:     sub get_unique_servers {
                   10119:         my %unique = reverse &get_servers(@_);
                   10120:         return reverse %unique;
                   10121:     }
                   10122: 
1.844     albertel 10123:     sub host_domain {
1.852     albertel 10124: 	&load_hosts_tab() if (!$loaded);
                   10125: 
1.844     albertel 10126: 	my ($lonid) = @_;
                   10127: 	return $hostdom{$lonid};
                   10128:     }
                   10129: 
1.841     albertel 10130:     sub all_domains {
1.852     albertel 10131: 	&load_hosts_tab() if (!$loaded);
                   10132: 
1.841     albertel 10133: 	my %seen;
                   10134: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10135: 	return @uniq;
                   10136:     }
1.1056.4.3  raeburn  10137: 
                   10138:     sub internet_dom {
                   10139:         &load_hosts_tab() if (!$loaded);
                   10140: 
                   10141:         my ($lonid) = @_;
                   10142:         return $internetdom{$lonid};
                   10143:     }
1.1       albertel 10144: }
                   10145: 
1.847     albertel 10146: { 
                   10147:     my %iphost;
1.856     albertel 10148:     my %name_to_ip;
                   10149:     my %lonid_to_ip;
1.869     albertel 10150: 
1.847     albertel 10151:     sub get_hosts_from_ip {
                   10152: 	my ($ip) = @_;
                   10153: 	my %iphosts = &get_iphost();
                   10154: 	if (ref($iphosts{$ip})) {
                   10155: 	    return @{$iphosts{$ip}};
                   10156: 	}
                   10157: 	return;
1.839     albertel 10158:     }
1.864     albertel 10159:     
                   10160:     sub reset_hosts_ip_info {
                   10161: 	undef(%iphost);
                   10162: 	undef(%name_to_ip);
                   10163: 	undef(%lonid_to_ip);
                   10164:     }
1.856     albertel 10165: 
                   10166:     sub get_host_ip {
                   10167: 	my ($lonid) = @_;
                   10168: 	if (exists($lonid_to_ip{$lonid})) {
                   10169: 	    return $lonid_to_ip{$lonid};
                   10170: 	}
                   10171: 	my $name=&hostname($lonid);
                   10172:    	my $ip = gethostbyname($name);
                   10173: 	return if (!$ip || length($ip) ne 4);
                   10174: 	$ip=inet_ntoa($ip);
                   10175: 	$name_to_ip{$name}   = $ip;
                   10176: 	$lonid_to_ip{$lonid} = $ip;
                   10177: 	return $ip;
                   10178:     }
1.847     albertel 10179:     
                   10180:     sub get_iphost {
1.869     albertel 10181: 	my ($ignore_cache) = @_;
1.894     albertel 10182: 
1.869     albertel 10183: 	if (!$ignore_cache) {
                   10184: 	    if (%iphost) {
                   10185: 		return %iphost;
                   10186: 	    }
                   10187: 	    my ($ip_info,$cached)=
                   10188: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10189: 	    if ($cached) {
                   10190: 		%iphost      = %{$ip_info->[0]};
                   10191: 		%name_to_ip  = %{$ip_info->[1]};
                   10192: 		%lonid_to_ip = %{$ip_info->[2]};
                   10193: 		return %iphost;
                   10194: 	    }
                   10195: 	}
1.894     albertel 10196: 
                   10197: 	# get yesterday's info for fallback
                   10198: 	my %old_name_to_ip;
                   10199: 	my ($ip_info,$cached)=
                   10200: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10201: 	if ($cached) {
                   10202: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10203: 	}
                   10204: 
1.888     albertel 10205: 	my %name_to_host = &all_names();
                   10206: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10207: 	    my $ip;
                   10208: 	    if (!exists($name_to_ip{$name})) {
                   10209: 		$ip = gethostbyname($name);
                   10210: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10211: 		    if (defined($old_name_to_ip{$name})) {
                   10212: 			$ip = $old_name_to_ip{$name};
                   10213: 			&logthis("Can't find $name defaulting to old $ip");
                   10214: 		    } else {
                   10215: 			&logthis("Name $name no IP found");
                   10216: 			next;
                   10217: 		    }
                   10218: 		} else {
                   10219: 		    $ip=inet_ntoa($ip);
1.847     albertel 10220: 		}
                   10221: 		$name_to_ip{$name} = $ip;
                   10222: 	    } else {
                   10223: 		$ip = $name_to_ip{$name};
1.653     albertel 10224: 	    }
1.888     albertel 10225: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10226: 		$lonid_to_ip{$id} = $ip;
                   10227: 	    }
                   10228: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10229: 	}
1.869     albertel 10230: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10231: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10232: 				      48*60*60);
1.869     albertel 10233: 
1.847     albertel 10234: 	return %iphost;
1.598     albertel 10235:     }
                   10236: 
1.992     raeburn  10237:     #
                   10238:     #  Given a DNS returns the loncapa host name for that DNS 
                   10239:     # 
                   10240:     sub host_from_dns {
                   10241:         my ($dns) = @_;
                   10242:         my @hosts;
                   10243:         my $ip;
                   10244: 
1.993     raeburn  10245:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10246:             $ip = $name_to_ip{$dns};
                   10247:         }
                   10248:         if (!$ip) {
                   10249:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10250:             if (length($ip) == 4) { 
                   10251: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10252:             }
                   10253:         }
                   10254:         if ($ip) {
                   10255: 	    @hosts = get_hosts_from_ip($ip);
                   10256: 	    return $hosts[0];
                   10257:         }
                   10258:         return undef;
1.986     foxr     10259:     }
1.992     raeburn  10260: 
1.1056.4.3  raeburn  10261:     sub get_internet_names {
                   10262:         my ($lonid) = @_;
                   10263:         return if ($lonid eq '');
                   10264:         my ($idnref,$cached)=
                   10265:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10266:         if ($cached) {
                   10267:             return $idnref;
                   10268:         }
                   10269:         my $ip = &get_host_ip($lonid);
                   10270:         my @hosts = &get_hosts_from_ip($ip);
                   10271:         my %iphost = &get_iphost();
                   10272:         my (@idns,%seen);
                   10273:         foreach my $id (@hosts) {
                   10274:             my $dom = &host_domain($id);
                   10275:             my $prim_id = &domain($dom,'primary');
                   10276:             my $prim_ip = &get_host_ip($prim_id);
                   10277:             next if ($seen{$prim_ip});
                   10278:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10279:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10280:                     my $intdom = &internet_dom($id);
                   10281:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10282:                         push(@idns,$intdom);
                   10283:                     }
                   10284:                 }
                   10285:             }
                   10286:             $seen{$prim_ip} = 1;
                   10287:         }
                   10288:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10289:     }
                   10290: 
                   10291: }
                   10292: 
                   10293: sub all_loncaparevs {
                   10294:     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     10295: }
                   10296: 
1.862     albertel 10297: BEGIN {
                   10298: 
                   10299: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10300:     unless ($readit) {
                   10301: {
                   10302:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10303:     %perlvar = (%perlvar,%{$configvars});
                   10304: }
                   10305: 
                   10306: 
1.1       albertel 10307: # ------------------------------------------------------ Read spare server file
                   10308: {
1.448     albertel 10309:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10310: 
                   10311:     while (my $configline=<$config>) {
                   10312:        chomp($configline);
1.284     matthew  10313:        if ($configline) {
1.784     albertel 10314: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10315: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10316: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10317:        }
                   10318:     }
1.448     albertel 10319:     close($config);
1.1       albertel 10320: }
1.11      www      10321: # ------------------------------------------------------------ Read permissions
                   10322: {
1.448     albertel 10323:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10324: 
                   10325:     while (my $configline=<$config>) {
1.448     albertel 10326: 	chomp($configline);
                   10327: 	if ($configline) {
                   10328: 	    my ($role,$perm)=split(/ /,$configline);
                   10329: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10330: 	}
1.11      www      10331:     }
1.448     albertel 10332:     close($config);
1.11      www      10333: }
                   10334: 
                   10335: # -------------------------------------------- Read plain texts for permissions
                   10336: {
1.448     albertel 10337:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10338: 
                   10339:     while (my $configline=<$config>) {
1.448     albertel 10340: 	chomp($configline);
                   10341: 	if ($configline) {
1.742     raeburn  10342: 	    my ($short,@plain)=split(/:/,$configline);
                   10343:             %{$prp{$short}} = ();
                   10344: 	    if (@plain > 0) {
                   10345:                 $prp{$short}{'std'} = $plain[0];
                   10346:                 for (my $i=1; $i<@plain; $i++) {
                   10347:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10348:                 }
                   10349:             }
1.448     albertel 10350: 	}
1.135     www      10351:     }
1.448     albertel 10352:     close($config);
1.135     www      10353: }
                   10354: 
                   10355: # ---------------------------------------------------------- Read package table
                   10356: {
1.448     albertel 10357:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10358: 
                   10359:     while (my $configline=<$config>) {
1.483     albertel 10360: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10361: 	chomp($configline);
                   10362: 	my ($short,$plain)=split(/:/,$configline);
                   10363: 	my ($pack,$name)=split(/\&/,$short);
                   10364: 	if ($plain ne '') {
                   10365: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10366: 	    $packagetab{$short}=$plain; 
                   10367: 	}
1.11      www      10368:     }
1.448     albertel 10369:     close($config);
1.329     matthew  10370: }
                   10371: 
1.1056.4.3  raeburn  10372: # ---------------------------------------------------------- Read loncaparev table
                   10373: {
                   10374:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10375:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10376:             while (my $configline=<$config>) {
                   10377:                 chomp($configline);
                   10378:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10379:                 $loncaparevs{$hostid}=$loncaparev;
                   10380:             }
                   10381:             close($config);
                   10382:         }
                   10383:     }
                   10384: }
                   10385: 
                   10386: # ---------------------------------------------------------- Read serverhostID table
                   10387: {
                   10388:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10389:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10390:             while (my $configline=<$config>) {
                   10391:                 chomp($configline);
                   10392:                 my ($name,$id)=split(/:/,$configline);
                   10393:                 $serverhomeIDs{$name}=$id;
                   10394:             }
                   10395:             close($config);
                   10396:         }
                   10397:     }
                   10398: }
                   10399: 
1.1056.4.5  raeburn  10400: {
                   10401:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10402:     if (-e $file) {
                   10403:         my $parser = HTML::LCParser->new($file);
                   10404:         while (my $token = $parser->get_token()) {
                   10405:             if ($token->[0] eq 'S') {
                   10406:                 my $item = $token->[1];
                   10407:                 my $name = $token->[2]{'name'};
                   10408:                 my $value = $token->[2]{'value'};
                   10409:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10410:                     my $release = $parser->get_text();
                   10411:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10412:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10413:                 }
                   10414:             }
                   10415:         }
                   10416:     }
                   10417: }
                   10418: 
1.329     matthew  10419: # ------------- set up temporary directory
                   10420: {
                   10421:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10422: 
1.11      www      10423: }
                   10424: 
1.794     albertel 10425: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10426: 				'compress_threshold'=> 20_000,
                   10427:  			        });
1.185     www      10428: 
1.281     www      10429: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10430: $dumpcount=0;
1.958     www      10431: $locknum=0;
1.22      www      10432: 
1.163     harris41 10433: &logtouch();
1.672     albertel 10434: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10435: $readit=1;
1.564     albertel 10436:     {
                   10437: 	use integer;
                   10438: 	my $test=(2**32)+1;
1.568     albertel 10439: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10440: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10441:     }
1.195     www      10442: }
1.1       albertel 10443: }
1.179     www      10444: 
1.1       albertel 10445: 1;
1.191     harris41 10446: __END__
                   10447: 
1.243     albertel 10448: =pod
                   10449: 
1.191     harris41 10450: =head1 NAME
                   10451: 
1.243     albertel 10452: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10453: 
                   10454: =head1 SYNOPSIS
                   10455: 
1.243     albertel 10456: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10457: 
                   10458:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10459: 
1.243     albertel 10460: Common parameters:
                   10461: 
                   10462: =over 4
                   10463: 
                   10464: =item *
                   10465: 
                   10466: $uname : an internal username (if $cname expecting a course Id specifically)
                   10467: 
                   10468: =item *
                   10469: 
                   10470: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10471: 
                   10472: =item *
                   10473: 
                   10474: $symb : a resource instance identifier
                   10475: 
                   10476: =item *
                   10477: 
                   10478: $namespace : the name of a .db file that contains the data needed or
                   10479: being set.
                   10480: 
                   10481: =back
                   10482: 
1.394     bowersj2 10483: =head1 OVERVIEW
1.191     harris41 10484: 
1.394     bowersj2 10485: lonnet provides subroutines which interact with the
                   10486: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10487: about classes, users, and resources.
1.243     albertel 10488: 
                   10489: For many of these objects you can also use this to store data about
                   10490: them or modify them in various ways.
1.191     harris41 10491: 
1.394     bowersj2 10492: =head2 Symbs
1.191     harris41 10493: 
1.394     bowersj2 10494: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10495: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10496: map, the resource number of the resource in the map, and the URL of
                   10497: the resource itself. The latter is somewhat redundant, but might help
                   10498: if maps change.
                   10499: 
                   10500: An example is
                   10501: 
                   10502:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10503: 
                   10504: The respective map entry is
                   10505: 
                   10506:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10507:   title="Problem 2">
                   10508:  </resource>
                   10509: 
                   10510: Symbs are used by the random number generator, as well as to store and
                   10511: restore data specific to a certain instance of for example a problem.
                   10512: 
                   10513: =head2 Storing And Retrieving Data
                   10514: 
                   10515: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10516: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10517: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10518: is is the non-critical message twin of cstore. These functions are for
                   10519: handlers to store a perl hash to a user's permanent data space in an
                   10520: easy manner, and to retrieve it again on another call. It is expected
                   10521: that a handler would use this once at the beginning to retrieve data,
                   10522: and then again once at the end to send only the new data back.
                   10523: 
                   10524: The data is stored in the user's data directory on the user's
                   10525: homeserver under the ID of the course.
                   10526: 
                   10527: The hash that is returned by restore will have all of the previous
                   10528: value for all of the elements of the hash.
                   10529: 
                   10530: Example:
                   10531: 
                   10532:  #creating a hash
                   10533:  my %hash;
                   10534:  $hash{'foo'}='bar';
                   10535: 
                   10536:  #storing it
                   10537:  &Apache::lonnet::cstore(\%hash);
                   10538: 
                   10539:  #changing a value
                   10540:  $hash{'foo'}='notbar';
                   10541: 
                   10542:  #adding a new value
                   10543:  $hash{'bar'}='foo';
                   10544:  &Apache::lonnet::cstore(\%hash);
                   10545: 
                   10546:  #retrieving the hash
                   10547:  my %history=&Apache::lonnet::restore();
                   10548: 
                   10549:  #print the hash
                   10550:  foreach my $key (sort(keys(%history))) {
                   10551:    print("\%history{$key} = $history{$key}");
                   10552:  }
                   10553: 
                   10554: Will print out:
1.191     harris41 10555: 
1.394     bowersj2 10556:  %history{1:foo} = bar
                   10557:  %history{1:keys} = foo:timestamp
                   10558:  %history{1:timestamp} = 990455579
                   10559:  %history{2:bar} = foo
                   10560:  %history{2:foo} = notbar
                   10561:  %history{2:keys} = foo:bar:timestamp
                   10562:  %history{2:timestamp} = 990455580
                   10563:  %history{bar} = foo
                   10564:  %history{foo} = notbar
                   10565:  %history{timestamp} = 990455580
                   10566:  %history{version} = 2
                   10567: 
                   10568: Note that the special hash entries C<keys>, C<version> and
                   10569: C<timestamp> were added to the hash. C<version> will be equal to the
                   10570: total number of versions of the data that have been stored. The
                   10571: C<timestamp> attribute will be the UNIX time the hash was
                   10572: stored. C<keys> is available in every historical section to list which
                   10573: keys were added or changed at a specific historical revision of a
                   10574: hash.
                   10575: 
                   10576: B<Warning>: do not store the hash that restore returns directly. This
                   10577: will cause a mess since it will restore the historical keys as if the
                   10578: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10579: 
1.394     bowersj2 10580: Calling convention:
1.191     harris41 10581: 
1.394     bowersj2 10582:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10583:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10584: 
1.394     bowersj2 10585: For more detailed information, see lonnet specific documentation.
1.191     harris41 10586: 
1.394     bowersj2 10587: =head1 RETURN MESSAGES
1.191     harris41 10588: 
1.394     bowersj2 10589: =over 4
1.191     harris41 10590: 
1.394     bowersj2 10591: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10592: 
1.394     bowersj2 10593: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10594: when the connection is brought back up
1.191     harris41 10595: 
1.394     bowersj2 10596: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10597: for later delivery
1.191     harris41 10598: 
1.967     bisitz   10599: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10600: 
1.394     bowersj2 10601: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10602: that was requested
1.191     harris41 10603: 
1.243     albertel 10604: =back
1.191     harris41 10605: 
1.243     albertel 10606: =head1 PUBLIC SUBROUTINES
1.191     harris41 10607: 
1.243     albertel 10608: =head2 Session Environment Functions
1.191     harris41 10609: 
1.243     albertel 10610: =over 4
1.191     harris41 10611: 
1.394     bowersj2 10612: =item * 
                   10613: X<appenv()>
1.949     raeburn  10614: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10615: the user envirnoment file, and will be restored for each access this
1.620     albertel 10616: user makes during this session, also modifies the %env for the current
1.949     raeburn  10617: process. Optional rolesarrayref - if defined contains a reference to an array
                   10618: of roles which are exempt from the restriction on modifying user.role entries 
                   10619: in the user's environment.db and in %env.    
1.191     harris41 10620: 
                   10621: =item *
1.394     bowersj2 10622: X<delenv()>
1.987     raeburn  10623: B<delenv($delthis,$regexp)>: removes all items from the session
                   10624: environment file that begin with $delthis. If the 
                   10625: optional second arg - $regexp - is true, $delthis is treated as a 
                   10626: regular expression, otherwise \Q$delthis\E is used. 
                   10627: The values are also deleted from the current processes %env.
1.191     harris41 10628: 
1.795     albertel 10629: =item * get_env_multiple($name) 
                   10630: 
                   10631: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10632: values may be defined and end up as an array ref.
                   10633: 
                   10634: returns an array of values
                   10635: 
1.243     albertel 10636: =back
                   10637: 
                   10638: =head2 User Information
1.191     harris41 10639: 
1.243     albertel 10640: =over 4
1.191     harris41 10641: 
                   10642: =item *
1.394     bowersj2 10643: X<queryauthenticate()>
                   10644: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10645: authentication scheme
                   10646: 
                   10647: =item *
1.394     bowersj2 10648: X<authenticate()>
1.1056.4.3  raeburn  10649: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10650: authenticate user from domain's lib servers (first use the current
                   10651: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10652: $checkdefauth is optional (value is 1 if a check should be made to
                   10653:    authenticate user using default authentication method, and allow
                   10654:    account creation if username does not have account in the domain).
                   10655: $clientcancheckhost is optional (value is 1 if checking whether the
                   10656:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10657: 
                   10658: =item *
1.394     bowersj2 10659: X<homeserver()>
                   10660: B<homeserver($uname,$udom)>: find the server which has
                   10661: the user's directory and files (there must be only one), this caches
                   10662: the answer, and also caches if there is a borken connection.
1.191     harris41 10663: 
                   10664: =item *
1.394     bowersj2 10665: X<idget()>
                   10666: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10667: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10668: username, and only 1 username per ID in a specific domain) (returns
                   10669: hash: id=>name,id=>name)
1.191     harris41 10670: 
                   10671: =item *
1.394     bowersj2 10672: X<idrget()>
                   10673: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10674: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10675: 
                   10676: =item *
1.394     bowersj2 10677: X<idput()>
                   10678: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10679: 
                   10680: =item *
1.394     bowersj2 10681: X<rolesinit()>
                   10682: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10683: 
                   10684: =item *
1.551     albertel 10685: X<getsection()>
                   10686: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10687: course $cname, return section name/number or '' for "not in course"
                   10688: and '-1' for "no section"
                   10689: 
                   10690: =item *
1.394     bowersj2 10691: X<userenvironment()>
                   10692: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10693: passed in @what from the requested user's environment, returns a hash
                   10694: 
1.858     raeburn  10695: =item * 
                   10696: X<userlog_query()>
1.859     albertel 10697: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10698: activity.log file. %filters defines filters applied when parsing the
                   10699: log file. These can be start or end timestamps, or the type of action
                   10700: - log to look for Login or Logout events, check for Checkin or
                   10701: Checkout, role for role selection. The response is in the form
                   10702: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10703: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10704: 
1.243     albertel 10705: =back
                   10706: 
                   10707: =head2 User Roles
                   10708: 
                   10709: =over 4
                   10710: 
                   10711: =item *
                   10712: 
1.810     raeburn  10713: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10714:  F: full access
                   10715:  U,I,K: authentication modes (cxx only)
                   10716:  '': forbidden
                   10717:  1: user needs to choose course
                   10718:  2: browse allowed
1.766     albertel 10719:  A: passphrase authentication needed
1.243     albertel 10720: 
                   10721: =item *
                   10722: 
                   10723: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10724: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10725: and course level
                   10726: 
                   10727: =item *
                   10728: 
1.988     raeburn  10729: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10730: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10731: $type is Course (default) or Community.
1.988     raeburn  10732: If $forcedefault evaluates to true, text returned will be default 
                   10733: text for $type. Otherwise, if this is a course, the text returned 
                   10734: will be a custom name for the role (if defined in the course's 
                   10735: environment).  If no custom name is defined the default is returned.
                   10736:    
1.832     raeburn  10737: =item *
                   10738: 
1.935     raeburn  10739: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10740: All arguments are optional. Returns a hash of a roles, either for
                   10741: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10742: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10743: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10744: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10745: For each key, value is set to colon-separated start and end times for
                   10746: the role.  If no username and domain are specified, will default to
1.934     raeburn  10747: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10748: of role statuses (active, future or previous), roles 
                   10749: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10750: to restrict the list of roles reported. If no array ref is 
                   10751: provided for types, will default to return only active roles.
1.834     albertel 10752: 
1.243     albertel 10753: =back
                   10754: 
                   10755: =head2 User Modification
                   10756: 
                   10757: =over 4
                   10758: 
                   10759: =item *
                   10760: 
1.957     raeburn  10761: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10762: user for the level given by URL.  Optional start and end dates (leave empty
                   10763: string or zero for "no date")
1.191     harris41 10764: 
                   10765: =item *
                   10766: 
1.243     albertel 10767: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10768: change a users, password, possible return values are: ok,
                   10769: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10770: refused
1.191     harris41 10771: 
                   10772: =item *
                   10773: 
1.243     albertel 10774: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10775: 
                   10776: =item *
                   10777: 
1.1056.4.1  raeburn  10778: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10779:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10780: 
                   10781: will update user information (firstname,middlename,lastname,generation,
                   10782: permanentemail), and if forceid is true, student/employee ID also.
                   10783: A user's institutional affiliation(s) can also be updated.
                   10784: User information fields will not be overwritten with empty entries 
                   10785: unless the field is included in the $candelete array reference.
                   10786: This array is included when a single user is modified via "Manage Users",
                   10787: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10788: 
                   10789: =item *
                   10790: 
1.286     matthew  10791: modifystudent
                   10792: 
1.957     raeburn  10793: modify a student's enrollment and identification information.
1.286     matthew  10794: The course id is resolved based on the current users environment.  
                   10795: This means the envoking user must be a course coordinator or otherwise
                   10796: associated with a course.
                   10797: 
1.297     matthew  10798: This call is essentially a wrapper for lonnet::modifyuser and
                   10799: lonnet::modify_student_enrollment
1.286     matthew  10800: 
                   10801: Inputs: 
                   10802: 
                   10803: =over 4
                   10804: 
1.957     raeburn  10805: =item B<$udom> Student's loncapa domain
1.286     matthew  10806: 
1.957     raeburn  10807: =item B<$uname> Student's loncapa login name
1.286     matthew  10808: 
1.964     bisitz   10809: =item B<$uid> Student/Employee ID
1.286     matthew  10810: 
1.957     raeburn  10811: =item B<$umode> Student's authentication mode
1.286     matthew  10812: 
1.957     raeburn  10813: =item B<$upass> Student's password
1.286     matthew  10814: 
1.957     raeburn  10815: =item B<$first> Student's first name
1.286     matthew  10816: 
1.957     raeburn  10817: =item B<$middle> Student's middle name
1.286     matthew  10818: 
1.957     raeburn  10819: =item B<$last> Student's last name
1.286     matthew  10820: 
1.957     raeburn  10821: =item B<$gene> Student's generation
1.286     matthew  10822: 
1.957     raeburn  10823: =item B<$usec> Student's section in course
1.286     matthew  10824: 
                   10825: =item B<$end> Unix time of the roles expiration
                   10826: 
                   10827: =item B<$start> Unix time of the roles start date
                   10828: 
                   10829: =item B<$forceid> If defined, allow $uid to be changed
                   10830: 
                   10831: =item B<$desiredhome> server to use as home server for student
                   10832: 
1.957     raeburn  10833: =item B<$email> Student's permanent e-mail address
                   10834: 
                   10835: =item B<$type> Type of enrollment (auto or manual)
                   10836: 
1.963     raeburn  10837: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10838: 
                   10839: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10840: 
1.963     raeburn  10841: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10842: 
1.963     raeburn  10843: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10844: 
1.963     raeburn  10845: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10846: 
1.286     matthew  10847: =back
1.297     matthew  10848: 
                   10849: =item *
                   10850: 
                   10851: modify_student_enrollment
                   10852: 
                   10853: Change a students enrollment status in a class.  The environment variable
                   10854: 'role.request.course' must be defined for this function to proceed.
                   10855: 
                   10856: Inputs:
                   10857: 
                   10858: =over 4
                   10859: 
                   10860: =item $udom, students domain
                   10861: 
                   10862: =item $uname, students name
                   10863: 
                   10864: =item $uid, students user id
                   10865: 
                   10866: =item $first, students first name
                   10867: 
                   10868: =item $middle
                   10869: 
                   10870: =item $last
                   10871: 
                   10872: =item $gene
                   10873: 
                   10874: =item $usec
                   10875: 
                   10876: =item $end
                   10877: 
                   10878: =item $start
                   10879: 
1.957     raeburn  10880: =item $type
                   10881: 
                   10882: =item $locktype
                   10883: 
                   10884: =item $cid
                   10885: 
                   10886: =item $selfenroll
                   10887: 
                   10888: =item $context
                   10889: 
1.297     matthew  10890: =back
                   10891: 
1.191     harris41 10892: 
                   10893: =item *
                   10894: 
1.243     albertel 10895: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10896: custom role; give a custom role to a user for the level given by URL.  Specify
                   10897: name and domain of role author, and role name
1.191     harris41 10898: 
                   10899: =item *
                   10900: 
1.243     albertel 10901: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10902: 
                   10903: =item *
                   10904: 
1.243     albertel 10905: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10906: 
                   10907: =back
                   10908: 
                   10909: =head2 Course Infomation
                   10910: 
                   10911: =over 4
1.191     harris41 10912: 
                   10913: =item *
                   10914: 
1.631     albertel 10915: coursedescription($courseid) : returns a hash of information about the
                   10916: specified course id, including all environment settings for the
                   10917: course, the description of the course will be in the hash under the
                   10918: key 'description'
1.191     harris41 10919: 
                   10920: =item *
                   10921: 
1.624     albertel 10922: resdata($name,$domain,$type,@which) : request for current parameter
                   10923: setting for a specific $type, where $type is either 'course' or 'user',
                   10924: @what should be a list of parameters to ask about. This routine caches
                   10925: answers for 5 minutes.
1.243     albertel 10926: 
1.877     foxr     10927: =item *
                   10928: 
                   10929: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10930: data base, returning a hash that is keyed by the resource name and has
                   10931: values that are the resource value.  I believe that the timestamps and
                   10932: versions are also returned.
                   10933: 
                   10934: 
1.243     albertel 10935: =back
                   10936: 
                   10937: =head2 Course Modification
                   10938: 
                   10939: =over 4
1.191     harris41 10940: 
                   10941: =item *
                   10942: 
1.243     albertel 10943: writecoursepref($courseid,%prefs) : write preferences (environment
                   10944: database) for a course
1.191     harris41 10945: 
                   10946: =item *
                   10947: 
1.1011    raeburn  10948: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10949: 
                   10950: =item *
                   10951: 
1.1038    raeburn  10952: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10953: 
                   10954: =back
                   10955: 
                   10956: =head2 Resource Subroutines
                   10957: 
                   10958: =over 4
1.191     harris41 10959: 
                   10960: =item *
                   10961: 
1.243     albertel 10962: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10963: 
                   10964: =item *
                   10965: 
1.243     albertel 10966: repcopy($filename) : subscribes to the requested file, and attempts to
                   10967: replicate from the owning library server, Might return
1.607     raeburn  10968: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10969: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10970: resource. Expects the local filesystem pathname
                   10971: (/home/httpd/html/res/....)
                   10972: 
                   10973: =back
                   10974: 
                   10975: =head2 Resource Information
                   10976: 
                   10977: =over 4
1.191     harris41 10978: 
                   10979: =item *
                   10980: 
1.243     albertel 10981: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10982: a vairety of different possible values, $varname should be a request
                   10983: string, and the other parameters can be used to specify who and what
                   10984: one is asking about.
                   10985: 
                   10986: Possible values for $varname are environment.lastname (or other item
                   10987: from the envirnment hash), user.name (or someother aspect about the
                   10988: user), resource.0.maxtries (or some other part and parameter of a
                   10989: resource)
1.204     albertel 10990: 
                   10991: =item *
                   10992: 
1.243     albertel 10993: directcondval($number) : get current value of a condition; reads from a state
                   10994: string
1.204     albertel 10995: 
                   10996: =item *
                   10997: 
1.243     albertel 10998: condval($condidx) : value of condition index based on state
1.204     albertel 10999: 
                   11000: =item *
                   11001: 
1.243     albertel 11002: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11003: resource's metadata, $what should be either a specific key, or either
                   11004: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11005: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11006: 
                   11007: this function automatically caches all requests
1.191     harris41 11008: 
                   11009: =item *
                   11010: 
1.243     albertel 11011: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11012: network of library servers; returns file handle of where SQL and regex results
                   11013: will be stored for query
1.191     harris41 11014: 
                   11015: =item *
                   11016: 
1.243     albertel 11017: symbread($filename) : return symbolic list entry (filename argument optional);
                   11018: returns the data handle
1.191     harris41 11019: 
                   11020: =item *
                   11021: 
1.243     albertel 11022: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11023: a possible symb for the URL in $thisfn, and if is an encryypted
                   11024: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11025: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11026: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11027: 
1.191     harris41 11028: 
                   11029: =item *
                   11030: 
1.243     albertel 11031: symbclean($symb) : removes versions numbers from a symb, returns the
                   11032: cleaned symb
1.191     harris41 11033: 
                   11034: =item *
                   11035: 
1.243     albertel 11036: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11037: course map, user must be in a course for it to work.
1.191     harris41 11038: 
                   11039: =item *
                   11040: 
1.243     albertel 11041: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11042: 
                   11043: =item *
                   11044: 
1.243     albertel 11045: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11046: a random seed, all arguments are optional, if they aren't sent it uses the
                   11047: environment to derive them. Note: if symb isn't sent and it can't get one
                   11048: from &symbread it will use the current time as its return value
1.191     harris41 11049: 
                   11050: =item *
                   11051: 
1.243     albertel 11052: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11053: unfakeable, receipt
1.191     harris41 11054: 
                   11055: =item *
                   11056: 
1.620     albertel 11057: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11058: 
                   11059: =item *
                   11060: 
1.243     albertel 11061: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11062: 
                   11063: =item *
                   11064: 
1.243     albertel 11065: 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 11066: 
                   11067: =item *
                   11068: 
1.243     albertel 11069: 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 11070: 
                   11071: =item *
                   11072: 
1.243     albertel 11073: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11074: 
                   11075: =item *
                   11076: 
1.243     albertel 11077: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11078: forcing spreadsheet to reevaluate the resource scores next time.
                   11079: 
                   11080: =back
                   11081: 
                   11082: =head2 Storing/Retreiving Data
                   11083: 
                   11084: =over 4
1.191     harris41 11085: 
                   11086: =item *
                   11087: 
1.243     albertel 11088: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11089: for this url; hashref needs to be given and should be a \%hashname; the
                   11090: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11091: be derived from the env
1.191     harris41 11092: 
                   11093: =item *
                   11094: 
1.243     albertel 11095: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11096: uses critical subroutine
1.191     harris41 11097: 
                   11098: =item *
                   11099: 
1.243     albertel 11100: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11101: all args are optional
1.191     harris41 11102: 
                   11103: =item *
                   11104: 
1.717     albertel 11105: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11106: dumps the complete (or key matching regexp) namespace into a hash
                   11107: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11108: normally &store()ed into
                   11109: 
                   11110: $range should be either an integer '100' (give me the first 100
                   11111:                                            matching records)
                   11112:               or be  two integers sperated by a - with no spaces
                   11113:                  '30-50' (give me the 30th through the 50th matching
                   11114:                           records)
                   11115: 
                   11116: 
                   11117: =item *
                   11118: 
                   11119: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11120: replaces a &store() version of data with a replacement set of data
                   11121: for a particular resource in a namespace passed in the $storehash hash 
                   11122: reference
                   11123: 
                   11124: =item *
                   11125: 
1.243     albertel 11126: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11127: works very similar to store/cstore, but all data is stored in a
                   11128: temporary location and can be reset using tmpreset, $storehash should
                   11129: be a hash reference, returns nothing on success
1.191     harris41 11130: 
                   11131: =item *
                   11132: 
1.243     albertel 11133: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11134: similar to restore, but all data is stored in a temporary location and
                   11135: can be reset using tmpreset. Returns a hash of values on success,
                   11136: error string otherwise.
1.191     harris41 11137: 
                   11138: =item *
                   11139: 
1.243     albertel 11140: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11141: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11142: 
                   11143: =item *
                   11144: 
1.243     albertel 11145: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11146: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11147: 
                   11148: =item *
                   11149: 
1.243     albertel 11150: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11151: namesp ($udom and $uname are optional)
1.191     harris41 11152: 
                   11153: =item *
                   11154: 
1.702     albertel 11155: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11156: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11157: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11158: 
1.702     albertel 11159: $range should be either an integer '100' (give me the first 100
                   11160:                                            matching records)
                   11161:               or be  two integers sperated by a - with no spaces
                   11162:                  '30-50' (give me the 30th through the 50th matching
                   11163:                           records)
1.449     matthew  11164: =item *
                   11165: 
                   11166: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11167: $store can be a scalar, an array reference, or if the amount to be 
                   11168: incremented is > 1, a hash reference.
                   11169: 
                   11170: ($udom and $uname are optional)
1.191     harris41 11171: 
                   11172: =item *
                   11173: 
1.243     albertel 11174: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11175: ($udom and $uname are optional)
1.191     harris41 11176: 
                   11177: =item *
                   11178: 
1.243     albertel 11179: cput($namespace,$storehash,$udom,$uname) : critical put
                   11180: ($udom and $uname are optional)
1.191     harris41 11181: 
                   11182: =item *
                   11183: 
1.748     albertel 11184: newput($namespace,$storehash,$udom,$uname) :
                   11185: 
                   11186: Attempts to store the items in the $storehash, but only if they don't
                   11187: currently exist, if this succeeds you can be certain that you have 
                   11188: successfully created a new key value pair in the $namespace db.
                   11189: 
                   11190: 
                   11191: Args:
                   11192:  $namespace: name of database to store values to
                   11193:  $storehash: hashref to store to the db
                   11194:  $udom: (optional) domain of user containing the db
                   11195:  $uname: (optional) name of user caontaining the db
                   11196: 
                   11197: Returns:
                   11198:  'ok' -> succeeded in storing all keys of $storehash
                   11199:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11200:                         least <key> already existed in the db (other
                   11201:                         requested keys may also already exist)
1.967     bisitz   11202:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11203:  'con_lost' -> unable to contact request server
                   11204:  'refused' -> action was not allowed by remote machine
                   11205: 
                   11206: 
                   11207: =item *
                   11208: 
1.243     albertel 11209: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11210: reference filled in from namesp (encrypts the return communication)
                   11211: ($udom and $uname are optional)
1.191     harris41 11212: 
                   11213: =item *
                   11214: 
1.243     albertel 11215: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11216: critical subroutine
                   11217: 
1.806     raeburn  11218: =item *
                   11219: 
1.860     raeburn  11220: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11221: array reference filled in from namespace found in domain level on either
                   11222: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11223: 
                   11224: =item *
                   11225: 
1.860     raeburn  11226: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11227: domain level either on specified domain server ($uhome) or primary domain 
                   11228: server ($udom and $uhome are optional)
1.806     raeburn  11229: 
1.943     raeburn  11230: =item * 
                   11231: 
                   11232: get_domain_defaults($target_domain) : returns hash with defaults for
                   11233: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11234: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11235: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11236: Values are retrieved from cache (if current), or from domain's configuration.db
                   11237: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11238: or lonTabs/domain.tab. 
                   11239: 
                   11240: %domdefaults = &get_auth_defaults($target_domain);
                   11241: 
1.243     albertel 11242: =back
                   11243: 
                   11244: =head2 Network Status Functions
                   11245: 
                   11246: =over 4
1.191     harris41 11247: 
                   11248: =item *
                   11249: 
                   11250: dirlist($uri) : return directory list based on URI
                   11251: 
                   11252: =item *
                   11253: 
1.243     albertel 11254: spareserver() : find server with least workload from spare.tab
                   11255: 
1.986     foxr     11256: 
                   11257: =item *
                   11258: 
                   11259: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11260: if there is no corresponding loncapa host.
                   11261: 
1.243     albertel 11262: =back
                   11263: 
1.986     foxr     11264: 
1.243     albertel 11265: =head2 Apache Request
                   11266: 
                   11267: =over 4
1.191     harris41 11268: 
                   11269: =item *
                   11270: 
1.243     albertel 11271: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11272: localhost, posts hash
                   11273: 
                   11274: =back
                   11275: 
                   11276: =head2 Data to String to Data
                   11277: 
                   11278: =over 4
1.191     harris41 11279: 
                   11280: =item *
                   11281: 
1.243     albertel 11282: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11283: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11284: 
                   11285: =item *
                   11286: 
1.243     albertel 11287: hashref2str($hashref) : convert a hashref into a string complete with
                   11288: escaping and '=' and '&' separators, supports elements that are
                   11289: arrayrefs and hashrefs
1.191     harris41 11290: 
                   11291: =item *
                   11292: 
1.243     albertel 11293: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11294: with escaping and '&' separators, supports elements that are arrayrefs
                   11295: and hashrefs
1.191     harris41 11296: 
                   11297: =item *
                   11298: 
1.243     albertel 11299: str2hash($string) : convert string to hash using unescaping and
                   11300: splitting on '=' and '&', supports elements that are arrayrefs and
                   11301: hashrefs
1.191     harris41 11302: 
                   11303: =item *
                   11304: 
1.243     albertel 11305: str2array($string) : convert string to hash using unescaping and
                   11306: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11307: 
                   11308: =back
                   11309: 
                   11310: =head2 Logging Routines
                   11311: 
                   11312: =over 4
                   11313: 
                   11314: These routines allow one to make log messages in the lonnet.log and
                   11315: lonnet.perm logfiles.
1.191     harris41 11316: 
                   11317: =item *
                   11318: 
1.243     albertel 11319: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11320: 
                   11321: =item *
                   11322: 
1.243     albertel 11323: logthis() : append message to the normal lonnet.log file, it gets
                   11324: preiodically rolled over and deleted.
1.191     harris41 11325: 
                   11326: =item *
                   11327: 
1.243     albertel 11328: logperm() : append a permanent message to lonnet.perm.log, this log
                   11329: file never gets deleted by any automated portion of the system, only
                   11330: messages of critical importance should go in here.
                   11331: 
                   11332: =back
                   11333: 
                   11334: =head2 General File Helper Routines
                   11335: 
                   11336: =over 4
1.191     harris41 11337: 
                   11338: =item *
                   11339: 
1.481     raeburn  11340: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11341: (a) files in /uploaded
                   11342:   (i) If a local copy of the file exists - 
                   11343:       compares modification date of local copy with last-modified date for 
                   11344:       definitive version stored on home server for course. If local copy is 
                   11345:       stale, requests a new version from the home server and stores it. 
                   11346:       If the original has been removed from the home server, then local copy 
                   11347:       is unlinked.
                   11348:   (ii) If local copy does not exist -
                   11349:       requests the file from the home server and stores it. 
                   11350:   
                   11351:   If $caller is 'uploadrep':  
                   11352:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11353:     for request for files originally uploaded via DOCS. 
                   11354:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11355:   
                   11356:   Otherwise:
                   11357:      This indicates a call from the content generation phase of the request.
                   11358:      -  returns the entire contents of the file or -1.
                   11359:      
                   11360: (b) files in /res
                   11361:    - returns the entire contents of a file or -1; 
                   11362:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11363: 
1.712     albertel 11364: 
                   11365: =item *
                   11366: 
                   11367: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11368:                   reference
                   11369: 
                   11370: returns either a stat() list of data about the file or an empty list
                   11371: if the file doesn't exist or couldn't find out about it (connection
                   11372: problems or user unknown)
                   11373: 
1.191     harris41 11374: =item *
                   11375: 
1.243     albertel 11376: filelocation($dir,$file) : returns file system location of a file
                   11377: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11378: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11379: and a file of ../bob will become /a/bob)
1.191     harris41 11380: 
                   11381: =item *
                   11382: 
                   11383: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11384: filelocation except for hrefs
                   11385: 
                   11386: =item *
                   11387: 
                   11388: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11389: 
1.243     albertel 11390: =back
                   11391: 
1.608     albertel 11392: =head2 Usererfile file routines (/uploaded*)
                   11393: 
                   11394: =over 4
                   11395: 
                   11396: =item *
                   11397: 
                   11398: userfileupload(): main rotine for putting a file in a user or course's
                   11399:                   filespace, arguments are,
                   11400: 
1.620     albertel 11401:  formname - required - this is the name of the element in $env where the
1.608     albertel 11402:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11403:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11404:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 11405:  coursedoc - if true, store the file in the course of the active role
                   11406:              of the current user
                   11407:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11408:          if undefined, it will be placed in "unknown"
                   11409: 
                   11410:  (This routine calls clean_filename() to remove any dangerous
                   11411:  characters from the filename, and then calls finuserfileupload() to
                   11412:  complete the transaction)
                   11413: 
                   11414:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11415:  and /adm/notfound.html if unsuccessful
                   11416: 
                   11417: =item *
                   11418: 
                   11419: clean_filename(): routine for cleaing a filename up for storage in
                   11420:                  userfile space, argument is:
                   11421: 
                   11422:  filename - proposed filename
                   11423: 
                   11424: returns: the new clean filename
                   11425: 
                   11426: =item *
                   11427: 
                   11428: finishuserfileupload(): routine that creaes and sends the file to
                   11429: userspace, probably shouldn't be called directly
                   11430: 
                   11431:   docuname: username or courseid of destination for the file
                   11432:   docudom: domain of user/course of destination for the file
                   11433:   formname: same as for userfileupload()
                   11434:   fname: filename (inculding subdirectories) for the file
                   11435: 
                   11436:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11437:  and /adm/notfound.html if unsuccessful
                   11438: 
                   11439: =item *
                   11440: 
                   11441: renameuserfile(): renames an existing userfile to a new name
                   11442: 
                   11443:   Args:
                   11444:    docuname: username or courseid of destination for the file
                   11445:    docudom: domain of user/course of destination for the file
                   11446:    old: current file name (including any subdirs under userfiles)
                   11447:    new: desired file name (including any subdirs under userfiles)
                   11448: 
                   11449: =item *
                   11450: 
                   11451: mkdiruserfile(): creates a directory is a userfiles dir
                   11452: 
                   11453:   Args:
                   11454:    docuname: username or courseid of destination for the file
                   11455:    docudom: domain of user/course of destination for the file
                   11456:    dir: dir to create (including any subdirs under userfiles)
                   11457: 
                   11458: =item *
                   11459: 
                   11460: removeuserfile(): removes a file that exists in userfiles
                   11461: 
                   11462:   Args:
                   11463:    docuname: username or courseid of destination for the file
                   11464:    docudom: domain of user/course of destination for the file
                   11465:    fname: filname to delete (including any subdirs under userfiles)
                   11466: 
                   11467: =item *
                   11468: 
                   11469: removeuploadedurl(): convience function for removeuserfile()
                   11470: 
                   11471:   Args:
                   11472:    url:  a full /uploaded/... url to delete
                   11473: 
1.747     albertel 11474: =item * 
                   11475: 
                   11476: get_portfile_permissions():
                   11477:   Args:
                   11478:     domain: domain of user or course contain the portfolio files
                   11479:     user: name of user or num of course contain the portfolio files
                   11480:   Returns:
                   11481:     hashref of a dump of the proper file_permissions.db
                   11482:    
                   11483: 
                   11484: =item * 
                   11485: 
                   11486: get_access_controls():
                   11487: 
                   11488: Args:
                   11489:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11490:   group: (optional) the group you want the files associated with
                   11491:   file: (optional) the file you want access info on
                   11492: 
                   11493: Returns:
1.749     raeburn  11494:     a hash (keys are file names) of hashes containing
                   11495:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11496:         values are XML containing access control settings (see below) 
1.747     albertel 11497: 
                   11498: Internal notes:
                   11499: 
1.749     raeburn  11500:  access controls are stored in file_permissions.db as key=value pairs.
                   11501:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11502:         where scope -> public,guest,course,group,domains or users.
                   11503:               end -> UNIX time for end of access (0 -> no end date)
                   11504:               start -> UNIX time for start of access
                   11505: 
                   11506:     value -> XML description of access control
                   11507:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11508:             <start></start>
                   11509:             <end></end>
                   11510: 
                   11511:             <password></password>  for scope type = guest
                   11512: 
                   11513:             <domain></domain>     for scope type = course or group
                   11514:             <number></number>
                   11515:             <roles id="">
                   11516:              <role></role>
                   11517:              <access></access>
                   11518:              <section></section>
                   11519:              <group></group>
                   11520:             </roles>
                   11521: 
                   11522:             <dom></dom>         for scope type = domains
                   11523: 
                   11524:             <users>             for scope type = users
                   11525:              <user>
                   11526:               <uname></uname>
                   11527:               <udom></udom>
                   11528:              </user>
                   11529:             </users>
                   11530:            </scope> 
                   11531:               
                   11532:  Access data is also aggregated for each file in an additional key=value pair:
                   11533:  key -> path to file/file_name\0accesscontrol 
                   11534:  value -> reference to hash
                   11535:           hash contains key = value pairs
                   11536:           where key = uniqueID:scope_end_start
                   11537:                 value = UNIX time record was last updated
                   11538: 
                   11539:           Used to improve speed of look-ups of access controls for each file.  
                   11540:  
                   11541:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11542: 
                   11543: modify_access_controls():
                   11544: 
                   11545: Modifies access controls for a portfolio file
                   11546: Args
                   11547: 1. file name
                   11548: 2. reference to hash of required changes,
                   11549: 3. domain
                   11550: 4. username
                   11551:   where domain,username are the domain of the portfolio owner 
                   11552:   (either a user or a course) 
                   11553: 
                   11554: Returns:
                   11555: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11556: 2. result of deletions ('ok' or 'error', with error message).
                   11557: 3. reference to hash of any new or updated access controls.
                   11558: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11559:    key = integer (inbound ID)
                   11560:    value = uniqueID  
1.747     albertel 11561: 
1.608     albertel 11562: =back
                   11563: 
1.243     albertel 11564: =head2 HTTP Helper Routines
                   11565: 
                   11566: =over 4
                   11567: 
1.191     harris41 11568: =item *
                   11569: 
                   11570: escape() : unpack non-word characters into CGI-compatible hex codes
                   11571: 
                   11572: =item *
                   11573: 
                   11574: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11575: 
1.243     albertel 11576: =back
                   11577: 
                   11578: =head1 PRIVATE SUBROUTINES
                   11579: 
                   11580: =head2 Underlying communication routines (Shouldn't call)
                   11581: 
                   11582: =over 4
                   11583: 
                   11584: =item *
                   11585: 
                   11586: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11587: 
                   11588: =item *
                   11589: 
                   11590: reply() : uses subreply to send a message to remote machine, logs all failures
                   11591: 
                   11592: =item *
                   11593: 
                   11594: critical() : passes a critical message to another server; if cannot
                   11595: get through then place message in connection buffer directory and
                   11596: returns con_delayed, if incapable of saving message, returns
                   11597: con_failed
                   11598: 
                   11599: =item *
                   11600: 
                   11601: reconlonc() : tries to reconnect lonc client processes.
                   11602: 
                   11603: =back
                   11604: 
                   11605: =head2 Resource Access Logging
                   11606: 
                   11607: =over 4
                   11608: 
                   11609: =item *
                   11610: 
                   11611: flushcourselogs() : flush (save) buffer logs and access logs
                   11612: 
                   11613: =item *
                   11614: 
                   11615: courselog($what) : save message for course in hash
                   11616: 
                   11617: =item *
                   11618: 
                   11619: courseacclog($what) : save message for course using &courselog().  Perform
                   11620: special processing for specific resource types (problems, exams, quizzes, etc).
                   11621: 
1.191     harris41 11622: =item *
                   11623: 
                   11624: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11625: as a PerlChildExitHandler
1.243     albertel 11626: 
                   11627: =back
                   11628: 
                   11629: =head2 Other
                   11630: 
                   11631: =over 4
                   11632: 
                   11633: =item *
                   11634: 
                   11635: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11636: 
                   11637: =back
                   11638: 
                   11639: =cut
1.877     foxr     11640: 

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