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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1088  ! raeburn     4: # $Id: lonnet.pm,v 1.1087 2010/09/30 14:08:51 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.1079    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.1073    raeburn   199:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   200:     if (defined($lonhost)) {
                    201:         if (!defined(&hostname($lonhost))) {
                    202:             undef($lonhost);
                    203:         }
                    204:     }
                    205:     if (!defined($lonhost)) {
                    206:         if (defined(&domain($dom,'primary'))) {
                    207:             $lonhost=&domain($dom,'primary');
                    208:             if ($lonhost eq 'no_host') {
                    209:                 undef($lonhost);
                    210:             }
                    211:         }
                    212:     }
                    213:     if (defined($lonhost)) {
1.1073    raeburn   214:         my $cachetime = 12*3600;
                    215:         if (!$ignore_cache) {
                    216:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    217:             if (defined($cached)) {
                    218:                 return $loncaparev;
                    219:             }
                    220:         }
                    221:         my ($answer,$loncaparev);
                    222:         my @ids=&current_machine_ids();
                    223:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    224:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   225:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    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.1082    raeburn   233:                     $ua->timeout(4);
1.1073    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.1081    raeburn   241:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   242:                             $loncaparev = $1;
                    243:                         }
                    244:                     }
                    245:                 } else {
                    246:                     $loncaparev = $loncaparevs{$lonhost};
                    247:                 }
1.1081    raeburn   248:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   249:                 $loncaparev = $1;
                    250:             }
1.993     raeburn   251:         }
1.1073    raeburn   252:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   253:     }
                    254: }
                    255: 
1.1074    raeburn   256: sub get_server_homeID {
                    257:     my ($hostname,$ignore_cache,$caller) = @_;
                    258:     unless ($ignore_cache) {
                    259:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    260:         if (defined($cached)) {
                    261:             return $serverhomeID;
                    262:         }
                    263:     }
                    264:     my $cachetime = 12*3600;
                    265:     my $serverhomeID;
                    266:     if ($caller eq 'loncron') { 
                    267:         my @machine_ids = &machine_ids($hostname);
                    268:         foreach my $id (@machine_ids) {
                    269:             my $response = &reply('serverhomeID',$id);
                    270:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    271:                 $serverhomeID = $response;
                    272:                 last;
                    273:             }
                    274:         }
                    275:         if ($serverhomeID eq '') {
                    276:             $serverhomeID = $machine_ids[-1];
                    277:         }
                    278:     } else {
                    279:         $serverhomeID = $serverhomeIDs{$hostname};
                    280:     }
                    281:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    282: }
                    283: 
1.1       albertel  284: # -------------------------------------------------- Non-critical communication
                    285: sub subreply {
                    286:     my ($cmd,$server)=@_;
1.838     albertel  287:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      288:     #
                    289:     #  With loncnew process trimming, there's a timing hole between lonc server
                    290:     #  process exit and the master server picking up the listen on the AF_UNIX
                    291:     #  socket.  In that time interval, a lock file will exist:
                    292: 
                    293:     my $lockfile=$peerfile.".lock";
                    294:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    295: 	sleep(1);
                    296:     }
                    297:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      298:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      299:     #
1.550     foxr      300:     #   We'll give the connection a few tries before abandoning it.  If
                    301:     #   connection is not possible, we'll con_lost back to the client.
                    302:     #   
                    303:     my $client;
                    304:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    305: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    306: 				      Type    => SOCK_STREAM,
                    307: 				      Timeout => 10);
1.869     albertel  308: 	if ($client) {
1.550     foxr      309: 	    last;		# Connected!
1.850     albertel  310: 	} else {
1.853     albertel  311: 	    &create_connection(&hostname($server),$server);
1.550     foxr      312: 	}
1.850     albertel  313:         sleep(1);		# Try again later if failed connection.
1.550     foxr      314:     }
                    315:     my $answer;
                    316:     if ($client) {
1.704     albertel  317: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      318: 	$answer=<$client>;
                    319: 	if (!$answer) { $answer="con_lost"; }
                    320: 	chomp($answer);
                    321:     } else {
                    322: 	$answer = 'con_lost';	# Failed connection.
                    323:     }
1.1       albertel  324:     return $answer;
                    325: }
                    326: 
                    327: sub reply {
                    328:     my ($cmd,$server)=@_;
1.838     albertel  329:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  330:     my $answer=subreply($cmd,$server);
1.65      www       331:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  332:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       333:                 " $cmd to $server returned $answer</font>");
                    334:     }
1.1       albertel  335:     return $answer;
                    336: }
                    337: 
                    338: # ----------------------------------------------------------- Send USR1 to lonc
                    339: 
                    340: sub reconlonc {
1.891     albertel  341:     my ($lonid) = @_;
                    342:     my $hostname = &hostname($lonid);
                    343:     if ($lonid) {
                    344: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    345: 	if ($hostname && -e $peerfile) {
                    346: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    347: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    348: 					     Type    => SOCK_STREAM,
                    349: 					     Timeout => 10);
                    350: 	    if ($client) {
                    351: 		print $client ("reset_retries\n");
                    352: 		my $answer=<$client>;
                    353: 		#reset just this one.
                    354: 	    }
                    355: 	}
                    356: 	return;
                    357:     }
                    358: 
1.836     www       359:     &logthis("Trying to reconnect lonc");
1.1       albertel  360:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  361:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  362: 	my $loncpid=<$fh>;
                    363:         chomp($loncpid);
                    364:         if (kill 0 => $loncpid) {
                    365: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    366:             kill USR1 => $loncpid;
                    367:             sleep 1;
1.836     www       368:          } else {
1.12      www       369: 	    &logthis(
1.672     albertel  370:                "<font color=\"blue\">WARNING:".
1.12      www       371:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  372:         }
                    373:     } else {
1.836     www       374: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  375:     }
                    376: }
                    377: 
                    378: # ------------------------------------------------------ Critical communication
1.12      www       379: 
1.1       albertel  380: sub critical {
                    381:     my ($cmd,$server)=@_;
1.838     albertel  382:     unless (&hostname($server)) {
1.672     albertel  383:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       384:                " Critical message to unknown server ($server)</font>");
                    385:         return 'no_such_host';
                    386:     }
1.1       albertel  387:     my $answer=reply($cmd,$server);
                    388:     if ($answer eq 'con_lost') {
                    389: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  390: 	my $answer=reply($cmd,$server);
1.1       albertel  391:         if ($answer eq 'con_lost') {
                    392:             my $now=time;
                    393:             my $middlename=$cmd;
1.5       www       394:             $middlename=substr($middlename,0,16);
1.1       albertel  395:             $middlename=~s/\W//g;
                    396:             my $dfilename=
1.305     www       397:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    398:             $dumpcount++;
1.1       albertel  399:             {
1.448     albertel  400: 		my $dfh;
                    401: 		if (open($dfh,">$dfilename")) {
                    402: 		    print $dfh "$cmd\n"; 
                    403: 		    close($dfh);
                    404: 		}
1.1       albertel  405:             }
                    406:             sleep 2;
                    407:             my $wcmd='';
                    408:             {
1.448     albertel  409: 		my $dfh;
                    410: 		if (open($dfh,"<$dfilename")) {
                    411: 		    $wcmd=<$dfh>; 
                    412: 		    close($dfh);
                    413: 		}
1.1       albertel  414:             }
                    415:             chomp($wcmd);
1.7       www       416:             if ($wcmd eq $cmd) {
1.672     albertel  417: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       418:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  419:                 &logperm("D:$server:$cmd");
                    420: 	        return 'con_delayed';
                    421:             } else {
1.672     albertel  422:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       423:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  424:                 &logperm("F:$server:$cmd");
                    425:                 return 'con_failed';
                    426:             }
                    427:         }
                    428:     }
                    429:     return $answer;
1.405     albertel  430: }
                    431: 
1.755     albertel  432: # ------------------------------------------- check if return value is an error
                    433: 
                    434: sub error {
                    435:     my ($result) = @_;
1.756     albertel  436:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  437: 	if ($2 == 2) { return undef; }
                    438: 	return $1;
                    439:     }
                    440:     return undef;
                    441: }
                    442: 
1.783     albertel  443: sub convert_and_load_session_env {
                    444:     my ($lonidsdir,$handle)=@_;
                    445:     my @profile;
                    446:     {
1.917     albertel  447: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    448: 	if (!$opened) {
1.915     albertel  449: 	    return 0;
                    450: 	}
1.783     albertel  451: 	flock($idf,LOCK_SH);
                    452: 	@profile=<$idf>;
                    453: 	close($idf);
                    454:     }
                    455:     my %temp_env;
                    456:     foreach my $line (@profile) {
1.786     albertel  457: 	if ($line !~ m/=/) {
                    458: 	    return 0;
                    459: 	}
1.783     albertel  460: 	chomp($line);
                    461: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    462: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    463:     }
                    464:     unlink("$lonidsdir/$handle.id");
                    465:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    466: 	    0640)) {
                    467: 	%disk_env = %temp_env;
                    468: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    469: 	untie(%disk_env);
                    470:     }
1.786     albertel  471:     return 1;
1.783     albertel  472: }
                    473: 
1.374     www       474: # ------------------------------------------- Transfer profile into environment
1.780     albertel  475: my $env_loaded;
                    476: sub transfer_profile_to_env {
1.788     albertel  477:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    478:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       479: 
1.720     albertel  480:     if (!defined($lonidsdir)) {
                    481: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    482:     }
                    483:     if (!defined($handle)) {
                    484:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    485:     }
                    486: 
1.786     albertel  487:     my $convert;
                    488:     {
1.917     albertel  489:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    490: 	if (!$opened) {
1.915     albertel  491: 	    return;
                    492: 	}
1.786     albertel  493: 	flock($idf,LOCK_SH);
                    494: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    495: 		&GDBM_READER(),0640)) {
                    496: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    497: 	    untie(%disk_env);
                    498: 	} else {
                    499: 	    $convert = 1;
                    500: 	}
                    501:     }
                    502:     if ($convert) {
                    503: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    504: 	    &logthis("Failed to load session, or convert session.");
                    505: 	}
1.374     www       506:     }
1.783     albertel  507: 
1.786     albertel  508:     my %remove;
1.783     albertel  509:     while ( my $envname = each(%env) ) {
1.433     matthew   510:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    511:             if ($time < time-300) {
1.783     albertel  512:                 $remove{$key}++;
1.433     matthew   513:             }
                    514:         }
                    515:     }
1.783     albertel  516: 
1.619     albertel  517:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  518:     $env_loaded=1;
1.783     albertel  519:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   520:         &delenv($expired_key);
1.374     www       521:     }
1.1       albertel  522: }
                    523: 
1.916     albertel  524: # ---------------------------------------------------- Check for valid session 
                    525: sub check_for_valid_session {
                    526:     my ($r) = @_;
                    527:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    528:     my $lonid=$cookies{'lonID'};
                    529:     return undef if (!$lonid);
                    530: 
                    531:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    532:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    533:     return undef if (!-e "$lonidsdir/$handle.id");
                    534: 
1.917     albertel  535:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    536:     return undef if (!$opened);
1.916     albertel  537: 
                    538:     flock($idf,LOCK_SH);
                    539:     my %disk_env;
                    540:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    541: 	    &GDBM_READER(),0640)) {
                    542: 	return undef;	
                    543:     }
                    544: 
                    545:     if (!defined($disk_env{'user.name'})
                    546: 	|| !defined($disk_env{'user.domain'})) {
                    547: 	return undef;
                    548:     }
                    549:     return $handle;
                    550: }
                    551: 
1.830     albertel  552: sub timed_flock {
                    553:     my ($file,$lock_type) = @_;
                    554:     my $failed=0;
                    555:     eval {
                    556: 	local $SIG{__DIE__}='DEFAULT';
                    557: 	local $SIG{ALRM}=sub {
                    558: 	    $failed=1;
                    559: 	    die("failed lock");
                    560: 	};
                    561: 	alarm(13);
                    562: 	flock($file,$lock_type);
                    563: 	alarm(0);
                    564:     };
                    565:     if ($failed) {
                    566: 	return undef;
                    567:     } else {
                    568: 	return 1;
                    569:     }
                    570: }
                    571: 
1.5       www       572: # ---------------------------------------------------------- Append Environment
                    573: 
                    574: sub appenv {
1.949     raeburn   575:     my ($newenv,$roles) = @_;
                    576:     if (ref($newenv) eq 'HASH') {
                    577:         foreach my $key (keys(%{$newenv})) {
                    578:             my $refused = 0;
                    579: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    580:                 $refused = 1;
                    581:                 if (ref($roles) eq 'ARRAY') {
                    582:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    583:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    584:                         $refused = 0;
                    585:                     }
                    586:                 }
                    587:             }
                    588:             if ($refused) {
                    589:                 &logthis("<font color=\"blue\">WARNING: ".
                    590:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    591:                          .'</font>');
                    592: 	        delete($newenv->{$key});
                    593:             } else {
                    594:                 $env{$key}=$newenv->{$key};
                    595:             }
                    596:         }
                    597:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    598:         if ($opened
                    599: 	    && &timed_flock($env_file,LOCK_EX)
                    600: 	    &&
                    601: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    602: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    603: 	    while (my ($key,$value) = each(%{$newenv})) {
                    604: 	        $disk_env{$key} = $value;
                    605: 	    }
                    606: 	    untie(%disk_env);
1.35      www       607:         }
1.191     harris41  608:     }
1.56      www       609:     return 'ok';
                    610: }
                    611: # ----------------------------------------------------- Delete from Environment
                    612: 
                    613: sub delenv {
1.987     raeburn   614:     my ($delthis,$regexp) = @_;
1.56      www       615:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  616:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       617:                 "Attempt to delete from environment ".$delthis);
                    618:         return 'error';
                    619:     }
1.917     albertel  620:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    621:     if ($opened
1.915     albertel  622: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  623: 	&&
                    624: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    625: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  626: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   627: 	    if ($regexp) {
                    628:                 if ($key=~/^$delthis/) {
                    629:                     delete($env{$key});
                    630:                     delete($disk_env{$key});
                    631:                 } 
                    632:             } else {
                    633:                 if ($key=~/^\Q$delthis\E/) {
                    634: 		    delete($env{$key});
                    635: 		    delete($disk_env{$key});
                    636: 	        }
                    637:             }
1.448     albertel  638: 	}
1.783     albertel  639: 	untie(%disk_env);
1.5       www       640:     }
                    641:     return 'ok';
1.369     albertel  642: }
                    643: 
1.790     albertel  644: sub get_env_multiple {
                    645:     my ($name) = @_;
                    646:     my @values;
                    647:     if (defined($env{$name})) {
                    648:         # exists is it an array
                    649:         if (ref($env{$name})) {
                    650:             @values=@{ $env{$name} };
                    651:         } else {
                    652:             $values[0]=$env{$name};
                    653:         }
                    654:     }
                    655:     return(@values);
                    656: }
                    657: 
1.958     www       658: # ------------------------------------------------------------------- Locking
                    659: 
                    660: sub set_lock {
                    661:     my ($text)=@_;
                    662:     $locknum++;
                    663:     my $id=$$.'-'.$locknum;
                    664:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    665:              'session.lock.'.$id => $text});
                    666:     return $id;
                    667: }
                    668: 
                    669: sub get_locks {
                    670:     my $num=0;
                    671:     my %texts=();
                    672:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    673:        if ($lock=~/\w/) {
                    674:           $num++;
                    675:           $texts{$lock}=$env{'session.lock.'.$lock};
                    676:        }
                    677:    }
                    678:    return ($num,%texts);
                    679: }
                    680: 
                    681: sub remove_lock {
                    682:     my ($id)=@_;
                    683:     my $newlocks='';
                    684:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    685:        if (($lock=~/\w/) && ($lock ne $id)) {
                    686:           $newlocks.=','.$lock;
                    687:        }
                    688:     }
                    689:     &appenv({'session.locks' => $newlocks});
                    690:     &delenv('session.lock.'.$id);
                    691: }
                    692: 
                    693: sub remove_all_locks {
                    694:     my $activelocks=$env{'session.locks'};
                    695:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    696:        if ($lock=~/\w/) {
                    697:           &remove_lock($lock);
                    698:        }
                    699:     }
                    700: }
                    701: 
                    702: 
1.369     albertel  703: # ------------------------------------------ Find out current server userload
                    704: sub userload {
                    705:     my $numusers=0;
                    706:     {
                    707: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    708: 	my $filename;
                    709: 	my $curtime=time;
                    710: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  711: 	    next if ($filename eq '.' || $filename eq '..');
                    712: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  713: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  714: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  715: 	}
                    716: 	closedir(LONIDS);
                    717:     }
                    718:     my $userloadpercent=0;
                    719:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    720:     if ($maxuserload) {
1.371     albertel  721: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  722:     }
1.372     albertel  723:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  724:     return $userloadpercent;
1.283     www       725: }
                    726: 
1.1       albertel  727: # ------------------------------ Find server with least workload from spare.tab
1.11      www       728: 
1.1       albertel  729: sub spareserver {
1.1083    raeburn   730:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  731:     my $spare_server;
1.370     albertel  732:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  733:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    734:                                                      :  $userloadpercent;
1.1083    raeburn   735:     my ($uint_dom,$remotesessions);
                    736:     if (($udom ne '') && (&domain($udom) ne '')) {
                    737:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    738:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    739:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    740:         $remotesessions = $udomdefaults{'remotesessions'};
                    741:     }
1.784     albertel  742:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083    raeburn   743:         if ($uint_dom) {
                    744:              next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    745:                                           $try_server));
                    746:         }
1.784     albertel  747: 	($spare_server, $lowest_load) =
                    748: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    749:     }
                    750: 
                    751:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    752: 
                    753:     if (!$found_server) {
                    754: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1083    raeburn   755:             if ($uint_dom) {
                    756:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    757:                                              $try_server));
                    758:             }
1.784     albertel  759: 	    ($spare_server, $lowest_load) =
                    760: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    761: 	}
                    762:     }
                    763: 
                    764:     if (!$want_server_name) {
1.968     raeburn   765:         my $protocol = 'http';
                    766:         if ($protocol{$spare_server} eq 'https') {
                    767:             $protocol = $protocol{$spare_server};
                    768:         }
1.1001    raeburn   769:         if (defined($spare_server)) {
                    770:             my $hostname = &hostname($spare_server);
1.1083    raeburn   771:             if (defined($hostname)) {
1.1001    raeburn   772: 	        $spare_server = $protocol.'://'.$hostname;
                    773:             }
                    774:         }
1.784     albertel  775:     }
                    776:     return $spare_server;
                    777: }
                    778: 
                    779: sub compare_server_load {
                    780:     my ($try_server, $spare_server, $lowest_load) = @_;
                    781: 
                    782:     my $loadans     = &reply('load',    $try_server);
                    783:     my $userloadans = &reply('userload',$try_server);
                    784: 
                    785:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072    www       786: 	return; #didn't get a number from the server
1.784     albertel  787:     }
                    788: 
                    789:     my $load;
                    790:     if ($loadans =~ /\d/) {
                    791: 	if ($userloadans =~ /\d/) {
                    792: 	    #both are numbers, pick the bigger one
                    793: 	    $load = ($loadans > $userloadans) ? $loadans 
                    794: 		                              : $userloadans;
1.411     albertel  795: 	} else {
1.784     albertel  796: 	    $load = $loadans;
1.411     albertel  797: 	}
1.784     albertel  798:     } else {
                    799: 	$load = $userloadans;
                    800:     }
                    801: 
                    802:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    803: 	$spare_server = $try_server;
                    804: 	$lowest_load  = $load;
1.370     albertel  805:     }
1.784     albertel  806:     return ($spare_server,$lowest_load);
1.202     matthew   807: }
1.914     albertel  808: 
                    809: # --------------------------- ask offload servers if user already has a session
                    810: sub find_existing_session {
                    811:     my ($udom,$uname) = @_;
                    812:     foreach my $try_server (@{ $spareid{'primary'} },
                    813: 			    @{ $spareid{'default'} }) {
                    814: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    815:     }
                    816:     return;
                    817: }
                    818: 
                    819: # -------------------------------- ask if server already has a session for user
                    820: sub has_user_session {
                    821:     my ($lonid,$udom,$uname) = @_;
                    822:     my $result = &reply(join(':','userhassession',
                    823: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    824:     return 1 if ($result eq 'ok');
                    825: 
                    826:     return 0;
                    827: }
                    828: 
1.1076    raeburn   829: # --------- determine least loaded server in a user's domain which allows login
                    830: 
                    831: sub choose_server {
                    832:     my ($udom) = @_;
                    833:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   834:     my %servers = &get_servers($udom);
1.1076    raeburn   835:     my $lowest_load = 30000;
                    836:     my ($login_host,$hostname);
                    837:     foreach my $lonhost (keys(%servers)) {
                    838:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    839:         if ($loginvia eq '') {
                    840:             ($login_host, $lowest_load) =
                    841:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    842:         }
                    843:     }
                    844:     if ($login_host ne '') {
                    845:         $hostname = $servers{$login_host};
                    846:     }
                    847:     return ($login_host,$hostname);
                    848: }
                    849: 
1.202     matthew   850: # --------------------------------------------- Try to change a user's password
                    851: 
                    852: sub changepass {
1.799     raeburn   853:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   854:     $currentpass = &escape($currentpass);
                    855:     $newpass     = &escape($newpass);
1.1030    raeburn   856:     my $lonhost = $perlvar{'lonHostID'};
                    857:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   858: 		       $server);
                    859:     if (! $answer) {
                    860: 	&logthis("No reply on password change request to $server ".
                    861: 		 "by $uname in domain $udom.");
                    862:     } elsif ($answer =~ "^ok") {
                    863:         &logthis("$uname in $udom successfully changed their password ".
                    864: 		 "on $server.");
                    865:     } elsif ($answer =~ "^pwchange_failure") {
                    866: 	&logthis("$uname in $udom was unable to change their password ".
                    867: 		 "on $server.  The action was blocked by either lcpasswd ".
                    868: 		 "or pwchange");
                    869:     } elsif ($answer =~ "^non_authorized") {
                    870:         &logthis("$uname in $udom did not get their password correct when ".
                    871: 		 "attempting to change it on $server.");
                    872:     } elsif ($answer =~ "^auth_mode_error") {
                    873:         &logthis("$uname in $udom attempted to change their password despite ".
                    874: 		 "not being locally or internally authenticated on $server.");
                    875:     } elsif ($answer =~ "^unknown_user") {
                    876:         &logthis("$uname in $udom attempted to change their password ".
                    877: 		 "on $server but were unable to because $server is not ".
                    878: 		 "their home server.");
                    879:     } elsif ($answer =~ "^refused") {
                    880: 	&logthis("$server refused to change $uname in $udom password because ".
                    881: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   882:     } elsif ($answer =~ "invalid_client") {
                    883:         &logthis("$server refused to change $uname in $udom password because ".
                    884:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   885:     }
                    886:     return $answer;
1.1       albertel  887: }
                    888: 
1.169     harris41  889: # ----------------------- Try to determine user's current authentication scheme
                    890: 
                    891: sub queryauthenticate {
                    892:     my ($uname,$udom)=@_;
1.456     albertel  893:     my $uhome=&homeserver($uname,$udom);
                    894:     if (!$uhome) {
                    895: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    896: 	return 'no_host';
                    897:     }
                    898:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    899:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    900: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  901:     }
1.456     albertel  902:     return $answer;
1.169     harris41  903: }
                    904: 
1.1       albertel  905: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       906: 
1.1       albertel  907: sub authenticate {
1.1073    raeburn   908:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  909:     $upass=&escape($upass);
                    910:     $uname= &LONCAPA::clean_username($uname);
1.836     www       911:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   912:     my $newhome;
1.836     www       913:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    914: # Maybe the machine was offline and only re-appeared again recently?
                    915:         &reconlonc();
                    916: # One more
1.952     raeburn   917: 	$uhome=&homeserver($uname,$udom,1);
                    918:         if (($uhome eq 'no_host') && $checkdefauth) {
                    919:             if (defined(&domain($udom,'primary'))) {
                    920:                 $newhome=&domain($udom,'primary');
                    921:             }
                    922:             if ($newhome ne '') {
                    923:                 $uhome = $newhome;
                    924:             }
                    925:         }
1.836     www       926: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    927: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   928: 	    return 'no_host';
                    929:         }
1.1       albertel  930:     }
1.1073    raeburn   931:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  932:     if ($answer eq 'authorized') {
1.952     raeburn   933:         if ($newhome) {
                    934:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    935:             return 'no_account_on_host'; 
                    936:         } else {
                    937:             &logthis("User $uname at $udom authorized by $uhome");
                    938:             return $uhome;
                    939:         }
1.471     albertel  940:     }
                    941:     if ($answer eq 'non_authorized') {
                    942: 	&logthis("User $uname at $udom rejected by $uhome");
                    943: 	return 'no_host'; 
1.9       www       944:     }
1.471     albertel  945:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  946:     return 'no_host';
                    947: }
                    948: 
1.1073    raeburn   949: sub can_host_session {
1.1074    raeburn   950:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn   951:     my $canhost = 1;
1.1074    raeburn   952:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn   953:     if (ref($remotesessions) eq 'HASH') {
                    954:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn   955:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn   956:                 $canhost = 0;
                    957:             } else {
                    958:                 $canhost = 1;
                    959:             }
                    960:         }
                    961:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn   962:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn   963:                 $canhost = 1;
                    964:             } else {
                    965:                 $canhost = 0;
                    966:             }
                    967:         }
                    968:         if ($canhost) {
                    969:             if ($remotesessions->{'version'} ne '') {
                    970:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                    971:                 if ($reqmajor ne '' && $reqminor ne '') {
                    972:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                    973:                         my $major = $1;
                    974:                         my $minor = $2;
                    975:                         if (($major < $reqmajor ) ||
                    976:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                    977:                             $canhost = 0;
                    978:                         }
                    979:                     } else {
                    980:                         $canhost = 0;
                    981:                     }
                    982:                 }
                    983:             }
                    984:         }
                    985:     }
                    986:     if ($canhost) {
                    987:         if (ref($hostedsessions) eq 'HASH') {
                    988:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                    989:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                    990:                     $canhost = 0;
                    991:                 } else {
                    992:                     $canhost = 1;
                    993:                 }
                    994:             }
                    995:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                    996:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                    997:                     $canhost = 1;
                    998:                 } else {
                    999:                     $canhost = 0;
                   1000:                 }
                   1001:             }
                   1002:         }
                   1003:     }
                   1004:     return $canhost;
                   1005: }
                   1006: 
1.1083    raeburn  1007: sub spare_can_host {
                   1008:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1009:     my $canhost=1;
                   1010:     my @intdoms;
                   1011:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1012:     if (ref($internet_names) eq 'ARRAY') {
                   1013:         @intdoms = @{$internet_names};
                   1014:     }
                   1015:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1016:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1017:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1018:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1019:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1020:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1021:                                      $remotesessions,
                   1022:                                      $defdomdefaults{'hostedsessions'});
                   1023:     }
                   1024:     return $canhost;
                   1025: }
                   1026: 
1.1       albertel 1027: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1028: 
1.599     albertel 1029: my %homecache;
1.1       albertel 1030: sub homeserver {
1.230     stredwic 1031:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1032:     my $index="$uname:$udom";
1.426     albertel 1033: 
1.599     albertel 1034:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1035: 
                   1036:     my %servers = &get_servers($udom,'library');
                   1037:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1038:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1039: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1040: 
                   1041: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1042: 	if ($answer eq 'found') {
                   1043: 	    delete($badServerCache{$tryserver}); 
                   1044: 	    return $homecache{$index}=$tryserver;
                   1045: 	} elsif ($answer eq 'no_host') {
                   1046: 	    $badServerCache{$tryserver}=1;
                   1047: 	}
1.1       albertel 1048:     }    
                   1049:     return 'no_host';
1.70      www      1050: }
                   1051: 
                   1052: # ------------------------------------- Find the usernames behind a list of IDs
                   1053: 
                   1054: sub idget {
                   1055:     my ($udom,@ids)=@_;
                   1056:     my %returnhash=();
                   1057:     
1.841     albertel 1058:     my %servers = &get_servers($udom,'library');
                   1059:     foreach my $tryserver (keys(%servers)) {
                   1060: 	my $idlist=join('&',@ids);
                   1061: 	$idlist=~tr/A-Z/a-z/; 
                   1062: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1063: 	my @answer=();
                   1064: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1065: 	    @answer=split(/\&/,$reply);
                   1066: 	}                    ;
                   1067: 	my $i;
                   1068: 	for ($i=0;$i<=$#ids;$i++) {
                   1069: 	    if ($answer[$i]) {
                   1070: 		$returnhash{$ids[$i]}=$answer[$i];
                   1071: 	    } 
                   1072: 	}
                   1073:     } 
1.70      www      1074:     return %returnhash;
                   1075: }
                   1076: 
                   1077: # ------------------------------------- Find the IDs behind a list of usernames
                   1078: 
                   1079: sub idrget {
                   1080:     my ($udom,@unames)=@_;
                   1081:     my %returnhash=();
1.800     albertel 1082:     foreach my $uname (@unames) {
                   1083:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1084:     }
1.70      www      1085:     return %returnhash;
                   1086: }
                   1087: 
                   1088: # ------------------------------- Store away a list of names and associated IDs
                   1089: 
                   1090: sub idput {
                   1091:     my ($udom,%ids)=@_;
                   1092:     my %servers=();
1.800     albertel 1093:     foreach my $uname (keys(%ids)) {
                   1094: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1095:         my $uhom=&homeserver($uname,$udom);
1.70      www      1096:         if ($uhom ne 'no_host') {
1.800     albertel 1097:             my $id=&escape($ids{$uname});
1.70      www      1098:             $id=~tr/A-Z/a-z/;
1.800     albertel 1099:             my $esc_unam=&escape($uname);
1.70      www      1100: 	    if ($servers{$uhom}) {
1.800     albertel 1101: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1102:             } else {
1.800     albertel 1103:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1104:             }
                   1105:         }
1.191     harris41 1106:     }
1.800     albertel 1107:     foreach my $server (keys(%servers)) {
                   1108:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1109:     }
1.344     www      1110: }
                   1111: 
1.1023    raeburn  1112: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1113: sub dump_dom {
1.1023    raeburn  1114:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1115:     if (!$udom) {
                   1116:         $udom=$env{'user.domain'};
                   1117:     }
                   1118:     my %returnhash;
1.1023    raeburn  1119:     if ($udom) {
                   1120:         my $uname = &get_domainconfiguser($udom);
                   1121:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1122:     }
                   1123:     return %returnhash;
                   1124: }
                   1125: 
1.1023    raeburn  1126: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1127: 
                   1128: sub get_dom {
1.860     raeburn  1129:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1130:     my $items='';
                   1131:     foreach my $item (@$storearr) {
                   1132:         $items.=&escape($item).'&';
                   1133:     }
                   1134:     $items=~s/\&$//;
1.860     raeburn  1135:     if (!$udom) {
                   1136:         $udom=$env{'user.domain'};
                   1137:         if (defined(&domain($udom,'primary'))) {
                   1138:             $uhome=&domain($udom,'primary');
                   1139:         } else {
1.874     albertel 1140:             undef($uhome);
1.860     raeburn  1141:         }
                   1142:     } else {
                   1143:         if (!$uhome) {
                   1144:             if (defined(&domain($udom,'primary'))) {
                   1145:                 $uhome=&domain($udom,'primary');
                   1146:             }
                   1147:         }
                   1148:     }
                   1149:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1150:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1151:         my %returnhash;
1.875     albertel 1152:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1153:             return %returnhash;
                   1154:         }
1.806     raeburn  1155:         my @pairs=split(/\&/,$rep);
                   1156:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1157:             return @pairs;
                   1158:         }
                   1159:         my $i=0;
                   1160:         foreach my $item (@$storearr) {
                   1161:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1162:             $i++;
                   1163:         }
                   1164:         return %returnhash;
                   1165:     } else {
1.880     banghart 1166:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1167:     }
                   1168: }
                   1169: 
                   1170: # -------------------------------------------- put items in domain db files 
                   1171: 
                   1172: sub put_dom {
1.860     raeburn  1173:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1174:     if (!$udom) {
                   1175:         $udom=$env{'user.domain'};
                   1176:         if (defined(&domain($udom,'primary'))) {
                   1177:             $uhome=&domain($udom,'primary');
                   1178:         } else {
1.874     albertel 1179:             undef($uhome);
1.860     raeburn  1180:         }
                   1181:     } else {
                   1182:         if (!$uhome) {
                   1183:             if (defined(&domain($udom,'primary'))) {
                   1184:                 $uhome=&domain($udom,'primary');
                   1185:             }
                   1186:         }
                   1187:     } 
                   1188:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1189:         my $items='';
                   1190:         foreach my $item (keys(%$storehash)) {
                   1191:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1192:         }
                   1193:         $items=~s/\&$//;
                   1194:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1195:     } else {
1.860     raeburn  1196:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1197:     }
                   1198: }
                   1199: 
1.1023    raeburn  1200: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1201: sub newput_dom {
1.1023    raeburn  1202:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1203:     my $result;
                   1204:     if (!$udom) {
                   1205:         $udom=$env{'user.domain'};
                   1206:     }
1.1023    raeburn  1207:     if ($udom) {
                   1208:         my $uname = &get_domainconfiguser($udom);
                   1209:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1210:     }
                   1211:     return $result;
                   1212: }
                   1213: 
1.1023    raeburn  1214: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1215: sub del_dom {
1.1023    raeburn  1216:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1217:     if (ref($storearr) eq 'ARRAY') {
                   1218:         if (!$udom) {
                   1219:             $udom=$env{'user.domain'};
                   1220:         }
1.1023    raeburn  1221:         if ($udom) {
                   1222:             my $uname = &get_domainconfiguser($udom); 
                   1223:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1224:         }
                   1225:     }
                   1226: }
                   1227: 
1.1023    raeburn  1228: # ----------------------------------construct domainconfig user for a domain 
                   1229: sub get_domainconfiguser {
                   1230:     my ($udom) = @_;
                   1231:     return $udom.'-domainconfig';
                   1232: }
                   1233: 
1.837     raeburn  1234: sub retrieve_inst_usertypes {
                   1235:     my ($udom) = @_;
                   1236:     my (%returnhash,@order);
1.989     raeburn  1237:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1238:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1239:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1240:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1241:         @order = @{$domdefs{'inststatusorder'}};
                   1242:     } else {
                   1243:         if (defined(&domain($udom,'primary'))) {
                   1244:             my $uhome=&domain($udom,'primary');
                   1245:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1246:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1247:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1248:                 return (\%returnhash,\@order);
                   1249:             }
                   1250:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1251:             my @pairs=split(/\&/,$hashitems);
                   1252:             foreach my $item (@pairs) {
                   1253:                 my ($key,$value)=split(/=/,$item,2);
                   1254:                 $key = &unescape($key);
                   1255:                 next if ($key =~ /^error: 2 /);
                   1256:                 $returnhash{$key}=&thaw_unescape($value);
                   1257:             }
                   1258:             my @esc_order = split(/\&/,$orderitems);
                   1259:             foreach my $item (@esc_order) {
                   1260:                 push(@order,&unescape($item));
                   1261:             }
                   1262:         } else {
                   1263:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1264:         }
                   1265:     }
                   1266:     return (\%returnhash,\@order);
                   1267: }
                   1268: 
1.868     raeburn  1269: sub is_domainimage {
                   1270:     my ($url) = @_;
                   1271:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1272:         if (&domain($1) ne '') {
                   1273:             return '1';
                   1274:         }
                   1275:     }
                   1276:     return;
                   1277: }
                   1278: 
1.899     raeburn  1279: sub inst_directory_query {
                   1280:     my ($srch) = @_;
                   1281:     my $udom = $srch->{'srchdomain'};
                   1282:     my %results;
                   1283:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1284:     my $outcome;
1.899     raeburn  1285:     if ($homeserver ne '') {
1.904     albertel 1286: 	my $queryid=&reply("querysend:instdirsearch:".
                   1287: 			   &escape($srch->{'srchby'}).':'.
                   1288: 			   &escape($srch->{'srchterm'}).':'.
                   1289: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1290: 	my $host=&hostname($homeserver);
                   1291: 	if ($queryid !~/^\Q$host\E\_/) {
                   1292: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1293: 	    return;
                   1294: 	}
                   1295: 	my $response = &get_query_reply($queryid);
                   1296: 	my $maxtries = 5;
                   1297: 	my $tries = 1;
                   1298: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1299: 	    $response = &get_query_reply($queryid);
                   1300: 	    $tries ++;
                   1301: 	}
                   1302: 
                   1303:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1304:             if ($response eq 'unavailable') {
                   1305:                 $outcome = $response;
                   1306:             } else {
                   1307:                 $outcome = 'ok';
                   1308:                 my @matches = split(/\n/,$response);
                   1309:                 foreach my $match (@matches) {
                   1310:                     my ($key,$value) = split(/=/,$match);
                   1311:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1312:                 }
1.899     raeburn  1313:             }
                   1314:         }
                   1315:     }
1.909     raeburn  1316:     return ($outcome,%results);
1.899     raeburn  1317: }
                   1318: 
                   1319: sub usersearch {
                   1320:     my ($srch) = @_;
                   1321:     my $dom = $srch->{'srchdomain'};
                   1322:     my %results;
                   1323:     my %libserv = &all_library();
                   1324:     my $query = 'usersearch';
                   1325:     foreach my $tryserver (keys(%libserv)) {
                   1326:         if (&host_domain($tryserver) eq $dom) {
                   1327:             my $host=&hostname($tryserver);
                   1328:             my $queryid=
1.911     raeburn  1329:                 &reply("querysend:".&escape($query).':'.
                   1330:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1331:                        &escape($srch->{'srchtype'}).':'.
                   1332:                        &escape($srch->{'srchterm'}),$tryserver);
                   1333:             if ($queryid !~/^\Q$host\E\_/) {
                   1334:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1335:                 next;
1.899     raeburn  1336:             }
                   1337:             my $reply = &get_query_reply($queryid);
                   1338:             my $maxtries = 1;
                   1339:             my $tries = 1;
                   1340:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1341:                 $reply = &get_query_reply($queryid);
                   1342:                 $tries ++;
                   1343:             }
                   1344:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1345:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1346:             } else {
1.911     raeburn  1347:                 my @matches;
                   1348:                 if ($reply =~ /\n/) {
                   1349:                     @matches = split(/\n/,$reply);
                   1350:                 } else {
                   1351:                     @matches = split(/\&/,$reply);
                   1352:                 }
1.899     raeburn  1353:                 foreach my $match (@matches) {
                   1354:                     my ($uname,$udom,%userhash);
1.911     raeburn  1355:                     foreach my $entry (split(/:/,$match)) {
                   1356:                         my ($key,$value) =
                   1357:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1358:                         $userhash{$key} = $value;
                   1359:                         if ($key eq 'username') {
                   1360:                             $uname = $value;
                   1361:                         } elsif ($key eq 'domain') {
                   1362:                             $udom = $value;
1.911     raeburn  1363:                         }
1.899     raeburn  1364:                     }
                   1365:                     $results{$uname.':'.$udom} = \%userhash;
                   1366:                 }
                   1367:             }
                   1368:         }
                   1369:     }
                   1370:     return %results;
                   1371: }
                   1372: 
1.912     raeburn  1373: sub get_instuser {
                   1374:     my ($udom,$uname,$id) = @_;
                   1375:     my $homeserver = &domain($udom,'primary');
                   1376:     my ($outcome,%results);
                   1377:     if ($homeserver ne '') {
                   1378:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1379:                            &escape($id).':'.&escape($udom),$homeserver);
                   1380:         my $host=&hostname($homeserver);
                   1381:         if ($queryid !~/^\Q$host\E\_/) {
                   1382:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1383:             return;
                   1384:         }
                   1385:         my $response = &get_query_reply($queryid);
                   1386:         my $maxtries = 5;
                   1387:         my $tries = 1;
                   1388:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1389:             $response = &get_query_reply($queryid);
                   1390:             $tries ++;
                   1391:         }
                   1392:         if (!&error($response) && $response ne 'refused') {
                   1393:             if ($response eq 'unavailable') {
                   1394:                 $outcome = $response;
                   1395:             } else {
                   1396:                 $outcome = 'ok';
                   1397:                 my @matches = split(/\n/,$response);
                   1398:                 foreach my $match (@matches) {
                   1399:                     my ($key,$value) = split(/=/,$match);
                   1400:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1401:                 }
                   1402:             }
                   1403:         }
                   1404:     }
                   1405:     my %userinfo;
                   1406:     if (ref($results{$uname}) eq 'HASH') {
                   1407:         %userinfo = %{$results{$uname}};
                   1408:     } 
                   1409:     return ($outcome,%userinfo);
                   1410: }
                   1411: 
                   1412: sub inst_rulecheck {
1.923     raeburn  1413:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1414:     my %returnhash;
                   1415:     if ($udom ne '') {
                   1416:         if (ref($rules) eq 'ARRAY') {
                   1417:             @{$rules} = map {&escape($_);} (@{$rules});
                   1418:             my $rulestr = join(':',@{$rules});
                   1419:             my $homeserver=&domain($udom,'primary');
                   1420:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1421:                 my $response;
                   1422:                 if ($item eq 'username') {                
                   1423:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1424:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1425:                                               $homeserver));
1.923     raeburn  1426:                 } elsif ($item eq 'id') {
                   1427:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1428:                                               ':'.&escape($id).':'.$rulestr,
                   1429:                                               $homeserver));
1.945     raeburn  1430:                 } elsif ($item eq 'selfcreate') {
                   1431:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1432:                                                &escape($udom).':'.&escape($uname).
                   1433:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1434:                 }
1.912     raeburn  1435:                 if ($response ne 'refused') {
                   1436:                     my @pairs=split(/\&/,$response);
                   1437:                     foreach my $item (@pairs) {
                   1438:                         my ($key,$value)=split(/=/,$item,2);
                   1439:                         $key = &unescape($key);
                   1440:                         next if ($key =~ /^error: 2 /);
                   1441:                         $returnhash{$key}=&thaw_unescape($value);
                   1442:                     }
                   1443:                 }
                   1444:             }
                   1445:         }
                   1446:     }
                   1447:     return %returnhash;
                   1448: }
                   1449: 
                   1450: sub inst_userrules {
1.923     raeburn  1451:     my ($udom,$check) = @_;
1.912     raeburn  1452:     my (%ruleshash,@ruleorder);
                   1453:     if ($udom ne '') {
                   1454:         my $homeserver=&domain($udom,'primary');
                   1455:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1456:             my $response;
                   1457:             if ($check eq 'id') {
                   1458:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1459:                                  $homeserver);
1.943     raeburn  1460:             } elsif ($check eq 'email') {
                   1461:                 $response=&reply('instemailrules:'.&escape($udom),
                   1462:                                  $homeserver);
1.923     raeburn  1463:             } else {
                   1464:                 $response=&reply('instuserrules:'.&escape($udom),
                   1465:                                  $homeserver);
                   1466:             }
1.912     raeburn  1467:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1468:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1469:                 ($response ne 'no_such_host')) {
                   1470:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1471:                 my @pairs=split(/\&/,$hashitems);
                   1472:                 foreach my $item (@pairs) {
                   1473:                     my ($key,$value)=split(/=/,$item,2);
                   1474:                     $key = &unescape($key);
                   1475:                     next if ($key =~ /^error: 2 /);
                   1476:                     $ruleshash{$key}=&thaw_unescape($value);
                   1477:                 }
                   1478:                 my @esc_order = split(/\&/,$orderitems);
                   1479:                 foreach my $item (@esc_order) {
                   1480:                     push(@ruleorder,&unescape($item));
                   1481:                 }
                   1482:             }
                   1483:         }
                   1484:     }
                   1485:     return (\%ruleshash,\@ruleorder);
                   1486: }
                   1487: 
1.976     raeburn  1488: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1489: 
                   1490: sub get_domain_defaults {
                   1491:     my ($domain) = @_;
                   1492:     my $cachetime = 60*60*24;
                   1493:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1494:     if (defined($cached)) {
                   1495:         if (ref($result) eq 'HASH') {
                   1496:             return %{$result};
                   1497:         }
                   1498:     }
                   1499:     my %domdefaults;
                   1500:     my %domconfig =
1.989     raeburn  1501:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1502:                                   'requestcourses','inststatus',
1.1073    raeburn  1503:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1504:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1505:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1506:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1507:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1508:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1509:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1510:     } else {
                   1511:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1512:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1513:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1514:     }
1.976     raeburn  1515:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1516:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1517:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1518:         } else {
                   1519:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1520:         } 
                   1521:         my @usertools = ('aboutme','blog','portfolio');
                   1522:         foreach my $item (@usertools) {
                   1523:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1524:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1525:             }
                   1526:         }
                   1527:     }
1.985     raeburn  1528:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1529:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1530:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1531:         }
                   1532:     }
1.989     raeburn  1533:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1534:         foreach my $item ('inststatustypes','inststatusorder') {
                   1535:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1536:         }
                   1537:     }
1.1047    raeburn  1538:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1539:         foreach my $item ('canuse_pdfforms') {
                   1540:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1541:         }
                   1542:     }
1.1073    raeburn  1543:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1544:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1545:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1546:         }
                   1547:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1548:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1549:         }
                   1550:     }
1.943     raeburn  1551:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1552:                                   $cachetime);
                   1553:     return %domdefaults;
                   1554: }
                   1555: 
1.344     www      1556: # --------------------------------------------------- Assign a key to a student
                   1557: 
                   1558: sub assign_access_key {
1.364     www      1559: #
                   1560: # a valid key looks like uname:udom#comments
                   1561: # comments are being appended
                   1562: #
1.498     www      1563:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1564:     $kdom=
1.620     albertel 1565:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1566:     $knum=
1.620     albertel 1567:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1568:     $cdom=
1.620     albertel 1569:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1570:     $cnum=
1.620     albertel 1571:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1572:     $udom=$env{'user.name'} unless (defined($udom));
                   1573:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1574:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1575:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1576:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1577:                                                   # assigned to this person
                   1578:                                                   # - this should not happen,
1.345     www      1579:                                                   # unless something went wrong
                   1580:                                                   # the first time around
                   1581: # ready to assign
1.364     www      1582:         $logentry=$1.'; '.$logentry;
1.496     www      1583:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1584:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1585: # key now belongs to user
1.346     www      1586: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1587:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1588:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1589:                 return 'ok';
                   1590:             } else {
                   1591:                 return 
                   1592:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1593: 	    }
                   1594:         } else {
                   1595:             return 'error: Could not assign key, try again later.';
                   1596:         }
1.364     www      1597:     } elsif (!$existing{$ckey}) {
1.345     www      1598: # the key does not exist
                   1599: 	return 'error: The key does not exist';
                   1600:     } else {
                   1601: # the key is somebody else's
                   1602: 	return 'error: The key is already in use';
                   1603:     }
1.344     www      1604: }
                   1605: 
1.364     www      1606: # ------------------------------------------ put an additional comment on a key
                   1607: 
                   1608: sub comment_access_key {
                   1609: #
                   1610: # a valid key looks like uname:udom#comments
                   1611: # comments are being appended
                   1612: #
                   1613:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1614:     $cdom=
1.620     albertel 1615:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1616:     $cnum=
1.620     albertel 1617:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1618:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1619:     if ($existing{$ckey}) {
                   1620:         $existing{$ckey}.='; '.$logentry;
                   1621: # ready to assign
1.367     www      1622:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1623:                                                  $cdom,$cnum) eq 'ok') {
                   1624: 	    return 'ok';
                   1625:         } else {
                   1626: 	    return 'error: Count not store comment.';
                   1627:         }
                   1628:     } else {
                   1629: # the key does not exist
                   1630: 	return 'error: The key does not exist';
                   1631:     }
                   1632: }
                   1633: 
1.344     www      1634: # ------------------------------------------------------ Generate a set of keys
                   1635: 
                   1636: sub generate_access_keys {
1.364     www      1637:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1638:     $cdom=
1.620     albertel 1639:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1640:     $cnum=
1.620     albertel 1641:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1642:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1643:     unless (($cdom) && ($cnum)) { return 0; }
                   1644:     if ($number>10000) { return 0; }
                   1645:     sleep(2); # make sure don't get same seed twice
                   1646:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1647:     my $total=0;
                   1648:     for (my $i=1;$i<=$number;$i++) {
                   1649:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1650:                   sprintf("%lx",int(100000*rand)).'-'.
                   1651:                   sprintf("%lx",int(100000*rand));
                   1652:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1653:        $newkey=~s/0/h/g; # and also 0 and O
                   1654:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1655:        if ($existing{$newkey}) {
                   1656:            $i--;
                   1657:        } else {
1.364     www      1658: 	  if (&put('accesskeys',
                   1659:               { $newkey => '# generated '.localtime().
1.620     albertel 1660:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1661:                            '; '.$logentry },
                   1662: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1663:               $total++;
                   1664: 	  }
                   1665:        }
                   1666:     }
1.620     albertel 1667:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1668:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1669:     return $total;
                   1670: }
                   1671: 
                   1672: # ------------------------------------------------------- Validate an accesskey
                   1673: 
                   1674: sub validate_access_key {
                   1675:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1676:     $cdom=
1.620     albertel 1677:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1678:     $cnum=
1.620     albertel 1679:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1680:     $udom=$env{'user.domain'} unless (defined($udom));
                   1681:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1682:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1683:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1684: }
                   1685: 
                   1686: # ------------------------------------- Find the section of student in a course
1.652     albertel 1687: sub devalidate_getsection_cache {
                   1688:     my ($udom,$unam,$courseid)=@_;
                   1689:     my $hashid="$udom:$unam:$courseid";
                   1690:     &devalidate_cache_new('getsection',$hashid);
                   1691: }
1.298     matthew  1692: 
1.815     albertel 1693: sub courseid_to_courseurl {
                   1694:     my ($courseid) = @_;
                   1695:     #already url style courseid
                   1696:     return $courseid if ($courseid =~ m{^/});
                   1697: 
                   1698:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1699: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1700: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1701: 	return "/$cdom/$cnum";
                   1702:     }
                   1703: 
                   1704:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1705:     if (exists($courseinfo{'num'})) {
                   1706: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1707:     }
                   1708: 
                   1709:     return undef;
                   1710: }
                   1711: 
1.298     matthew  1712: sub getsection {
                   1713:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1714:     my $cachetime=1800;
1.551     albertel 1715: 
                   1716:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1717:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1718:     if (defined($cached)) { return $result; }
                   1719: 
1.298     matthew  1720:     my %Pending; 
                   1721:     my %Expired;
                   1722:     #
                   1723:     # Each role can either have not started yet (pending), be active, 
                   1724:     #    or have expired.
                   1725:     #
                   1726:     # If there is an active role, we are done.
                   1727:     #
                   1728:     # If there is more than one role which has not started yet, 
                   1729:     #     choose the one which will start sooner
                   1730:     # If there is one role which has not started yet, return it.
                   1731:     #
                   1732:     # If there is more than one expired role, choose the one which ended last.
                   1733:     # If there is a role which has expired, return it.
                   1734:     #
1.815     albertel 1735:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1736:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1737:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1738:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1739:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1740:         my $section=$1;
                   1741:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1742:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1743:         my $now=time;
1.548     albertel 1744:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1745:             $Expired{$end}=$section;
                   1746:             next;
                   1747:         }
1.548     albertel 1748:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1749:             $Pending{$start}=$section;
                   1750:             next;
                   1751:         }
1.599     albertel 1752:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1753:     }
                   1754:     #
                   1755:     # Presumedly there will be few matching roles from the above
                   1756:     # loop and the sorting time will be negligible.
                   1757:     if (scalar(keys(%Pending))) {
                   1758:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1759:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1760:     } 
                   1761:     if (scalar(keys(%Expired))) {
                   1762:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1763:         my $time = pop(@sorted);
1.599     albertel 1764:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1765:     }
1.599     albertel 1766:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1767: }
1.70      www      1768: 
1.599     albertel 1769: sub save_cache {
                   1770:     &purge_remembered();
1.722     albertel 1771:     #&Apache::loncommon::validate_page();
1.620     albertel 1772:     undef(%env);
1.780     albertel 1773:     undef($env_loaded);
1.599     albertel 1774: }
1.452     albertel 1775: 
1.599     albertel 1776: my $to_remember=-1;
                   1777: my %remembered;
                   1778: my %accessed;
                   1779: my $kicks=0;
                   1780: my $hits=0;
1.849     albertel 1781: sub make_key {
                   1782:     my ($name,$id) = @_;
1.872     albertel 1783:     if (length($id) > 65 
                   1784: 	&& length(&escape($id)) > 200) {
                   1785: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1786:     }
1.849     albertel 1787:     return &escape($name.':'.$id);
                   1788: }
                   1789: 
1.599     albertel 1790: sub devalidate_cache_new {
                   1791:     my ($name,$id,$debug) = @_;
                   1792:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1793:     $id=&make_key($name,$id);
1.599     albertel 1794:     $memcache->delete($id);
                   1795:     delete($remembered{$id});
                   1796:     delete($accessed{$id});
                   1797: }
                   1798: 
                   1799: sub is_cached_new {
                   1800:     my ($name,$id,$debug) = @_;
1.849     albertel 1801:     $id=&make_key($name,$id);
1.599     albertel 1802:     if (exists($remembered{$id})) {
                   1803: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1804: 	$accessed{$id}=[&gettimeofday()];
                   1805: 	$hits++;
                   1806: 	return ($remembered{$id},1);
                   1807:     }
                   1808:     my $value = $memcache->get($id);
                   1809:     if (!(defined($value))) {
                   1810: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1811: 	return (undef,undef);
1.416     albertel 1812:     }
1.599     albertel 1813:     if ($value eq '__undef__') {
                   1814: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1815: 	$value=undef;
                   1816:     }
                   1817:     &make_room($id,$value,$debug);
                   1818:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1819:     return ($value,1);
                   1820: }
                   1821: 
                   1822: sub do_cache_new {
                   1823:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1824:     $id=&make_key($name,$id);
1.599     albertel 1825:     my $setvalue=$value;
                   1826:     if (!defined($setvalue)) {
                   1827: 	$setvalue='__undef__';
                   1828:     }
1.623     albertel 1829:     if (!defined($time) ) {
                   1830: 	$time=600;
                   1831:     }
1.599     albertel 1832:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1833:     my $result = $memcache->set($id,$setvalue,$time);
                   1834:     if (! $result) {
1.872     albertel 1835: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1836: 	$memcache->disconnect_all();
1.872     albertel 1837:     }
1.600     albertel 1838:     # need to make a copy of $value
1.919     albertel 1839:     &make_room($id,$value,$debug);
1.599     albertel 1840:     return $value;
                   1841: }
                   1842: 
                   1843: sub make_room {
                   1844:     my ($id,$value,$debug)=@_;
1.919     albertel 1845: 
                   1846:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1847:                                     : $value;
1.599     albertel 1848:     if ($to_remember<0) { return; }
                   1849:     $accessed{$id}=[&gettimeofday()];
                   1850:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1851:     my $to_kick;
                   1852:     my $max_time=0;
                   1853:     foreach my $other (keys(%accessed)) {
                   1854: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1855: 	    $to_kick=$other;
                   1856: 	    $max_time=&tv_interval($accessed{$other});
                   1857: 	}
                   1858:     }
                   1859:     delete($remembered{$to_kick});
                   1860:     delete($accessed{$to_kick});
                   1861:     $kicks++;
                   1862:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1863:     return;
                   1864: }
                   1865: 
1.599     albertel 1866: sub purge_remembered {
1.604     albertel 1867:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1868:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1869:     undef(%remembered);
                   1870:     undef(%accessed);
1.428     albertel 1871: }
1.70      www      1872: # ------------------------------------- Read an entry from a user's environment
                   1873: 
                   1874: sub userenvironment {
                   1875:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1876:     my $items;
                   1877:     foreach my $item (@what) {
                   1878:         $items.=&escape($item).'&';
                   1879:     }
                   1880:     $items=~s/\&$//;
1.70      www      1881:     my %returnhash=();
1.1009    raeburn  1882:     my $uhome = &homeserver($unam,$udom);
                   1883:     unless ($uhome eq 'no_host') {
                   1884:         my @answer=split(/\&/, 
                   1885:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1886:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1887:             return %returnhash;
                   1888:         }
1.1009    raeburn  1889:         my $i;
                   1890:         for ($i=0;$i<=$#what;$i++) {
                   1891: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1892:         }
1.70      www      1893:     }
                   1894:     return %returnhash;
1.1       albertel 1895: }
                   1896: 
1.617     albertel 1897: # ---------------------------------------------------------- Get a studentphoto
                   1898: sub studentphoto {
                   1899:     my ($udom,$unam,$ext) = @_;
                   1900:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1901:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1902:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1903:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1904:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1905:             } else {
                   1906:                 my ($result,$perm_reqd)=
1.707     albertel 1907: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1908:                 if ($result eq 'ok') {
                   1909:                     if (!($perm_reqd eq 'yes')) {
                   1910:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1911:                     }
                   1912:                 }
                   1913:             }
                   1914:         }
                   1915:     } else {
                   1916:         my ($result,$perm_reqd) = 
1.707     albertel 1917: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1918:         if ($result eq 'ok') {
                   1919:             if (!($perm_reqd eq 'yes')) {
                   1920:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1921:             }
                   1922:         }
                   1923:     }
                   1924:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1925: }
                   1926: 
                   1927: sub retrievestudentphoto {
                   1928:     my ($udom,$unam,$ext,$type) = @_;
                   1929:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1930:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1931:     if ($ret eq 'ok') {
                   1932:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1933:         if ($type eq 'thumbnail') {
                   1934:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1935:         }
                   1936:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1937:         return $tokenurl;
                   1938:     } else {
                   1939:         if ($type eq 'thumbnail') {
                   1940:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1941:         } else { 
                   1942:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1943:         }
1.617     albertel 1944:     }
                   1945: }
                   1946: 
1.263     www      1947: # -------------------------------------------------------------------- New chat
                   1948: 
                   1949: sub chatsend {
1.724     raeburn  1950:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1951:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1952:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1953:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1954:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1955: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1956: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1957: }
                   1958: 
                   1959: # ------------------------------------------ Find current version of a resource
                   1960: 
                   1961: sub getversion {
                   1962:     my $fname=&clutter(shift);
                   1963:     unless ($fname=~/^\/res\//) { return -1; }
                   1964:     return &currentversion(&filelocation('',$fname));
                   1965: }
                   1966: 
                   1967: sub currentversion {
                   1968:     my $fname=shift;
1.599     albertel 1969:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1970:     if (defined($cached)) { return $result; }
1.292     www      1971:     my $author=$fname;
                   1972:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1973:     my ($udom,$uname)=split(/\//,$author);
                   1974:     my $home=homeserver($uname,$udom);
                   1975:     if ($home eq 'no_host') { 
                   1976:         return -1; 
                   1977:     }
                   1978:     my $answer=reply("currentversion:$fname",$home);
                   1979:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1980: 	return -1;
                   1981:     }
1.599     albertel 1982:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1983: }
                   1984: 
1.1       albertel 1985: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1986: 
1.1       albertel 1987: sub subscribe {
                   1988:     my $fname=shift;
1.761     raeburn  1989:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1990:     $fname=~s/[\n\r]//g;
1.1       albertel 1991:     my $author=$fname;
                   1992:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1993:     my ($udom,$uname)=split(/\//,$author);
                   1994:     my $home=homeserver($uname,$udom);
1.335     albertel 1995:     if ($home eq 'no_host') {
                   1996:         return 'not_found';
1.1       albertel 1997:     }
                   1998:     my $answer=reply("sub:$fname",$home);
1.64      www      1999:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2000: 	$answer.=' by '.$home;
                   2001:     }
1.1       albertel 2002:     return $answer;
                   2003: }
                   2004:     
1.8       www      2005: # -------------------------------------------------------------- Replicate file
                   2006: 
                   2007: sub repcopy {
                   2008:     my $filename=shift;
1.23      www      2009:     $filename=~s/\/+/\//g;
1.607     raeburn  2010:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2011:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2012:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2013: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2014: 	return &repcopy_userfile($filename);
                   2015:     }
1.532     albertel 2016:     $filename=~s/[\n\r]//g;
1.8       www      2017:     my $transname="$filename.in.transfer";
1.828     www      2018: # FIXME: this should flock
1.607     raeburn  2019:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2020:     my $remoteurl=subscribe($filename);
1.64      www      2021:     if ($remoteurl =~ /^con_lost by/) {
                   2022: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2023:            return 'unavailable';
1.8       www      2024:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2025: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2026: 	   return 'not_found';
1.64      www      2027:     } elsif ($remoteurl =~ /^rejected by/) {
                   2028: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2029:            return 'forbidden';
1.20      www      2030:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2031:            return 'ok';
1.8       www      2032:     } else {
1.290     www      2033:         my $author=$filename;
                   2034:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2035:         my ($udom,$uname)=split(/\//,$author);
                   2036:         my $home=homeserver($uname,$udom);
                   2037:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2038:            my @parts=split(/\//,$filename);
                   2039:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2040:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2041:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2042: 	       return 'bad_request';
1.8       www      2043:            }
                   2044:            my $count;
                   2045:            for ($count=5;$count<$#parts;$count++) {
                   2046:                $path.="/$parts[$count]";
                   2047:                if ((-e $path)!=1) {
                   2048: 		   mkdir($path,0777);
                   2049:                }
                   2050:            }
                   2051:            my $ua=new LWP::UserAgent;
                   2052:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2053:            my $response=$ua->request($request,$transname);
                   2054:            if ($response->is_error()) {
                   2055: 	       unlink($transname);
                   2056:                my $message=$response->status_line;
1.672     albertel 2057:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2058:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2059:                return 'unavailable';
1.8       www      2060:            } else {
1.16      www      2061: 	       if ($remoteurl!~/\.meta$/) {
                   2062:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2063:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2064:                   if ($mresponse->is_error()) {
                   2065: 		      unlink($filename.'.meta');
                   2066:                       &logthis(
1.672     albertel 2067:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2068:                   }
                   2069: 	       }
1.8       www      2070:                rename($transname,$filename);
1.607     raeburn  2071:                return 'ok';
1.8       www      2072:            }
1.290     www      2073:        }
1.8       www      2074:     }
1.330     www      2075: }
                   2076: 
                   2077: # ------------------------------------------------ Get server side include body
                   2078: sub ssi_body {
1.381     albertel 2079:     my ($filelink,%form)=@_;
1.606     matthew  2080:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2081:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2082:     }
1.953     www      2083:     my $output='';
                   2084:     my $response;
1.980     raeburn  2085:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2086:        ($output,$response)=&externalssi($filelink);
1.953     www      2087:     } else {
1.1004    droeschl 2088:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2089:        $filelink .= 'inhibitmenu=yes';
1.953     www      2090:        ($output,$response)=&ssi($filelink,%form);
                   2091:     }
1.778     albertel 2092:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2093:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2094:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2095:     if (wantarray) {
                   2096:         return ($output, $response);
                   2097:     } else {
                   2098:         return $output;
                   2099:     }
1.8       www      2100: }
                   2101: 
1.15      www      2102: # --------------------------------------------------------- Server Side Include
                   2103: 
1.782     albertel 2104: sub absolute_url {
                   2105:     my ($host_name) = @_;
                   2106:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2107:     if ($host_name eq '') {
                   2108: 	$host_name = $ENV{'SERVER_NAME'};
                   2109:     }
                   2110:     return $protocol.$host_name;
                   2111: }
                   2112: 
1.942     foxr     2113: #
                   2114: #   Server side include.
                   2115: # Parameters:
                   2116: #  fn     Possibly encrypted resource name/id.
                   2117: #  form   Hash that describes how the rendering should be done
                   2118: #         and other things.
1.944     foxr     2119: # Returns:
1.950     raeburn  2120: #   Scalar context: The content of the response.
                   2121: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2122: #     
1.15      www      2123: sub ssi {
                   2124: 
1.944     foxr     2125:     my ($fn,%form)=@_;
1.15      www      2126:     my $ua=new LWP::UserAgent;
1.23      www      2127:     my $request;
1.711     albertel 2128: 
                   2129:     $form{'no_update_last_known'}=1;
1.895     albertel 2130:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2131:     if (%form) {
1.782     albertel 2132:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2133:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2134:     } else {
1.782     albertel 2135:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2136:     }
                   2137: 
1.15      www      2138:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2139:     my $response=$ua->request($request);
                   2140: 
1.944     foxr     2141:     if (wantarray) {
                   2142: 	return ($response->content, $response);
                   2143:     } else {
                   2144: 	return $response->content;
1.942     foxr     2145:     }
1.324     www      2146: }
                   2147: 
                   2148: sub externalssi {
                   2149:     my ($url)=@_;
                   2150:     my $ua=new LWP::UserAgent;
                   2151:     my $request=new HTTP::Request('GET',$url);
                   2152:     my $response=$ua->request($request);
1.954     raeburn  2153:     if (wantarray) {
                   2154:         return ($response->content, $response);
                   2155:     } else {
                   2156:         return $response->content;
                   2157:     }
1.15      www      2158: }
1.254     www      2159: 
1.492     albertel 2160: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2161: 
                   2162: sub allowuploaded {
                   2163:     my ($srcurl,$url)=@_;
                   2164:     $url=&clutter(&declutter($url));
                   2165:     my $dir=$url;
                   2166:     $dir=~s/\/[^\/]+$//;
                   2167:     my %httpref=();
                   2168:     my $httpurl=&hreflocation('',$url);
                   2169:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2170:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2171: }
1.477     raeburn  2172: 
1.478     albertel 2173: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2174: # input: action, courseID, current domain, intended
1.637     raeburn  2175: #        path to file, source of file, instruction to parse file for objects,
                   2176: #        ref to hash for embedded objects,
                   2177: #        ref to hash for codebase of java objects.
                   2178: #
1.485     raeburn  2179: # output: url to file (if action was uploaddoc), 
                   2180: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2181: #
1.478     albertel 2182: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2183: # course.
1.477     raeburn  2184: #
1.478     albertel 2185: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2186: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2187: #          course's home server.
1.477     raeburn  2188: #
1.478     albertel 2189: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2190: #          be copied from $source (current location) to 
                   2191: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2192: #         and will then be copied to
                   2193: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2194: #         course's home server.
1.485     raeburn  2195: #
1.481     raeburn  2196: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2197: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2198: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2199: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2200: #         in course's home server.
1.637     raeburn  2201: #
1.477     raeburn  2202: 
                   2203: sub process_coursefile {
1.638     albertel 2204:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2205:     my $fetchresult;
1.638     albertel 2206:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2207:     if ($action eq 'propagate') {
1.638     albertel 2208:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2209: 			     $home);
1.481     raeburn  2210:     } else {
1.477     raeburn  2211:         my $fpath = '';
                   2212:         my $fname = $file;
1.478     albertel 2213:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2214:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2215:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2216:         if ($action eq 'copy') {
                   2217:             if ($source eq '') {
                   2218:                 $fetchresult = 'no source file';
                   2219:                 return $fetchresult;
                   2220:             } else {
                   2221:                 my $destination = $filepath.'/'.$fname;
                   2222:                 rename($source,$destination);
                   2223:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2224:                                  $home);
1.481     raeburn  2225:             }
                   2226:         } elsif ($action eq 'uploaddoc') {
                   2227:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2228:             print $fh $env{'form.'.$source};
1.481     raeburn  2229:             close($fh);
1.637     raeburn  2230:             if ($parser eq 'parse') {
1.1024    raeburn  2231:                 my $mm = new File::MMagic;
                   2232:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2233:                 if ($mime_type eq 'text/html') {
                   2234:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2235:                     unless ($parse_result eq 'ok') {
                   2236:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2237:                     }
1.637     raeburn  2238:                 }
                   2239:             }
1.477     raeburn  2240:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2241:                                  $home);
1.481     raeburn  2242:             if ($fetchresult eq 'ok') {
                   2243:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2244:             } else {
                   2245:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2246:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2247:                 return '/adm/notfound.html';
                   2248:             }
1.477     raeburn  2249:         }
                   2250:     }
1.485     raeburn  2251:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2252:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2253:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2254:     }
                   2255:     return $fetchresult;
                   2256: }
                   2257: 
1.637     raeburn  2258: sub build_filepath {
                   2259:     my ($fpath) = @_;
                   2260:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2261:     unless ($fpath eq '') {
                   2262:         my @parts=split('/',$fpath);
                   2263:         foreach my $part (@parts) {
                   2264:             $filepath.= '/'.$part;
                   2265:             if ((-e $filepath)!=1) {
                   2266:                 mkdir($filepath,0777);
                   2267:             }
                   2268:         }
                   2269:     }
                   2270:     return $filepath;
                   2271: }
                   2272: 
                   2273: sub store_edited_file {
1.638     albertel 2274:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2275:     my $file = $primary_url;
                   2276:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2277:     my $fpath = '';
                   2278:     my $fname = $file;
                   2279:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2280:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2281:     my $filepath = &build_filepath($fpath);
                   2282:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2283:     print $fh $content;
                   2284:     close($fh);
1.638     albertel 2285:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2286:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2287: 			  $home);
1.637     raeburn  2288:     if ($$fetchresult eq 'ok') {
                   2289:         return '/uploaded/'.$fpath.'/'.$fname;
                   2290:     } else {
1.638     albertel 2291:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2292: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2293:         return '/adm/notfound.html';
                   2294:     }
                   2295: }
                   2296: 
1.531     albertel 2297: sub clean_filename {
1.831     albertel 2298:     my ($fname,$args)=@_;
1.315     www      2299: # Replace Windows backslashes by forward slashes
1.257     www      2300:     $fname=~s/\\/\//g;
1.831     albertel 2301:     if (!$args->{'keep_path'}) {
                   2302:         # Get rid of everything but the actual filename
                   2303: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2304:     }
1.315     www      2305: # Replace spaces by underscores
                   2306:     $fname=~s/\s+/\_/g;
                   2307: # Replace all other weird characters by nothing
1.831     albertel 2308:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2309: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2310: # numbers
                   2311:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2312:     return $fname;
                   2313: }
1.1051    raeburn  2314: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2315: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2316: # image with the same aspect ratio as the original, but with dimensions which do 
                   2317: # not exceed $resizewidth and $resizeheight.
                   2318:  
1.984     neumanie 2319: sub resizeImage {
1.1051    raeburn  2320:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2321:     my $ima = Image::Magick->new;
                   2322:     my $resized;
                   2323:     if (-e $img_path) {
                   2324:         $ima->Read($img_path);
                   2325:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2326:             my $width = $ima->Get('width');
                   2327:             my $height = $ima->Get('height');
                   2328:             if ($width > $resizewidth) {
                   2329: 	        my $factor = $width/$resizewidth;
                   2330:                 my $newheight = $height/$factor;
                   2331:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2332:                 $resized = 1;
                   2333:             }
                   2334:         }
                   2335:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2336:             my $width = $ima->Get('width');
                   2337:             my $height = $ima->Get('height');
                   2338:             if ($height > $resizeheight) {
                   2339:                 my $factor = $height/$resizeheight;
                   2340:                 my $newwidth = $width/$factor;
                   2341:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2342:                 $resized = 1;
                   2343:             }
                   2344:         }
                   2345:         if ($resized) {
                   2346:             $ima->Write($img_path);
                   2347:         }
                   2348:     }
                   2349:     return;
1.977     amueller 2350: }
                   2351: 
1.608     albertel 2352: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2353: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2354: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2355: #        $coursedoc - if true up to the current course
                   2356: #                     if false
                   2357: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2358: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2359: #        $allfiles - reference to hash for embedded objects
                   2360: #        $codebase - reference to hash for codebase of java objects
                   2361: #        $desuname - username for permanent storage of uploaded file
                   2362: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2363: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2364: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2365: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2366: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2367: # 
1.686     albertel 2368: # output: url of file in userspace, or error: <message> 
                   2369: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2370: 
1.531     albertel 2371: sub userfileupload {
1.860     raeburn  2372:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2373:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2374:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2375:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2376:     $fname=&clean_filename($fname);
1.315     www      2377: # See if there is anything left
1.257     www      2378:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2379:     chop($env{'form.'.$formname});
1.523     raeburn  2380:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2381:         my $now = time;
                   2382:         my $filepath = 'tmp/helprequests/'.$now;
                   2383:         my @parts=split(/\//,$filepath);
                   2384:         my $fullpath = $perlvar{'lonDaemons'};
                   2385:         for (my $i=0;$i<@parts;$i++) {
                   2386:             $fullpath .= '/'.$parts[$i];
                   2387:             if ((-e $fullpath)!=1) {
                   2388:                 mkdir($fullpath,0777);
                   2389:             }
                   2390:         }
                   2391:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2392:         print $fh $env{'form.'.$formname};
1.523     raeburn  2393:         close($fh);
1.741     raeburn  2394:         return $fullpath.'/'.$fname;
                   2395:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2396:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2397:                        '_'.$env{'user.domain'}.'/pending';
                   2398:         my @parts=split(/\//,$filepath);
                   2399:         my $fullpath = $perlvar{'lonDaemons'};
                   2400:         for (my $i=0;$i<@parts;$i++) {
                   2401:             $fullpath .= '/'.$parts[$i];
                   2402:             if ((-e $fullpath)!=1) {
                   2403:                 mkdir($fullpath,0777);
                   2404:             }
                   2405:         }
                   2406:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2407:         print $fh $env{'form.'.$formname};
                   2408:         close($fh);
                   2409:         return $fullpath.'/'.$fname;
1.523     raeburn  2410:     }
1.995     raeburn  2411:     if ($subdir eq 'scantron') {
                   2412:         $fname = 'scantron_orig_'.$fname;
                   2413:     } else {   
1.258     www      2414: # Create the directory if not present
1.995     raeburn  2415:         $fname="$subdir/$fname";
                   2416:     }
1.259     www      2417:     if ($coursedoc) {
1.638     albertel 2418: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2419: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2420:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2421:             return &finishuserfileupload($docuname,$docudom,
                   2422: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2423: 					 $codebase,$thumbwidth,$thumbheight,
                   2424:                                          $resizewidth,$resizeheight);
1.481     raeburn  2425:         } else {
1.620     albertel 2426:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2427:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2428: 				       $fname,$formname,$parser,
                   2429: 				       $allfiles,$codebase);
1.481     raeburn  2430:         }
1.719     banghart 2431:     } elsif (defined($destuname)) {
                   2432:         my $docuname=$destuname;
                   2433:         my $docudom=$destudom;
1.860     raeburn  2434: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2435: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2436:                                      $thumbwidth,$thumbheight,
                   2437:                                      $resizewidth,$resizeheight);
1.719     banghart 2438:         
1.259     www      2439:     } else {
1.638     albertel 2440:         my $docuname=$env{'user.name'};
                   2441:         my $docudom=$env{'user.domain'};
1.714     raeburn  2442:         if (exists($env{'form.group'})) {
                   2443:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2444:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2445:         }
1.860     raeburn  2446: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2447: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2448:                                      $thumbwidth,$thumbheight,
                   2449:                                      $resizewidth,$resizeheight);
1.259     www      2450:     }
1.271     www      2451: }
                   2452: 
                   2453: sub finishuserfileupload {
1.860     raeburn  2454:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051    raeburn  2455:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477     raeburn  2456:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2457:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2458:   
1.860     raeburn  2459:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2460:     $file=$fname;
                   2461:     if ($fname=~m|/|) {
                   2462:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2463: 	$path.=$fnamepath.'/';
                   2464:     }
1.259     www      2465:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2466:     my $count;
                   2467:     for ($count=4;$count<=$#parts;$count++) {
                   2468:         $filepath.="/$parts[$count]";
                   2469:         if ((-e $filepath)!=1) {
                   2470: 	    mkdir($filepath,0777);
                   2471:         }
                   2472:     }
1.984     neumanie 2473: 
1.258     www      2474: # Save the file
                   2475:     {
1.701     albertel 2476: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2477: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2478: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2479: 	    return '/adm/notfound.html';
                   2480: 	}
                   2481: 	if (!print FH ($env{'form.'.$formname})) {
                   2482: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2483: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2484: 	    return '/adm/notfound.html';
                   2485: 	}
1.570     albertel 2486: 	close(FH);
1.1051    raeburn  2487:         if ($resizewidth && $resizeheight) {
                   2488:             my $mm = new File::MMagic;
                   2489:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2490:             if ($mime_type =~ m{^image/}) {
                   2491: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2492:             }  
1.977     amueller 2493: 	}
1.258     www      2494:     }
1.637     raeburn  2495:     if ($parser eq 'parse') {
1.1024    raeburn  2496:         my $mm = new File::MMagic;
                   2497:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2498:         if ($mime_type eq 'text/html') {
                   2499:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2500:                                                        $allfiles,$codebase);
                   2501:             unless ($parse_result eq 'ok') {
                   2502:                 &logthis('Failed to parse '.$filepath.$file.
                   2503: 	   	         ' for embedded media: '.$parse_result); 
                   2504:             }
1.637     raeburn  2505:         }
                   2506:     }
1.860     raeburn  2507:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2508:         my $input = $filepath.'/'.$file;
                   2509:         my $output = $filepath.'/'.'tn-'.$file;
                   2510:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2511:         system("convert -sample $thumbsize $input $output");
                   2512:         if (-e $filepath.'/'.'tn-'.$file) {
                   2513:             $fetchthumb  = 1; 
                   2514:         }
                   2515:     }
1.858     raeburn  2516:  
1.259     www      2517: # Notify homeserver to grep it
                   2518: #
1.984     neumanie 2519:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2520:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2521:     if ($fetchresult eq 'ok') {
1.860     raeburn  2522:         if ($fetchthumb) {
                   2523:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2524:             if ($thumbresult ne 'ok') {
                   2525:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2526:                          $docuhome.': '.$thumbresult);
                   2527:             }
                   2528:         }
1.259     www      2529: #
1.258     www      2530: # Return the URL to it
1.494     albertel 2531:         return '/uploaded/'.$path.$file;
1.263     www      2532:     } else {
1.494     albertel 2533:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2534: 		 ': '.$fetchresult);
1.263     www      2535:         return '/adm/notfound.html';
1.858     raeburn  2536:     }
1.493     albertel 2537: }
                   2538: 
1.637     raeburn  2539: sub extract_embedded_items {
1.961     raeburn  2540:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2541:     my @state = ();
                   2542:     my %javafiles = (
                   2543:                       codebase => '',
                   2544:                       code => '',
                   2545:                       archive => ''
                   2546:                     );
                   2547:     my %mediafiles = (
                   2548:                       src => '',
                   2549:                       movie => '',
                   2550:                      );
1.648     raeburn  2551:     my $p;
                   2552:     if ($content) {
                   2553:         $p = HTML::LCParser->new($content);
                   2554:     } else {
1.961     raeburn  2555:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2556:     }
1.641     albertel 2557:     while (my $t=$p->get_token()) {
1.640     albertel 2558: 	if ($t->[0] eq 'S') {
                   2559: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2560: 	    push(@state, $tagname);
1.648     raeburn  2561:             if (lc($tagname) eq 'allow') {
                   2562:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2563:             }
1.640     albertel 2564: 	    if (lc($tagname) eq 'img') {
                   2565: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2566: 	    }
1.886     albertel 2567: 	    if (lc($tagname) eq 'a') {
                   2568: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2569: 	    }
1.645     raeburn  2570:             if (lc($tagname) eq 'script') {
                   2571:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2572:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2573:                 } else {
                   2574:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2575:                 }
                   2576:             }
                   2577:             if (lc($tagname) eq 'link') {
                   2578:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2579:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2580:                 }
                   2581:             }
1.640     albertel 2582: 	    if (lc($tagname) eq 'object' ||
                   2583: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2584: 		foreach my $item (keys(%javafiles)) {
                   2585: 		    $javafiles{$item} = '';
                   2586: 		}
                   2587: 	    }
                   2588: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2589: 		my $name = lc($attr->{'name'});
                   2590: 		foreach my $item (keys(%javafiles)) {
                   2591: 		    if ($name eq $item) {
                   2592: 			$javafiles{$item} = $attr->{'value'};
                   2593: 			last;
                   2594: 		    }
                   2595: 		}
                   2596: 		foreach my $item (keys(%mediafiles)) {
                   2597: 		    if ($name eq $item) {
                   2598: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2599: 			last;
                   2600: 		    }
                   2601: 		}
                   2602: 	    }
                   2603: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2604: 		foreach my $item (keys(%javafiles)) {
                   2605: 		    if ($attr->{$item}) {
                   2606: 			$javafiles{$item} = $attr->{$item};
                   2607: 			last;
                   2608: 		    }
                   2609: 		}
                   2610: 		foreach my $item (keys(%mediafiles)) {
                   2611: 		    if ($attr->{$item}) {
                   2612: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2613: 			last;
                   2614: 		    }
                   2615: 		}
                   2616: 	    }
                   2617: 	} elsif ($t->[0] eq 'E') {
                   2618: 	    my ($tagname) = ($t->[1]);
                   2619: 	    if ($javafiles{'codebase'} ne '') {
                   2620: 		$javafiles{'codebase'} .= '/';
                   2621: 	    }  
                   2622: 	    if (lc($tagname) eq 'applet' ||
                   2623: 		lc($tagname) eq 'object' ||
                   2624: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2625: 		) {
                   2626: 		foreach my $item (keys(%javafiles)) {
                   2627: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2628: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2629: 			&add_filetype($allfiles,$file,$item);
                   2630: 		    }
                   2631: 		}
                   2632: 	    } 
                   2633: 	    pop @state;
                   2634: 	}
                   2635:     }
1.637     raeburn  2636:     return 'ok';
                   2637: }
                   2638: 
1.639     albertel 2639: sub add_filetype {
                   2640:     my ($allfiles,$file,$type)=@_;
                   2641:     if (exists($allfiles->{$file})) {
                   2642: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2643: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2644: 	}
                   2645:     } else {
                   2646: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2647:     }
                   2648: }
                   2649: 
1.493     albertel 2650: sub removeuploadedurl {
1.984     neumanie 2651:     my ($url)=@_;	
                   2652:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2653:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2654: }
                   2655: 
                   2656: sub removeuserfile {
                   2657:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2658:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2659:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2660:     if ($result eq 'ok') {	
1.798     raeburn  2661:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2662:             my $metafile = $fname.'.meta';
                   2663:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2664: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2665:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2666:             my $sqlresult = 
1.823     albertel 2667:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2668:                                         'portfolio_metadata',$group,
                   2669:                                         'delete');
1.798     raeburn  2670:         }
                   2671:     }
                   2672:     return $result;
1.257     www      2673: }
1.15      www      2674: 
1.530     albertel 2675: sub mkdiruserfile {
                   2676:     my ($docuname,$docudom,$dir)=@_;
                   2677:     my $home=&homeserver($docuname,$docudom);
                   2678:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2679: }
                   2680: 
1.531     albertel 2681: sub renameuserfile {
                   2682:     my ($docuname,$docudom,$old,$new)=@_;
                   2683:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2684:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2685:                         &escape("$old").':'.&escape("$new"),$home);
                   2686:     if ($result eq 'ok') {
                   2687:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2688:             my $oldmeta = $old.'.meta';
                   2689:             my $newmeta = $new.'.meta';
                   2690:             my $metaresult = 
                   2691:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2692: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2693:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2694:             my $sqlresult = 
1.823     albertel 2695:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2696:                                         'portfolio_metadata',$group,
                   2697:                                         'delete');
1.798     raeburn  2698:         }
                   2699:     }
                   2700:     return $result;
1.531     albertel 2701: }
                   2702: 
1.14      www      2703: # ------------------------------------------------------------------------- Log
                   2704: 
                   2705: sub log {
                   2706:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2707:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2708: }
                   2709: 
                   2710: # ------------------------------------------------------------------ Course Log
1.352     www      2711: #
                   2712: # This routine flushes several buffers of non-mission-critical nature
                   2713: #
1.157     www      2714: 
                   2715: sub flushcourselogs {
1.352     www      2716:     &logthis('Flushing log buffers');
                   2717: #
                   2718: # course logs
                   2719: # This is a log of all transactions in a course, which can be used
                   2720: # for data mining purposes
                   2721: #
                   2722: # It also collects the courseid database, which lists last transaction
                   2723: # times and course titles for all courseids
                   2724: #
                   2725:     my %courseidbuffer=();
1.921     raeburn  2726:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2727:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2728: 		          &escape($courselogs{$crsid}),
                   2729: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2730: 	    delete $courselogs{$crsid};
                   2731:         } else {
                   2732:             &logthis('Failed to flush log buffer for '.$crsid);
                   2733:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2734:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2735:                         " exceeded maximum size, deleting.</font>");
                   2736:                delete $courselogs{$crsid};
                   2737:             }
1.352     www      2738:         }
1.920     raeburn  2739:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2740:             'description' => $coursedescrbuf{$crsid},
                   2741:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2742:             'type'        => $coursetypebuf{$crsid},
                   2743:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2744:         };
1.191     harris41 2745:     }
1.352     www      2746: #
                   2747: # Write course id database (reverse lookup) to homeserver of courses 
                   2748: # Is used in pickcourse
                   2749: #
1.840     albertel 2750:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2751:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2752:                                     $courseidbuffer{$crs_home},
                   2753:                                     $crs_home,'timeonly');
1.352     www      2754:     }
                   2755: #
                   2756: # File accesses
                   2757: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2758: #
1.449     matthew  2759:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2760:         if ($entry =~ /___count$/) {
                   2761:             my ($dom,$name);
1.807     albertel 2762:             ($dom,$name,undef)=
1.811     albertel 2763: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2764:             if (! defined($dom) || $dom eq '' || 
                   2765:                 ! defined($name) || $name eq '') {
1.620     albertel 2766:                 my $cid = $env{'request.course.id'};
                   2767:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2768:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2769:             }
1.450     matthew  2770:             my $value = $accesshash{$entry};
                   2771:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2772:             my %temphash=($url => $value);
1.449     matthew  2773:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2774:             if ($result eq 'ok') {
                   2775:                 delete $accesshash{$entry};
                   2776:             } elsif ($result eq 'unknown_cmd') {
                   2777:                 # Target server has old code running on it.
1.450     matthew  2778:                 my %temphash=($entry => $value);
1.449     matthew  2779:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2780:                     delete $accesshash{$entry};
                   2781:                 }
                   2782:             }
                   2783:         } else {
1.811     albertel 2784:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2785:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2786:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2787:                 delete $accesshash{$entry};
                   2788:             }
1.185     www      2789:         }
1.191     harris41 2790:     }
1.352     www      2791: #
                   2792: # Roles
                   2793: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2794: #
1.800     albertel 2795:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2796:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2797: 	    split(/\:/,$entry);
                   2798:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2799:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2800:                 $rudom,$runame) eq 'ok') {
                   2801: 	    delete $userrolehash{$entry};
                   2802:         }
                   2803:     }
1.662     raeburn  2804: #
                   2805: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2806: #
                   2807:     my %domrolebuffer = ();
1.1000    raeburn  2808:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2809:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2810:         if ($domrolebuffer{$rudom}) {
                   2811:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2812:                       '='.&escape($domainrolehash{$entry});
                   2813:         } else {
                   2814:             $domrolebuffer{$rudom}.=&escape($entry).
                   2815:                       '='.&escape($domainrolehash{$entry});
                   2816:         }
                   2817:         delete $domainrolehash{$entry};
                   2818:     }
                   2819:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2820: 	my %servers = &get_servers($dom,'library');
                   2821: 	foreach my $tryserver (keys(%servers)) {
                   2822: 	    unless (&reply('domroleput:'.$dom.':'.
                   2823: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2824: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2825: 	    }
1.662     raeburn  2826:         }
                   2827:     }
1.186     www      2828:     $dumpcount++;
1.157     www      2829: }
                   2830: 
                   2831: sub courselog {
                   2832:     my $what=shift;
1.158     www      2833:     $what=time.':'.$what;
1.620     albertel 2834:     unless ($env{'request.course.id'}) { return ''; }
                   2835:     $coursedombuf{$env{'request.course.id'}}=
                   2836:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2837:     $coursenumbuf{$env{'request.course.id'}}=
                   2838:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2839:     $coursehombuf{$env{'request.course.id'}}=
                   2840:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2841:     $coursedescrbuf{$env{'request.course.id'}}=
                   2842:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2843:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2844:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2845:     $courseownerbuf{$env{'request.course.id'}}=
                   2846:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2847:     $coursetypebuf{$env{'request.course.id'}}=
                   2848:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2849:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2850: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2851:     } else {
1.620     albertel 2852: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2853:     }
1.620     albertel 2854:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2855: 	&flushcourselogs();
                   2856:     }
1.158     www      2857: }
                   2858: 
                   2859: sub courseacclog {
                   2860:     my $fnsymb=shift;
1.620     albertel 2861:     unless ($env{'request.course.id'}) { return ''; }
                   2862:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2863:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2864:         $what.=':POST';
1.583     matthew  2865:         # FIXME: Probably ought to escape things....
1.800     albertel 2866: 	foreach my $key (keys(%env)) {
                   2867:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2868:                 my $formitem = $1;
                   2869:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2870:                     $what.=':'.$formitem.'='.$env{$key};
                   2871:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2872:                     $what.=':'.$formitem.'='.$env{$key};
                   2873:                 }
1.158     www      2874:             }
1.191     harris41 2875:         }
1.583     matthew  2876:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2877:         # FIXME: We should not be depending on a form parameter that someone
                   2878:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2879:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2880:             $what.= ':POST';
                   2881:             # FIXME: Probably ought to escape things....
                   2882:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2883:                                  'crsdiscuss') {
1.620     albertel 2884:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2885:             }
                   2886:         }
1.158     www      2887:     }
                   2888:     &courselog($what);
1.149     www      2889: }
                   2890: 
1.185     www      2891: sub countacc {
                   2892:     my $url=&declutter(shift);
1.458     matthew  2893:     return if (! defined($url) || $url eq '');
1.620     albertel 2894:     unless ($env{'request.course.id'}) { return ''; }
                   2895:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2896:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2897:     $accesshash{$key}++;
1.185     www      2898: }
1.349     www      2899: 
1.361     www      2900: sub linklog {
                   2901:     my ($from,$to)=@_;
                   2902:     $from=&declutter($from);
                   2903:     $to=&declutter($to);
                   2904:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2905:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2906: }
                   2907:   
1.349     www      2908: sub userrolelog {
                   2909:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2910:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2911:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2912:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2913:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2914:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2915:        $userrolehash
                   2916:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2917:                     =$tend.':'.$tstart;
1.662     raeburn  2918:     }
1.898     albertel 2919:     if (($env{'request.role'} =~ /dc\./) &&
                   2920: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2921: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2922: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2923:          ($trole=~/^co/))) {
1.898     albertel 2924:        $userrolehash
                   2925:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2926:                     =$tend.':'.$tstart;
                   2927:     }
1.662     raeburn  2928:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2929:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2930:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2931:         ($trole=~/^sc/)) {
                   2932:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2933:        $domainrolehash
                   2934:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2935:                     = $tend.':'.$tstart;
                   2936:     }
1.351     www      2937: }
                   2938: 
1.957     raeburn  2939: sub courserolelog {
                   2940:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2941:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2942:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2943:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2944:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2945:         ($trole eq 'co')) {
1.957     raeburn  2946:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2947:             my $cdom = $1;
                   2948:             my $cnum = $2;
                   2949:             my $sec = $3;
                   2950:             my $namespace = 'rolelog';
                   2951:             my %storehash = (
                   2952:                                role    => $trole,
                   2953:                                start   => $tstart,
                   2954:                                end     => $tend,
                   2955:                                selfenroll => $selfenroll,
                   2956:                                context    => $context,
                   2957:                             );
                   2958:             if ($trole eq 'gr') {
                   2959:                 $namespace = 'groupslog';
                   2960:                 $storehash{'group'} = $sec;
                   2961:             } else {
                   2962:                 $storehash{'section'} = $sec;
                   2963:             }
                   2964:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2965:             if (($trole ne 'st') || ($sec ne '')) {
                   2966:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2967:             }
1.957     raeburn  2968:         }
                   2969:     }
                   2970:     return;
                   2971: }
                   2972: 
1.351     www      2973: sub get_course_adv_roles {
1.948     raeburn  2974:     my ($cid,$codes) = @_;
1.620     albertel 2975:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2976:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2977:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2978:     my %nothide=();
1.800     albertel 2979:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2980:         if ($user !~ /:/) {
                   2981: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2982:         } else {
                   2983:             $nothide{$user}=1;
                   2984:         }
1.470     www      2985:     }
1.351     www      2986:     my %returnhash=();
                   2987:     my %dumphash=
                   2988:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2989:     my $now=time;
1.997     raeburn  2990:     my %privileged;
1.1000    raeburn  2991:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2992: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2993:         if (($tstart) && ($tstart<0)) { next; }
                   2994:         if (($tend) && ($tend<$now)) { next; }
                   2995:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2996:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2997: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2998:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2999:             my %dompersonnel =
1.998     raeburn  3000:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3001:             $privileged{$domain} = {};
                   3002:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3003:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3004:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3005:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3006:                         $privileged{$udom}{$uname} = 1;
                   3007:                     }
                   3008:                 }
                   3009:             }
                   3010:         }
                   3011:         if ((exists($privileged{$domain}{$username})) && 
                   3012:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3013: 	if ($role eq 'cr') { next; }
1.948     raeburn  3014:         if ($codes) {
                   3015:             if ($section) { $role .= ':'.$section; }
                   3016:             if ($returnhash{$role}) {
                   3017:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3018:             } else {
                   3019:                 $returnhash{$role}=$username.':'.$domain;
                   3020:             }
1.351     www      3021:         } else {
1.988     raeburn  3022:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3023:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3024:             if ($returnhash{$key}) {
                   3025: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3026:             } else {
                   3027:                 $returnhash{$key}=$username.':'.$domain;
                   3028:             }
1.351     www      3029:         }
1.948     raeburn  3030:     }
1.400     www      3031:     return %returnhash;
                   3032: }
                   3033: 
                   3034: sub get_my_roles {
1.937     raeburn  3035:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3036:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3037:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3038:     my (%dumphash,%nothide);
1.1086    raeburn  3039:     if ($context eq 'userroles') {
                   3040:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3041:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3042:     } else {
                   3043:         %dumphash=
1.400     www      3044:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3045:         if ($hidepriv) {
                   3046:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3047:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3048:                 if ($user !~ /:/) {
                   3049:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3050:                 } else {
                   3051:                     $nothide{$user} = 1;
                   3052:                 }
                   3053:             }
                   3054:         }
1.858     raeburn  3055:     }
1.400     www      3056:     my %returnhash=();
                   3057:     my $now=time;
1.999     raeburn  3058:     my %privileged;
1.800     albertel 3059:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3060:         my ($role,$tend,$tstart);
                   3061:         if ($context eq 'userroles') {
                   3062: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3063:         } else {
                   3064:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3065:         }
1.400     www      3066:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3067:         my $status = 'active';
1.939     raeburn  3068:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3069:             $status = 'previous';
                   3070:         } 
                   3071:         if (($tstart) && ($now<$tstart)) {
                   3072:             $status = 'future';
                   3073:         }
                   3074:         if (ref($types) eq 'ARRAY') {
                   3075:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3076:                 next;
                   3077:             } 
                   3078:         } else {
                   3079:             if ($status ne 'active') {
                   3080:                 next;
                   3081:             }
                   3082:         }
1.867     raeburn  3083:         my ($rolecode,$username,$domain,$section,$area);
                   3084:         if ($context eq 'userroles') {
                   3085:             ($area,$rolecode) = split(/_/,$entry);
                   3086:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3087:         } else {
                   3088:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3089:         }
1.832     raeburn  3090:         if (ref($roledoms) eq 'ARRAY') {
                   3091:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3092:                 next;
                   3093:             }
                   3094:         }
                   3095:         if (ref($roles) eq 'ARRAY') {
                   3096:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3097:                 if ($role =~ /^cr\//) {
                   3098:                     if (!grep(/^cr$/,@{$roles})) {
                   3099:                         next;
                   3100:                     }
                   3101:                 } else {
                   3102:                     next;
                   3103:                 }
1.832     raeburn  3104:             }
1.867     raeburn  3105:         }
1.937     raeburn  3106:         if ($hidepriv) {
1.999     raeburn  3107:             if ($context eq 'userroles') {
                   3108:                 if ((&privileged($username,$domain)) &&
                   3109:                     (!$nothide{$username.':'.$domain})) {
                   3110:                     next;
                   3111:                 }
                   3112:             } else {
                   3113:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3114:                     my %dompersonnel =
                   3115:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3116:                     $privileged{$domain} = {};
                   3117:                     if (keys(%dompersonnel)) {
                   3118:                         foreach my $server (keys(%dompersonnel)) {
                   3119:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3120:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3121:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3122:                                     $privileged{$udom}{$uname} = $trole;
                   3123:                                 }
                   3124:                             }
                   3125:                         }
                   3126:                     }
                   3127:                 }
                   3128:                 if (exists($privileged{$domain}{$username})) {
                   3129:                     if (!$nothide{$username.':'.$domain}) {
                   3130:                         next;
                   3131:                     }
                   3132:                 }
1.937     raeburn  3133:             }
                   3134:         }
1.933     raeburn  3135:         if ($withsec) {
                   3136:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3137:                 $tstart.':'.$tend;
                   3138:         } else {
                   3139:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3140:         }
1.832     raeburn  3141:     }
1.373     www      3142:     return %returnhash;
1.399     www      3143: }
                   3144: 
                   3145: # ----------------------------------------------------- Frontpage Announcements
                   3146: #
                   3147: #
                   3148: 
                   3149: sub postannounce {
                   3150:     my ($server,$text)=@_;
1.844     albertel 3151:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3152:     unless ($text=~/\w/) { $text=''; }
                   3153:     return &reply('setannounce:'.&escape($text),$server);
                   3154: }
                   3155: 
                   3156: sub getannounce {
1.448     albertel 3157: 
                   3158:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3159: 	my $announcement='';
1.800     albertel 3160: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3161: 	close($fh);
1.399     www      3162: 	if ($announcement=~/\w/) { 
                   3163: 	    return 
                   3164:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3165:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3166: 	} else {
                   3167: 	    return '';
                   3168: 	}
                   3169:     } else {
                   3170: 	return '';
                   3171:     }
1.351     www      3172: }
1.353     www      3173: 
                   3174: # ---------------------------------------------------------- Course ID routines
                   3175: # Deal with domain's nohist_courseid.db files
                   3176: #
                   3177: 
                   3178: sub courseidput {
1.921     raeburn  3179:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3180:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3181:     my $outcome;
                   3182:     if ($caller eq 'timeonly') {
                   3183:         my $cids = '';
                   3184:         foreach my $item (keys(%$storehash)) {
                   3185:             $cids.=&escape($item).'&';
                   3186:         }
                   3187:         $cids=~s/\&$//;
                   3188:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3189:                           $coursehome);       
                   3190:     } else {
                   3191:         my $items = '';
                   3192:         foreach my $item (keys(%$storehash)) {
                   3193:             $items.= &escape($item).'='.
                   3194:                      &freeze_escape($$storehash{$item}).'&';
                   3195:         }
                   3196:         $items=~s/\&$//;
                   3197:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3198:                           $coursehome);
1.918     raeburn  3199:     }
                   3200:     if ($outcome eq 'unknown_cmd') {
                   3201:         my $what;
                   3202:         foreach my $cid (keys(%$storehash)) {
                   3203:             $what .= &escape($cid).'=';
1.921     raeburn  3204:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3205:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3206:             }
                   3207:             $what =~ s/\:$/&/;
                   3208:         }
                   3209:         $what =~ s/\&$//;  
                   3210:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3211:     } else {
                   3212:         return $outcome;
                   3213:     }
1.353     www      3214: }
                   3215: 
                   3216: sub courseiddump {
1.921     raeburn  3217:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3218:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3219:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3220:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3221:     my $as_hash = 1;
                   3222:     my %returnhash;
                   3223:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3224:     my %libserv = &all_library();
                   3225:     foreach my $tryserver (keys(%libserv)) {
                   3226:         if ( (  $hostidflag == 1 
                   3227: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3228: 	     || (!defined($hostidflag)) ) {
                   3229: 
1.918     raeburn  3230: 	    if (($domfilter eq '') ||
                   3231: 		(&host_domain($tryserver) eq $domfilter)) {
                   3232:                 my $rep = 
                   3233:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3234:                          $sincefilter.':'.&escape($descfilter).':'.
                   3235:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3236:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3237:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3238:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3239:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3240:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3241:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3242:                          &escape($creationcontext).':'.$domcloner,
                   3243:                          $tryserver);
1.918     raeburn  3244:                 my @pairs=split(/\&/,$rep);
                   3245:                 foreach my $item (@pairs) {
                   3246:                     my ($key,$value)=split(/\=/,$item,2);
                   3247:                     $key = &unescape($key);
                   3248:                     next if ($key =~ /^error: 2 /);
                   3249:                     my $result = &thaw_unescape($value);
                   3250:                     if (ref($result) eq 'HASH') {
                   3251:                         $returnhash{$key}=$result;
                   3252:                     } else {
1.921     raeburn  3253:                         my @responses = split(/:/,$value);
                   3254:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3255:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3256:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3257:                         }
1.1008    raeburn  3258:                     }
1.353     www      3259:                 }
                   3260:             }
                   3261:         }
                   3262:     }
                   3263:     return %returnhash;
                   3264: }
                   3265: 
1.1055    raeburn  3266: sub courselastaccess {
                   3267:     my ($cdom,$cnum,$hostidref) = @_;
                   3268:     my %returnhash;
                   3269:     if ($cdom && $cnum) {
                   3270:         my $chome = &homeserver($cnum,$cdom);
                   3271:         if ($chome ne 'no_host') {
                   3272:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3273:             &extract_lastaccess(\%returnhash,$rep);
                   3274:         }
                   3275:     } else {
                   3276:         if (!$cdom) { $cdom=''; }
                   3277:         my %libserv = &all_library();
                   3278:         foreach my $tryserver (keys(%libserv)) {
                   3279:             if (ref($hostidref) eq 'ARRAY') {
                   3280:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3281:             } 
                   3282:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3283:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3284:                 &extract_lastaccess(\%returnhash,$rep);
                   3285:             }
                   3286:         }
                   3287:     }
                   3288:     return %returnhash;
                   3289: }
                   3290: 
                   3291: sub extract_lastaccess {
                   3292:     my ($returnhash,$rep) = @_;
                   3293:     if (ref($returnhash) eq 'HASH') {
                   3294:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3295:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3296:                  $rep eq '') {
                   3297:             my @pairs=split(/\&/,$rep);
                   3298:             foreach my $item (@pairs) {
                   3299:                 my ($key,$value)=split(/\=/,$item,2);
                   3300:                 $key = &unescape($key);
                   3301:                 next if ($key =~ /^error: 2 /);
                   3302:                 $returnhash->{$key} = &thaw_unescape($value);
                   3303:             }
                   3304:         }
                   3305:     }
                   3306:     return;
                   3307: }
                   3308: 
1.658     raeburn  3309: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3310: 
                   3311: sub dcmailput {
1.685     raeburn  3312:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3313:     my $status = &Apache::lonnet::critical(
1.740     www      3314:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3315:        &escape($message),$server);
1.662     raeburn  3316:     return $status;
                   3317: }
                   3318: 
1.658     raeburn  3319: sub dcmaildump {
                   3320:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3321:     my %returnhash=();
1.846     albertel 3322: 
                   3323:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3324:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3325:                                                          &escape($enddate).':';
                   3326: 	my @esc_senders=map { &escape($_)} @$senders;
                   3327: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3328: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3329:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3330:             if (($key) && ($value)) {
                   3331:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3332:             }
                   3333:         }
                   3334:     }
                   3335:     return %returnhash;
                   3336: }
1.662     raeburn  3337: # ---------------------------------------------------------- Domain roles
                   3338: 
                   3339: sub get_domain_roles {
                   3340:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3341:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3342:         $startdate = '.';
                   3343:     }
1.1018    raeburn  3344:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3345:         $enddate = '.';
                   3346:     }
1.922     raeburn  3347:     my $rolelist;
                   3348:     if (ref($roles) eq 'ARRAY') {
                   3349:         $rolelist = join(':',@{$roles});
                   3350:     }
1.662     raeburn  3351:     my %personnel = ();
1.841     albertel 3352: 
                   3353:     my %servers = &get_servers($dom,'library');
                   3354:     foreach my $tryserver (keys(%servers)) {
                   3355: 	%{$personnel{$tryserver}}=();
                   3356: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3357: 					    &escape($startdate).':'.
                   3358: 					    &escape($enddate).':'.
                   3359: 					    &escape($rolelist), $tryserver))) {
                   3360: 	    my ($key,$value) = split(/\=/,$line,2);
                   3361: 	    if (($key) && ($value)) {
                   3362: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3363: 	    }
                   3364: 	}
1.662     raeburn  3365:     }
                   3366:     return %personnel;
                   3367: }
1.658     raeburn  3368: 
1.1057    www      3369: # ----------------------------------------------------------- Interval timing 
1.149     www      3370: 
1.504     albertel 3371: sub get_first_access {
                   3372:     my ($type,$argsymb)=@_;
1.790     albertel 3373:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3374:     if ($argsymb) { $symb=$argsymb; }
                   3375:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3376:     if ($type eq 'course') {
                   3377: 	$res='course';
                   3378:     } elsif ($type eq 'map') {
1.588     albertel 3379: 	$res=&symbread($map);
                   3380:     } else {
                   3381: 	$res=$symb;
                   3382:     }
                   3383:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3384:     return $times{"$courseid\0$res"};
1.504     albertel 3385: }
                   3386: 
                   3387: sub set_first_access {
                   3388:     my ($type)=@_;
1.790     albertel 3389:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3390:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3391:     if ($type eq 'course') {
                   3392: 	$res='course';
                   3393:     } elsif ($type eq 'map') {
1.588     albertel 3394: 	$res=&symbread($map);
                   3395:     } else {
                   3396: 	$res=$symb;
                   3397:     }
                   3398:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3399:     if (!$firstaccess) {
1.588     albertel 3400: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3401:     }
                   3402:     return 'already_set';
1.504     albertel 3403: }
                   3404: 
1.110     www      3405: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3406: 
                   3407: sub expirespread {
                   3408:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3409:     my $cid=$env{'request.course.id'}; 
1.110     www      3410:     if ($cid) {
                   3411:        my $now=time;
                   3412:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3413:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3414:                             $env{'course.'.$cid.'.num'}.
1.110     www      3415: 	        	    ':nohist_expirationdates:'.
                   3416:                             &escape($key).'='.$now,
1.620     albertel 3417:                             $env{'course.'.$cid.'.home'})
1.110     www      3418:     }
                   3419:     return 'ok';
1.14      www      3420: }
                   3421: 
1.109     www      3422: # ----------------------------------------------------- Devalidate Spreadsheets
                   3423: 
                   3424: sub devalidate {
1.325     www      3425:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3426:     my $cid=$env{'request.course.id'}; 
1.109     www      3427:     if ($cid) {
1.391     matthew  3428:         # delete the stored spreadsheets for
                   3429:         # - the student level sheet of this user in course's homespace
                   3430:         # - the assessment level sheet for this resource 
                   3431:         #   for this user in user's homespace
1.553     albertel 3432: 	# - current conditional state info
1.325     www      3433: 	my $key=$uname.':'.$udom.':';
1.109     www      3434:         my $status=
1.299     matthew  3435: 	    &del('nohist_calculatedsheets',
1.391     matthew  3436: 		 [$key.'studentcalc:'],
1.620     albertel 3437: 		 $env{'course.'.$cid.'.domain'},
                   3438: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3439: 		.' '.
                   3440: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3441: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3442:         unless ($status eq 'ok ok') {
                   3443:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3444:                     $uname.' at '.$udom.' for '.
1.109     www      3445: 		    $symb.': '.$status);
1.133     albertel 3446:         }
1.553     albertel 3447: 	&delenv('user.state.'.$cid);
1.109     www      3448:     }
                   3449: }
                   3450: 
1.265     albertel 3451: sub get_scalar {
                   3452:     my ($string,$end) = @_;
                   3453:     my $value;
                   3454:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3455: 	$value = $1;
                   3456:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3457: 	$value = $1;
                   3458:     }
                   3459:     return &unescape($value);
                   3460: }
                   3461: 
                   3462: sub array2str {
                   3463:   my (@array) = @_;
                   3464:   my $result=&arrayref2str(\@array);
                   3465:   $result=~s/^__ARRAY_REF__//;
                   3466:   $result=~s/__END_ARRAY_REF__$//;
                   3467:   return $result;
                   3468: }
                   3469: 
1.204     albertel 3470: sub arrayref2str {
                   3471:   my ($arrayref) = @_;
1.265     albertel 3472:   my $result='__ARRAY_REF__';
1.204     albertel 3473:   foreach my $elem (@$arrayref) {
1.265     albertel 3474:     if(ref($elem) eq 'ARRAY') {
                   3475:       $result.=&arrayref2str($elem).'&';
                   3476:     } elsif(ref($elem) eq 'HASH') {
                   3477:       $result.=&hashref2str($elem).'&';
                   3478:     } elsif(ref($elem)) {
                   3479:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3480:     } else {
                   3481:       $result.=&escape($elem).'&';
                   3482:     }
                   3483:   }
                   3484:   $result=~s/\&$//;
1.265     albertel 3485:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3486:   return $result;
                   3487: }
                   3488: 
1.168     albertel 3489: sub hash2str {
1.204     albertel 3490:   my (%hash) = @_;
                   3491:   my $result=&hashref2str(\%hash);
1.265     albertel 3492:   $result=~s/^__HASH_REF__//;
                   3493:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3494:   return $result;
                   3495: }
                   3496: 
                   3497: sub hashref2str {
                   3498:   my ($hashref)=@_;
1.265     albertel 3499:   my $result='__HASH_REF__';
1.800     albertel 3500:   foreach my $key (sort(keys(%$hashref))) {
                   3501:     if (ref($key) eq 'ARRAY') {
                   3502:       $result.=&arrayref2str($key).'=';
                   3503:     } elsif (ref($key) eq 'HASH') {
                   3504:       $result.=&hashref2str($key).'=';
                   3505:     } elsif (ref($key)) {
1.265     albertel 3506:       $result.='=';
1.800     albertel 3507:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3508:     } else {
1.800     albertel 3509: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3510:     }
                   3511: 
1.800     albertel 3512:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3513:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3514:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3515:       $result.=&hashref2str($hashref->{$key}).'&';
                   3516:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3517:        $result.='&';
1.800     albertel 3518:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3519:     } else {
1.800     albertel 3520:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3521:     }
                   3522:   }
1.168     albertel 3523:   $result=~s/\&$//;
1.265     albertel 3524:   $result .= '__END_HASH_REF__';
1.168     albertel 3525:   return $result;
                   3526: }
                   3527: 
                   3528: sub str2hash {
1.265     albertel 3529:     my ($string)=@_;
                   3530:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3531:     return %$hash;
                   3532: }
                   3533: 
                   3534: sub str2hashref {
1.168     albertel 3535:   my ($string) = @_;
1.265     albertel 3536: 
                   3537:   my %hash;
                   3538: 
                   3539:   if($string !~ /^__HASH_REF__/) {
                   3540:       if (! ($string eq '' || !defined($string))) {
                   3541: 	  $hash{'error'}='Not hash reference';
                   3542:       }
                   3543:       return (\%hash, $string);
                   3544:   }
                   3545: 
                   3546:   $string =~ s/^__HASH_REF__//;
                   3547: 
                   3548:   while($string !~ /^__END_HASH_REF__/) {
                   3549:       #key
                   3550:       my $key='';
                   3551:       if($string =~ /^__HASH_REF__/) {
                   3552:           ($key, $string)=&str2hashref($string);
                   3553:           if(defined($key->{'error'})) {
                   3554:               $hash{'error'}='Bad data';
                   3555:               return (\%hash, $string);
                   3556:           }
                   3557:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3558:           ($key, $string)=&str2arrayref($string);
                   3559:           if($key->[0] eq 'Array reference error') {
                   3560:               $hash{'error'}='Bad data';
                   3561:               return (\%hash, $string);
                   3562:           }
                   3563:       } else {
                   3564:           $string =~ s/^(.*?)=//;
1.267     albertel 3565: 	  $key=&unescape($1);
1.265     albertel 3566:       }
                   3567:       $string =~ s/^=//;
                   3568: 
                   3569:       #value
                   3570:       my $value='';
                   3571:       if($string =~ /^__HASH_REF__/) {
                   3572:           ($value, $string)=&str2hashref($string);
                   3573:           if(defined($value->{'error'})) {
                   3574:               $hash{'error'}='Bad data';
                   3575:               return (\%hash, $string);
                   3576:           }
                   3577:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3578:           ($value, $string)=&str2arrayref($string);
                   3579:           if($value->[0] eq 'Array reference error') {
                   3580:               $hash{'error'}='Bad data';
                   3581:               return (\%hash, $string);
                   3582:           }
                   3583:       } else {
                   3584: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3585:       }
                   3586:       $string =~ s/^&//;
                   3587: 
                   3588:       $hash{$key}=$value;
1.204     albertel 3589:   }
1.265     albertel 3590: 
                   3591:   $string =~ s/^__END_HASH_REF__//;
                   3592: 
                   3593:   return (\%hash, $string);
1.204     albertel 3594: }
                   3595: 
                   3596: sub str2array {
1.265     albertel 3597:     my ($string)=@_;
                   3598:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3599:     return @$array;
                   3600: }
                   3601: 
                   3602: sub str2arrayref {
1.204     albertel 3603:   my ($string) = @_;
1.265     albertel 3604:   my @array;
                   3605: 
                   3606:   if($string !~ /^__ARRAY_REF__/) {
                   3607:       if (! ($string eq '' || !defined($string))) {
                   3608: 	  $array[0]='Array reference error';
                   3609:       }
                   3610:       return (\@array, $string);
                   3611:   }
                   3612: 
                   3613:   $string =~ s/^__ARRAY_REF__//;
                   3614: 
                   3615:   while($string !~ /^__END_ARRAY_REF__/) {
                   3616:       my $value='';
                   3617:       if($string =~ /^__HASH_REF__/) {
                   3618:           ($value, $string)=&str2hashref($string);
                   3619:           if(defined($value->{'error'})) {
                   3620:               $array[0] ='Array reference error';
                   3621:               return (\@array, $string);
                   3622:           }
                   3623:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3624:           ($value, $string)=&str2arrayref($string);
                   3625:           if($value->[0] eq 'Array reference error') {
                   3626:               $array[0] ='Array reference error';
                   3627:               return (\@array, $string);
                   3628:           }
                   3629:       } else {
                   3630: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3631:       }
                   3632:       $string =~ s/^&//;
                   3633: 
                   3634:       push(@array, $value);
1.191     harris41 3635:   }
1.265     albertel 3636: 
                   3637:   $string =~ s/^__END_ARRAY_REF__//;
                   3638: 
                   3639:   return (\@array, $string);
1.168     albertel 3640: }
                   3641: 
1.167     albertel 3642: # -------------------------------------------------------------------Temp Store
                   3643: 
1.168     albertel 3644: sub tmpreset {
                   3645:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3646:   if (!$symb) {
                   3647:     $symb=&symbread();
1.620     albertel 3648:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3649:   }
                   3650:   $symb=escape($symb);
                   3651: 
1.620     albertel 3652:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3653:   $namespace=~s/\//\_/g;
                   3654:   $namespace=~s/\W//g;
                   3655: 
1.620     albertel 3656:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3657:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3658:   if ($domain eq 'public' && $stuname eq 'public') {
                   3659:       $stuname=$ENV{'REMOTE_ADDR'};
                   3660:   }
1.168     albertel 3661:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3662:   my %hash;
                   3663:   if (tie(%hash,'GDBM_File',
                   3664: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3665: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3666:     foreach my $key (keys(%hash)) {
1.180     albertel 3667:       if ($key=~ /:$symb/) {
1.168     albertel 3668: 	delete($hash{$key});
                   3669:       }
                   3670:     }
                   3671:   }
                   3672: }
                   3673: 
1.167     albertel 3674: sub tmpstore {
1.168     albertel 3675:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3676: 
                   3677:   if (!$symb) {
                   3678:     $symb=&symbread();
1.620     albertel 3679:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3680:   }
                   3681:   $symb=escape($symb);
                   3682: 
                   3683:   if (!$namespace) {
                   3684:     # I don't think we would ever want to store this for a course.
                   3685:     # it seems this will only be used if we don't have a course.
1.620     albertel 3686:     #$namespace=$env{'request.course.id'};
1.168     albertel 3687:     #if (!$namespace) {
1.620     albertel 3688:       $namespace=$env{'request.state'};
1.168     albertel 3689:     #}
                   3690:   }
                   3691:   $namespace=~s/\//\_/g;
                   3692:   $namespace=~s/\W//g;
1.620     albertel 3693:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3694:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3695:   if ($domain eq 'public' && $stuname eq 'public') {
                   3696:       $stuname=$ENV{'REMOTE_ADDR'};
                   3697:   }
1.168     albertel 3698:   my $now=time;
                   3699:   my %hash;
                   3700:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3701:   if (tie(%hash,'GDBM_File',
                   3702: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3703: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3704:     $hash{"version:$symb"}++;
                   3705:     my $version=$hash{"version:$symb"};
                   3706:     my $allkeys=''; 
                   3707:     foreach my $key (keys(%$storehash)) {
                   3708:       $allkeys.=$key.':';
1.591     albertel 3709:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3710:     }
                   3711:     $hash{"$version:$symb:timestamp"}=$now;
                   3712:     $allkeys.='timestamp';
                   3713:     $hash{"$version:keys:$symb"}=$allkeys;
                   3714:     if (untie(%hash)) {
                   3715:       return 'ok';
                   3716:     } else {
                   3717:       return "error:$!";
                   3718:     }
                   3719:   } else {
                   3720:     return "error:$!";
                   3721:   }
                   3722: }
1.167     albertel 3723: 
1.168     albertel 3724: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3725: 
1.168     albertel 3726: sub tmprestore {
                   3727:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3728: 
1.168     albertel 3729:   if (!$symb) {
                   3730:     $symb=&symbread();
1.620     albertel 3731:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3732:   }
                   3733:   $symb=escape($symb);
                   3734: 
1.620     albertel 3735:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3736: 
1.620     albertel 3737:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3738:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3739:   if ($domain eq 'public' && $stuname eq 'public') {
                   3740:       $stuname=$ENV{'REMOTE_ADDR'};
                   3741:   }
1.168     albertel 3742:   my %returnhash;
                   3743:   $namespace=~s/\//\_/g;
                   3744:   $namespace=~s/\W//g;
                   3745:   my %hash;
                   3746:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3747:   if (tie(%hash,'GDBM_File',
                   3748: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3749: 	  &GDBM_READER(),0640)) {
1.168     albertel 3750:     my $version=$hash{"version:$symb"};
                   3751:     $returnhash{'version'}=$version;
                   3752:     my $scope;
                   3753:     for ($scope=1;$scope<=$version;$scope++) {
                   3754:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3755:       my @keys=split(/:/,$vkeys);
                   3756:       my $key;
                   3757:       $returnhash{"$scope:keys"}=$vkeys;
                   3758:       foreach $key (@keys) {
1.591     albertel 3759: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3760: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3761:       }
                   3762:     }
1.168     albertel 3763:     if (!(untie(%hash))) {
                   3764:       return "error:$!";
                   3765:     }
                   3766:   } else {
                   3767:     return "error:$!";
                   3768:   }
                   3769:   return %returnhash;
1.167     albertel 3770: }
                   3771: 
1.9       www      3772: # ----------------------------------------------------------------------- Store
                   3773: 
                   3774: sub store {
1.124     www      3775:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3776:     my $home='';
                   3777: 
1.168     albertel 3778:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3779: 
1.213     www      3780:     $symb=&symbclean($symb);
1.122     albertel 3781:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3782: 
1.620     albertel 3783:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3784:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3785: 
                   3786:     &devalidate($symb,$stuname,$domain);
1.109     www      3787: 
                   3788:     $symb=escape($symb);
1.187     www      3789:     if (!$namespace) { 
1.620     albertel 3790:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3791:           return ''; 
                   3792:        } 
                   3793:     }
1.620     albertel 3794:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3795: 
                   3796:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3797:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3798: 
1.12      www      3799:     my $namevalue='';
1.800     albertel 3800:     foreach my $key (keys(%$storehash)) {
                   3801:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3802:     }
1.12      www      3803:     $namevalue=~s/\&$//;
1.187     www      3804:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3805:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3806: }
                   3807: 
1.47      www      3808: # -------------------------------------------------------------- Critical Store
                   3809: 
                   3810: sub cstore {
1.124     www      3811:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3812:     my $home='';
                   3813: 
1.168     albertel 3814:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3815: 
1.213     www      3816:     $symb=&symbclean($symb);
1.122     albertel 3817:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3818: 
1.620     albertel 3819:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3820:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3821: 
                   3822:     &devalidate($symb,$stuname,$domain);
1.109     www      3823: 
                   3824:     $symb=escape($symb);
1.187     www      3825:     if (!$namespace) { 
1.620     albertel 3826:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3827:           return ''; 
                   3828:        } 
                   3829:     }
1.620     albertel 3830:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3831: 
                   3832:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3833:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3834: 
1.47      www      3835:     my $namevalue='';
1.800     albertel 3836:     foreach my $key (keys(%$storehash)) {
                   3837:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3838:     }
1.47      www      3839:     $namevalue=~s/\&$//;
1.187     www      3840:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3841:     return critical
                   3842:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3843: }
                   3844: 
1.9       www      3845: # --------------------------------------------------------------------- Restore
                   3846: 
                   3847: sub restore {
1.124     www      3848:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3849:     my $home='';
                   3850: 
1.168     albertel 3851:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3852: 
1.122     albertel 3853:     if (!$symb) {
                   3854:       unless ($symb=escape(&symbread())) { return ''; }
                   3855:     } else {
1.213     www      3856:       $symb=&escape(&symbclean($symb));
1.122     albertel 3857:     }
1.188     www      3858:     if (!$namespace) { 
1.620     albertel 3859:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3860:           return ''; 
                   3861:        } 
                   3862:     }
1.620     albertel 3863:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3864:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3865:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3866:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3867: 
1.12      www      3868:     my %returnhash=();
1.800     albertel 3869:     foreach my $line (split(/\&/,$answer)) {
                   3870: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3871:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3872:     }
1.75      www      3873:     my $version;
                   3874:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3875:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3876:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3877:        }
1.75      www      3878:     }
1.13      www      3879:     return %returnhash;
1.34      www      3880: }
                   3881: 
                   3882: # ---------------------------------------------------------- Course Description
                   3883: 
                   3884: sub coursedescription {
1.731     albertel 3885:     my ($courseid,$args)=@_;
1.34      www      3886:     $courseid=~s/^\///;
1.49      www      3887:     $courseid=~s/\_/\//g;
1.34      www      3888:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3889:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3890:     my $normalid=$cdomain.'_'.$cnum;
                   3891:     # need to always cache even if we get errors otherwise we keep 
                   3892:     # trying and trying and trying to get the course description.
                   3893:     my %envhash=();
                   3894:     my %returnhash=();
1.731     albertel 3895:     
                   3896:     my $expiretime=600;
                   3897:     if ($env{'request.course.id'} eq $normalid) {
                   3898: 	$expiretime=120;
                   3899:     }
                   3900: 
                   3901:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3902:     if (!$args->{'freshen_cache'}
                   3903: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3904: 	foreach my $key (keys(%env)) {
                   3905: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3906: 	    my ($setting) = $1;
                   3907: 	    $returnhash{$setting} = $env{$key};
                   3908: 	}
                   3909: 	return %returnhash;
                   3910:     }
                   3911: 
                   3912:     # get the data agin
                   3913:     if (!$args->{'one_time'}) {
                   3914: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3915:     }
1.811     albertel 3916: 
1.34      www      3917:     if ($chome ne 'no_host') {
1.302     albertel 3918:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3919:        if (!exists($returnhash{'con_lost'})) {
                   3920:            $returnhash{'home'}= $chome;
                   3921: 	   $returnhash{'domain'} = $cdomain;
                   3922: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3923:            if (!defined($returnhash{'type'})) {
                   3924:                $returnhash{'type'} = 'Course';
                   3925:            }
1.130     albertel 3926:            while (my ($name,$value) = each %returnhash) {
1.53      www      3927:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3928:            }
1.270     www      3929:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3930:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3931: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3932:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3933:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3934:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3935:        }
                   3936:     }
1.731     albertel 3937:     if (!$args->{'one_time'}) {
1.949     raeburn  3938: 	&appenv(\%envhash);
1.731     albertel 3939:     }
1.302     albertel 3940:     return %returnhash;
1.461     www      3941: }
                   3942: 
1.1080    raeburn  3943: sub update_released_required {
                   3944:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   3945:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   3946:         $cid = $env{'request.course.id'};
                   3947:         $cdom = $env{'course.'.$cid.'.domain'};
                   3948:         $cnum = $env{'course.'.$cid.'.num'};
                   3949:         $chome = $env{'course.'.$cid.'.home'};
                   3950:     }
                   3951:     if ($needsrelease) {
                   3952:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   3953:         my $needsupdate;
                   3954:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   3955:             $needsupdate = 1;
                   3956:         } else {
                   3957:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   3958:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   3959:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   3960:                 $needsupdate = 1;
                   3961:             }
                   3962:         }
                   3963:         if ($needsupdate) {
                   3964:             my %needshash = (
                   3965:                              'internal.releaserequired' => $needsrelease,
                   3966:                             );
                   3967:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   3968:             if ($putresult eq 'ok') {
                   3969:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   3970:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   3971:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   3972:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   3973:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   3974:                 }
                   3975:             }
                   3976:         }
                   3977:     }
                   3978:     return;
                   3979: }
                   3980: 
1.461     www      3981: # -------------------------------------------------See if a user is privileged
                   3982: 
                   3983: sub privileged {
                   3984:     my ($username,$domain)=@_;
                   3985:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3986: 			&homeserver($username,$domain));
1.1033    raeburn  3987:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3988:         ($rolesdump =~ /^error:/)) {
                   3989:         return 0;
                   3990:     }
1.461     www      3991:     my $now=time;
                   3992:     if ($rolesdump ne '') {
1.800     albertel 3993:         foreach my $entry (split(/&/,$rolesdump)) {
                   3994: 	    if ($entry!~/^rolesdef_/) {
                   3995: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3996: 		$area=~s/\_\w\w$//;
                   3997: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3998: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3999: 		    my $active=1;
                   4000: 		    if ($tend) {
                   4001: 			if ($tend<$now) { $active=0; }
                   4002: 		    }
                   4003: 		    if ($tstart) {
                   4004: 			if ($tstart>$now) { $active=0; }
                   4005: 		    }
                   4006: 		    if ($active) { return 1; }
                   4007: 		}
                   4008: 	    }
                   4009: 	}
                   4010:     }
                   4011:     return 0;
1.9       www      4012: }
1.1       albertel 4013: 
1.103     harris41 4014: # -------------------------------------------------------- Get user privileges
1.11      www      4015: 
                   4016: sub rolesinit {
                   4017:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4018:     my $now=time;
                   4019:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4020:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4021:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4022:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4023:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4024:         return \%userroles;
                   4025:     }
1.11      www      4026:     my %allroles=();
1.678     raeburn  4027:     my %allgroups=();   
                   4028:     my $group_privs;
1.11      www      4029: 
                   4030:     if ($rolesdump ne '') {
1.800     albertel 4031:         foreach my $entry (split(/&/,$rolesdump)) {
                   4032: 	  if ($entry!~/^rolesdef_/) {
                   4033:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4034: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4035:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4036: 	    if ($role=~/^cr/) { 
1.807     albertel 4037: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4038: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4039: 		    ($tend,$tstart)=split('_',$trest);
                   4040: 		} else {
                   4041: 		    $trole=$role;
                   4042: 		}
1.678     raeburn  4043:             } elsif ($role =~ m|^gr/|) {
                   4044:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4045:                 ($trole,$group_privs) = split(/\//,$trole);
                   4046:                 $group_privs = &unescape($group_privs);
1.587     albertel 4047: 	    } else {
                   4048: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4049: 	    }
1.743     albertel 4050: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4051: 					 $username);
                   4052: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4053:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4054:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4055:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4056: 		my $spec=$trole.'.'.$area;
                   4057: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4058: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4059:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4060:                 } elsif ($trole eq 'gr') {
                   4061:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4062: 		} else {
1.567     raeburn  4063:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4064: 		}
1.12      www      4065:             }
1.662     raeburn  4066:           }
1.191     harris41 4067:         }
1.743     albertel 4068:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4069:         $userroles{'user.adv'}    = $adv;
                   4070: 	$userroles{'user.author'} = $author;
1.620     albertel 4071:         $env{'user.adv'}=$adv;
1.11      www      4072:     }
1.743     albertel 4073:     return \%userroles;  
1.11      www      4074: }
                   4075: 
1.567     raeburn  4076: sub set_arearole {
                   4077:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4078: # log the associated role with the area
                   4079:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4080:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4081: }
                   4082: 
                   4083: sub custom_roleprivs {
                   4084:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4085:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4086:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4087:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4088:         my ($rdummy,$roledef)=
                   4089:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4090:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4091:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4092:             if (defined($syspriv)) {
1.1043    raeburn  4093:                 if ($trest =~ /^$match_community$/) {
                   4094:                     $syspriv =~ s/bre\&S//; 
                   4095:                 }
1.567     raeburn  4096:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4097:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4098:             }
                   4099:             if ($tdomain ne '') {
                   4100:                 if (defined($dompriv)) {
                   4101:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4102:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4103:                 }
                   4104:                 if (($trest ne '') && (defined($coursepriv))) {
                   4105:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4106:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4107:                 }
                   4108:             }
                   4109:         }
                   4110:     }
                   4111: }
                   4112: 
1.678     raeburn  4113: sub group_roleprivs {
                   4114:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4115:     my $access = 1;
                   4116:     my $now = time;
                   4117:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4118:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4119:     if ($access) {
1.811     albertel 4120:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4121:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4122:     }
                   4123: }
1.567     raeburn  4124: 
                   4125: sub standard_roleprivs {
                   4126:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4127:     if (defined($pr{$trole.':s'})) {
                   4128:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4129:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4130:     }
                   4131:     if ($tdomain ne '') {
                   4132:         if (defined($pr{$trole.':d'})) {
                   4133:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4134:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4135:         }
                   4136:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4137:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4138:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4139:         }
                   4140:     }
                   4141: }
                   4142: 
                   4143: sub set_userprivs {
1.1064    raeburn  4144:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4145:     my $author=0;
                   4146:     my $adv=0;
1.678     raeburn  4147:     my %grouproles = ();
                   4148:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4149:         my @groupkeys; 
1.1000    raeburn  4150:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4151:             push(@groupkeys,$role);
                   4152:         }
                   4153:         if (ref($groups_roles) eq 'HASH') {
                   4154:             foreach my $key (keys(%{$groups_roles})) {
                   4155:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4156:                     push(@groupkeys,$key);
                   4157:                 }
                   4158:             }
                   4159:         }
                   4160:         if (@groupkeys > 0) {
                   4161:             foreach my $role (@groupkeys) {
                   4162:                 my ($trole,$area,$sec,$extendedarea);
                   4163:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4164:                     $trole = $1;
                   4165:                     $area = $2;
                   4166:                     $sec = $3;
                   4167:                     $extendedarea = $area.$sec;
                   4168:                     if (exists($$allgroups{$area})) {
                   4169:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4170:                             my $spec = $trole.'.'.$extendedarea;
                   4171:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4172:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4173:                         }
1.678     raeburn  4174:                     }
                   4175:                 }
                   4176:             }
                   4177:         }
                   4178:     }
1.800     albertel 4179:     foreach my $group (keys(%grouproles)) {
                   4180:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4181:     }
1.800     albertel 4182:     foreach my $role (keys(%{$allroles})) {
                   4183:         my %thesepriv;
1.941     raeburn  4184:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4185:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4186:             if ($item ne '') {
                   4187:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4188:                 if ($restrictions eq '') {
                   4189:                     $thesepriv{$privilege}='F';
                   4190:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4191:                     $thesepriv{$privilege}.=$restrictions;
                   4192:                 }
                   4193:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4194:             }
                   4195:         }
                   4196:         my $thesestr='';
1.800     albertel 4197:         foreach my $priv (keys(%thesepriv)) {
                   4198: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4199: 	}
                   4200:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4201:     }
                   4202:     return ($author,$adv);
                   4203: }
                   4204: 
1.994     raeburn  4205: sub role_status {
1.1002    raeburn  4206:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4207:     my @pwhere = ();
                   4208:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4209:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4210:         unless (!defined($$role) || $$role eq '') {
                   4211:             $$where=join('.',@pwhere);
                   4212:             $$trolecode=$$role.'.'.$$where;
                   4213:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4214:             $$tstatus='is';
                   4215:             if ($$tstart && $$tstart>$then) {
                   4216:                 $$tstatus='future';
1.1034    raeburn  4217:                 if ($$tstart<$now) {
                   4218:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4219:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4220:                             my (%allroles,%allgroups,$group_privs,
                   4221:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4222:                             my %userroles = (
                   4223:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4224:                             );
1.1064    raeburn  4225:                             @rolecodes = ('cm'); 
1.1002    raeburn  4226:                             my $spec=$$role.'.'.$$where;
                   4227:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4228:                             if ($$role =~ /^cr\//) {
                   4229:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4230:                                 push(@rolecodes,'cr');
1.1002    raeburn  4231:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4232:                                 push(@rolecodes,$$role);
1.1002    raeburn  4233:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4234:                                                     $env{'user.name'});
1.1064    raeburn  4235:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4236:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4237:                                 $group_privs = &unescape($group_privs);
                   4238:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4239:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4240:                                 if (keys(%course_roles) > 0) {
                   4241:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4242:                                     if ($tdomain ne '' && $tnum ne '') { 
                   4243:                                         foreach my $key (keys(%course_roles)) {
                   4244:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4245:                                                 my $crsrole = $1;
                   4246:                                                 my $crssec = $2;
                   4247:                                                 if ($crsrole =~ /^cr/) {
                   4248:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4249:                                                         push(@rolecodes,'cr');
                   4250:                                                     }
                   4251:                                                 } else {
                   4252:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4253:                                                         push(@rolecodes,$crsrole);
                   4254:                                                     }
                   4255:                                                 }
                   4256:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4257:                                                 if ($crssec ne '') {
                   4258:                                                     $rolekey .= '/'.$crssec;
                   4259:                                                 }
                   4260:                                                 $rolekey .= './';
                   4261:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4262:                                             }
                   4263:                                         }
                   4264:                                     }
                   4265:                                 }
1.1002    raeburn  4266:                             } else {
1.1064    raeburn  4267:                                 push(@rolecodes,$$role);
1.1002    raeburn  4268:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4269:                             }
1.1064    raeburn  4270:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4271:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4272:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4273:                         }
                   4274:                     }
1.1034    raeburn  4275:                     $$tstatus = 'is';
1.1002    raeburn  4276:                 }
1.994     raeburn  4277:             }
                   4278:             if ($$tend) {
                   4279:                 if ($$tend<$then) {
                   4280:                     $$tstatus='expired';
                   4281:                 } elsif ($$tend<$now) {
                   4282:                     $$tstatus='will_not';
                   4283:                 }
                   4284:             }
                   4285:         }
                   4286:     }
                   4287: }
                   4288: 
                   4289: sub check_adhoc_privs {
1.1088  ! raeburn  4290:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4291:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4292:     if ($env{$cckey}) {
                   4293:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4294:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4295:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088  ! raeburn  4296:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4297:         }
                   4298:     } else {
1.1088  ! raeburn  4299:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4300:     }
                   4301: }
                   4302: 
                   4303: sub set_adhoc_privileges {
                   4304: # role can be cc or ca
1.1088  ! raeburn  4305:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4306:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4307:     my $spec = $role.'.'.$area;
                   4308:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4309:                                   $env{'user.name'});
                   4310:     my %ccrole = ();
                   4311:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4312:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4313:     &appenv(\%userroles,[$role,'cm']);
                   4314:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088  ! raeburn  4315:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
        !          4316:         &appenv( {'request.role'        => $spec,
        !          4317:                   'request.role.domain' => $dcdom,
        !          4318:                   'request.course.sec'  => ''
        !          4319:                  }
        !          4320:                );
        !          4321:         my $tadv=0;
        !          4322:         if (&allowed('adv') eq 'F') { $tadv=1; }
        !          4323:         &appenv({'request.role.adv'    => $tadv});
        !          4324:     }
1.994     raeburn  4325: }
                   4326: 
1.12      www      4327: # --------------------------------------------------------------- get interface
                   4328: 
                   4329: sub get {
1.131     albertel 4330:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4331:    my $items='';
1.800     albertel 4332:    foreach my $item (@$storearr) {
                   4333:        $items.=&escape($item).'&';
1.191     harris41 4334:    }
1.12      www      4335:    $items=~s/\&$//;
1.620     albertel 4336:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4337:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4338:    my $uhome=&homeserver($uname,$udomain);
                   4339: 
1.133     albertel 4340:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4341:    my @pairs=split(/\&/,$rep);
1.273     albertel 4342:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4343:      return @pairs;
                   4344:    }
1.15      www      4345:    my %returnhash=();
1.42      www      4346:    my $i=0;
1.800     albertel 4347:    foreach my $item (@$storearr) {
                   4348:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4349:       $i++;
1.191     harris41 4350:    }
1.15      www      4351:    return %returnhash;
1.27      www      4352: }
                   4353: 
                   4354: # --------------------------------------------------------------- del interface
                   4355: 
                   4356: sub del {
1.133     albertel 4357:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4358:    my $items='';
1.800     albertel 4359:    foreach my $item (@$storearr) {
                   4360:        $items.=&escape($item).'&';
1.191     harris41 4361:    }
1.984     neumanie 4362: 
1.27      www      4363:    $items=~s/\&$//;
1.620     albertel 4364:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4365:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4366:    my $uhome=&homeserver($uname,$udomain);
                   4367:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4368: }
                   4369: 
                   4370: # -------------------------------------------------------------- dump interface
                   4371: 
                   4372: sub dump {
1.1086    raeburn  4373:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4374:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4375:     if (!$uname) { $uname=$env{'user.name'}; }
                   4376:     my $uhome=&homeserver($uname,$udomain);
                   4377:     if ($regexp) {
                   4378: 	$regexp=&escape($regexp);
                   4379:     } else {
                   4380: 	$regexp='.';
                   4381:     }
1.1086    raeburn  4382:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4383:     my @pairs=split(/\&/,$rep);
                   4384:     my %returnhash=();
                   4385:     foreach my $item (@pairs) {
                   4386: 	my ($key,$value)=split(/=/,$item,2);
                   4387: 	$key = &unescape($key);
                   4388: 	next if ($key =~ /^error: 2 /);
                   4389: 	$returnhash{$key}=&thaw_unescape($value);
                   4390:     }
                   4391:     return %returnhash;
1.407     www      4392: }
                   4393: 
1.717     albertel 4394: # --------------------------------------------------------- dumpstore interface
                   4395: 
                   4396: sub dumpstore {
                   4397:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4398:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4399:    if (!$uname) { $uname=$env{'user.name'}; }
                   4400:    my $uhome=&homeserver($uname,$udomain);
                   4401:    if ($regexp) {
                   4402:        $regexp=&escape($regexp);
                   4403:    } else {
                   4404:        $regexp='.';
                   4405:    }
                   4406:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4407:    my @pairs=split(/\&/,$rep);
                   4408:    my %returnhash=();
                   4409:    foreach my $item (@pairs) {
                   4410:        my ($key,$value)=split(/=/,$item,2);
                   4411:        next if ($key =~ /^error: 2 /);
                   4412:        $returnhash{$key}=&thaw_unescape($value);
                   4413:    }
                   4414:    return %returnhash;
1.717     albertel 4415: }
                   4416: 
1.407     www      4417: # -------------------------------------------------------------- keys interface
                   4418: 
                   4419: sub getkeys {
                   4420:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4421:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4422:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4423:    my $uhome=&homeserver($uname,$udomain);
                   4424:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4425:    my @keyarray=();
1.800     albertel 4426:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4427:       next if ($key =~ /^error: 2 /);
1.800     albertel 4428:       push(@keyarray,&unescape($key));
1.407     www      4429:    }
                   4430:    return @keyarray;
1.318     matthew  4431: }
                   4432: 
1.319     matthew  4433: # --------------------------------------------------------------- currentdump
                   4434: sub currentdump {
1.328     matthew  4435:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4436:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4437:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4438:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4439:    my $uhome = &homeserver($sname,$sdom);
                   4440:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4441:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4442:    #
1.318     matthew  4443:    my %returnhash=();
1.319     matthew  4444:    #
                   4445:    if ($rep eq "unknown_cmd") { 
                   4446:        # an old lond will not know currentdump
                   4447:        # Do a dump and make it look like a currentdump
1.822     albertel 4448:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4449:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4450:        my %hash = @tmp;
                   4451:        @tmp=();
1.424     matthew  4452:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4453:    } else {
                   4454:        my @pairs=split(/\&/,$rep);
1.800     albertel 4455:        foreach my $pair (@pairs) {
                   4456:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4457:            my ($symb,$param) = split(/:/,$key);
                   4458:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4459:                                                         &thaw_unescape($value);
1.319     matthew  4460:        }
1.191     harris41 4461:    }
1.12      www      4462:    return %returnhash;
1.424     matthew  4463: }
                   4464: 
                   4465: sub convert_dump_to_currentdump{
                   4466:     my %hash = %{shift()};
                   4467:     my %returnhash;
                   4468:     # Code ripped from lond, essentially.  The only difference
                   4469:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4470:     # we might run in to problems with parameter names =~ /^v\./
                   4471:     while (my ($key,$value) = each(%hash)) {
                   4472:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4473: 	$symb  = &unescape($symb);
                   4474: 	$param = &unescape($param);
1.424     matthew  4475:         next if ($v eq 'version' || $symb eq 'keys');
                   4476:         next if (exists($returnhash{$symb}) &&
                   4477:                  exists($returnhash{$symb}->{$param}) &&
                   4478:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4479:         $returnhash{$symb}->{$param}=$value;
                   4480:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4481:     }
                   4482:     #
                   4483:     # Remove all of the keys in the hashes which keep track of
                   4484:     # the version of the parameter.
                   4485:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4486:         # use a foreach because we are going to delete from the hash.
                   4487:         foreach my $key (keys(%$param_hash)) {
                   4488:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4489:         }
                   4490:     }
                   4491:     return \%returnhash;
1.12      www      4492: }
                   4493: 
1.627     albertel 4494: # ------------------------------------------------------ critical inc interface
                   4495: 
                   4496: sub cinc {
                   4497:     return &inc(@_,'critical');
                   4498: }
                   4499: 
1.449     matthew  4500: # --------------------------------------------------------------- inc interface
                   4501: 
                   4502: sub inc {
1.627     albertel 4503:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4504:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4505:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4506:     my $uhome=&homeserver($uname,$udomain);
                   4507:     my $items='';
                   4508:     if (! ref($store)) {
                   4509:         # got a single value, so use that instead
                   4510:         $items = &escape($store).'=&';
                   4511:     } elsif (ref($store) eq 'SCALAR') {
                   4512:         $items = &escape($$store).'=&';        
                   4513:     } elsif (ref($store) eq 'ARRAY') {
                   4514:         $items = join('=&',map {&escape($_);} @{$store});
                   4515:     } elsif (ref($store) eq 'HASH') {
                   4516:         while (my($key,$value) = each(%{$store})) {
                   4517:             $items.= &escape($key).'='.&escape($value).'&';
                   4518:         }
                   4519:     }
                   4520:     $items=~s/\&$//;
1.627     albertel 4521:     if ($critical) {
                   4522: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4523:     } else {
                   4524: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4525:     }
1.449     matthew  4526: }
                   4527: 
1.12      www      4528: # --------------------------------------------------------------- put interface
                   4529: 
                   4530: sub put {
1.134     albertel 4531:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4532:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4533:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4534:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4535:    my $items='';
1.800     albertel 4536:    foreach my $item (keys(%$storehash)) {
                   4537:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4538:    }
1.12      www      4539:    $items=~s/\&$//;
1.134     albertel 4540:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4541: }
                   4542: 
1.631     albertel 4543: # ------------------------------------------------------------ newput interface
                   4544: 
                   4545: sub newput {
                   4546:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4547:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4548:    if (!$uname) { $uname=$env{'user.name'}; }
                   4549:    my $uhome=&homeserver($uname,$udomain);
                   4550:    my $items='';
                   4551:    foreach my $key (keys(%$storehash)) {
                   4552:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4553:    }
                   4554:    $items=~s/\&$//;
                   4555:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4556: }
                   4557: 
                   4558: # ---------------------------------------------------------  putstore interface
                   4559: 
1.524     raeburn  4560: sub putstore {
1.715     albertel 4561:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4562:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4563:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4564:    my $uhome=&homeserver($uname,$udomain);
                   4565:    my $items='';
1.715     albertel 4566:    foreach my $key (keys(%$storehash)) {
                   4567:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4568:    }
1.715     albertel 4569:    $items=~s/\&$//;
1.716     albertel 4570:    my $esc_symb=&escape($symb);
                   4571:    my $esc_v=&escape($version);
1.715     albertel 4572:    my $reply =
1.716     albertel 4573:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4574: 	      $uhome);
                   4575:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4576:        # gfall back to way things use to be done
1.715     albertel 4577:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4578: 			    $uname);
1.524     raeburn  4579:    }
1.715     albertel 4580:    return $reply;
                   4581: }
                   4582: 
                   4583: sub old_putstore {
1.716     albertel 4584:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4585:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4586:     if (!$uname) { $uname=$env{'user.name'}; }
                   4587:     my $uhome=&homeserver($uname,$udomain);
                   4588:     my %newstorehash;
1.800     albertel 4589:     foreach my $item (keys(%$storehash)) {
                   4590: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4591: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4592:     }
                   4593:     my $items='';
                   4594:     my %allitems = ();
1.800     albertel 4595:     foreach my $item (keys(%newstorehash)) {
                   4596: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4597: 	    my $key = $1.':keys:'.$2;
                   4598: 	    $allitems{$key} .= $3.':';
                   4599: 	}
1.800     albertel 4600: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4601:     }
1.800     albertel 4602:     foreach my $item (keys(%allitems)) {
                   4603: 	$allitems{$item} =~ s/\:$//;
                   4604: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4605:     }
                   4606:     $items=~s/\&$//;
                   4607:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4608: }
                   4609: 
1.47      www      4610: # ------------------------------------------------------ critical put interface
                   4611: 
                   4612: sub cput {
1.134     albertel 4613:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4614:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4615:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4616:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4617:    my $items='';
1.800     albertel 4618:    foreach my $item (keys(%$storehash)) {
                   4619:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4620:    }
1.47      www      4621:    $items=~s/\&$//;
1.134     albertel 4622:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4623: }
                   4624: 
                   4625: # -------------------------------------------------------------- eget interface
                   4626: 
                   4627: sub eget {
1.133     albertel 4628:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4629:    my $items='';
1.800     albertel 4630:    foreach my $item (@$storearr) {
                   4631:        $items.=&escape($item).'&';
1.191     harris41 4632:    }
1.12      www      4633:    $items=~s/\&$//;
1.620     albertel 4634:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4635:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4636:    my $uhome=&homeserver($uname,$udomain);
                   4637:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4638:    my @pairs=split(/\&/,$rep);
                   4639:    my %returnhash=();
1.42      www      4640:    my $i=0;
1.800     albertel 4641:    foreach my $item (@$storearr) {
                   4642:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4643:       $i++;
1.191     harris41 4644:    }
1.12      www      4645:    return %returnhash;
                   4646: }
                   4647: 
1.667     albertel 4648: # ------------------------------------------------------------ tmpput interface
                   4649: sub tmpput {
1.802     raeburn  4650:     my ($storehash,$server,$context)=@_;
1.667     albertel 4651:     my $items='';
1.800     albertel 4652:     foreach my $item (keys(%$storehash)) {
                   4653: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4654:     }
                   4655:     $items=~s/\&$//;
1.802     raeburn  4656:     if (defined($context)) {
                   4657:         $items .= ':'.&escape($context);
                   4658:     }
1.667     albertel 4659:     return &reply("tmpput:$items",$server);
                   4660: }
                   4661: 
                   4662: # ------------------------------------------------------------ tmpget interface
                   4663: sub tmpget {
1.688     albertel 4664:     my ($token,$server)=@_;
                   4665:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4666:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4667:     my %returnhash;
                   4668:     foreach my $item (split(/\&/,$rep)) {
                   4669: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4670:         next if ($key =~ /^error: 2 /);
1.667     albertel 4671: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4672:     }
                   4673:     return %returnhash;
                   4674: }
                   4675: 
1.688     albertel 4676: # ------------------------------------------------------------ tmpget interface
                   4677: sub tmpdel {
                   4678:     my ($token,$server)=@_;
                   4679:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4680:     return &reply("tmpdel:$token",$server);
                   4681: }
                   4682: 
1.765     albertel 4683: # -------------------------------------------------- portfolio access checking
                   4684: 
                   4685: sub portfolio_access {
1.766     albertel 4686:     my ($requrl) = @_;
1.765     albertel 4687:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4688:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4689:     if ($result) {
                   4690:         my %setters;
                   4691:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4692:             my ($startblock,$endblock) =
                   4693:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4694:             if ($startblock && $endblock) {
                   4695:                 return 'B';
                   4696:             }
                   4697:         } else {
                   4698:             my ($startblock,$endblock) =
                   4699:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4700:             if ($startblock && $endblock) {
                   4701:                 return 'B';
                   4702:             }
                   4703:         }
                   4704:     }
1.765     albertel 4705:     if ($result eq 'ok') {
1.766     albertel 4706:        return 'F';
1.765     albertel 4707:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4708:        return 'A';
1.765     albertel 4709:     }
1.766     albertel 4710:     return '';
1.765     albertel 4711: }
                   4712: 
                   4713: sub get_portfolio_access {
1.767     albertel 4714:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4715: 
                   4716:     if (!ref($access_hash)) {
                   4717: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4718: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4719: 						   $file_name);
                   4720: 	$access_hash = $access_controls{$file_name};
                   4721:     }
                   4722: 
1.765     albertel 4723:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4724:     my $now = time;
                   4725:     if (ref($access_hash) eq 'HASH') {
                   4726:         foreach my $key (keys(%{$access_hash})) {
                   4727:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4728:             if ($start > $now) {
                   4729:                 next;
                   4730:             }
                   4731:             if ($end && $end<$now) {
                   4732:                 next;
                   4733:             }
                   4734:             if ($scope eq 'public') {
                   4735:                 $public = $key;
                   4736:                 last;
                   4737:             } elsif ($scope eq 'guest') {
                   4738:                 $guest = $key;
                   4739:             } elsif ($scope eq 'domains') {
                   4740:                 push(@domains,$key);
                   4741:             } elsif ($scope eq 'users') {
                   4742:                 push(@users,$key);
                   4743:             } elsif ($scope eq 'course') {
                   4744:                 push(@courses,$key);
                   4745:             } elsif ($scope eq 'group') {
                   4746:                 push(@groups,$key);
                   4747:             }
                   4748:         }
                   4749:         if ($public) {
                   4750:             return 'ok';
                   4751:         }
                   4752:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4753:             if ($guest) {
                   4754:                 return $guest;
                   4755:             }
                   4756:         } else {
                   4757:             if (@domains > 0) {
                   4758:                 foreach my $domkey (@domains) {
                   4759:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4760:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4761:                             return 'ok';
                   4762:                         }
                   4763:                     }
                   4764:                 }
                   4765:             }
                   4766:             if (@users > 0) {
                   4767:                 foreach my $userkey (@users) {
1.865     raeburn  4768:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4769:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4770:                             if (ref($item) eq 'HASH') {
                   4771:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4772:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4773:                                     return 'ok';
                   4774:                                 }
                   4775:                             }
                   4776:                         }
                   4777:                     } 
1.765     albertel 4778:                 }
                   4779:             }
                   4780:             my %roleshash;
                   4781:             my @courses_and_groups = @courses;
                   4782:             push(@courses_and_groups,@groups); 
                   4783:             if (@courses_and_groups > 0) {
                   4784:                 my (%allgroups,%allroles); 
                   4785:                 my ($start,$end,$role,$sec,$group);
                   4786:                 foreach my $envkey (%env) {
1.1060    raeburn  4787:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4788:                         my $cid = $2.'_'.$3; 
                   4789:                         if ($1 eq 'gr') {
                   4790:                             $group = $4;
                   4791:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4792:                         } else {
                   4793:                             if ($4 eq '') {
                   4794:                                 $sec = 'none';
                   4795:                             } else {
                   4796:                                 $sec = $4;
                   4797:                             }
                   4798:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4799:                         }
1.811     albertel 4800:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4801:                         my $cid = $2.'_'.$3;
                   4802:                         if ($4 eq '') {
                   4803:                             $sec = 'none';
                   4804:                         } else {
                   4805:                             $sec = $4;
                   4806:                         }
                   4807:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4808:                     }
                   4809:                 }
                   4810:                 if (keys(%allroles) == 0) {
                   4811:                     return;
                   4812:                 }
                   4813:                 foreach my $key (@courses_and_groups) {
                   4814:                     my %content = %{$$access_hash{$key}};
                   4815:                     my $cnum = $content{'number'};
                   4816:                     my $cdom = $content{'domain'};
                   4817:                     my $cid = $cdom.'_'.$cnum;
                   4818:                     if (!exists($allroles{$cid})) {
                   4819:                         next;
                   4820:                     }    
                   4821:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4822:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4823:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4824:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4825:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4826:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4827:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4828:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4829:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4830:                                         if (grep/^all$/,@sections) {
                   4831:                                             return 'ok';
                   4832:                                         } else {
                   4833:                                             if (grep/^$sec$/,@sections) {
                   4834:                                                 return 'ok';
                   4835:                                             }
                   4836:                                         }
                   4837:                                     }
                   4838:                                 }
                   4839:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4840:                                     if (grep/^none$/,@groups) {
                   4841:                                         return 'ok';
                   4842:                                     }
                   4843:                                 } else {
                   4844:                                     if (grep/^all$/,@groups) {
                   4845:                                         return 'ok';
                   4846:                                     } 
                   4847:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4848:                                         if (grep/^$group$/,@groups) {
                   4849:                                             return 'ok';
                   4850:                                         }
                   4851:                                     }
                   4852:                                 } 
                   4853:                             }
                   4854:                         }
                   4855:                     }
                   4856:                 }
                   4857:             }
                   4858:             if ($guest) {
                   4859:                 return $guest;
                   4860:             }
                   4861:         }
                   4862:     }
                   4863:     return;
                   4864: }
                   4865: 
                   4866: sub course_group_datechecker {
                   4867:     my ($dates,$now,$status) = @_;
                   4868:     my ($start,$end) = split(/\./,$dates);
                   4869:     if (!$start && !$end) {
                   4870:         return 'ok';
                   4871:     }
                   4872:     if (grep/^active$/,@{$status}) {
                   4873:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4874:             return 'ok';
                   4875:         }
                   4876:     }
                   4877:     if (grep/^previous$/,@{$status}) {
                   4878:         if ($end > $now ) {
                   4879:             return 'ok';
                   4880:         }
                   4881:     }
                   4882:     if (grep/^future$/,@{$status}) {
                   4883:         if ($start > $now) {
                   4884:             return 'ok';
                   4885:         }
                   4886:     }
                   4887:     return; 
                   4888: }
                   4889: 
                   4890: sub parse_portfolio_url {
                   4891:     my ($url) = @_;
                   4892: 
                   4893:     my ($type,$udom,$unum,$group,$file_name);
                   4894:     
1.823     albertel 4895:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4896: 	$type = 1;
                   4897:         $udom = $1;
                   4898:         $unum = $2;
                   4899:         $file_name = $3;
1.823     albertel 4900:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4901: 	$type = 2;
                   4902:         $udom = $1;
                   4903:         $unum = $2;
                   4904:         $group = $3;
                   4905:         $file_name = $3.'/'.$4;
                   4906:     }
                   4907:     if (wantarray) {
                   4908: 	return ($type,$udom,$unum,$file_name,$group);
                   4909:     }
                   4910:     return $type;
                   4911: }
                   4912: 
                   4913: sub is_portfolio_url {
                   4914:     my ($url) = @_;
                   4915:     return scalar(&parse_portfolio_url($url));
                   4916: }
                   4917: 
1.798     raeburn  4918: sub is_portfolio_file {
                   4919:     my ($file) = @_;
1.820     raeburn  4920:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4921:         return 1;
                   4922:     }
                   4923:     return;
                   4924: }
                   4925: 
1.976     raeburn  4926: sub usertools_access {
1.1084    raeburn  4927:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  4928:     my ($access,%tools);
                   4929:     if ($context eq '') {
                   4930:         $context = 'tools';
                   4931:     }
                   4932:     if ($context eq 'requestcourses') {
                   4933:         %tools = (
                   4934:                       official   => 1,
                   4935:                       unofficial => 1,
1.1006    raeburn  4936:                       community  => 1,
1.985     raeburn  4937:                  );
                   4938:     } else {
                   4939:         %tools = (
                   4940:                       aboutme   => 1,
                   4941:                       blog      => 1,
                   4942:                       portfolio => 1,
                   4943:                  );
                   4944:     }
1.976     raeburn  4945:     return if (!defined($tools{$tool}));
                   4946: 
                   4947:     if ((!defined($udom)) || (!defined($uname))) {
                   4948:         $udom = $env{'user.domain'};
                   4949:         $uname = $env{'user.name'};
                   4950:     }
                   4951: 
1.978     raeburn  4952:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4953:         if ($action ne 'reload') {
1.985     raeburn  4954:             if ($context eq 'requestcourses') {
                   4955:                 return $env{'environment.canrequest.'.$tool};
                   4956:             } else {
                   4957:                 return $env{'environment.availabletools.'.$tool};
                   4958:             }
                   4959:         }
1.976     raeburn  4960:     }
                   4961: 
                   4962:     my ($toolstatus,$inststatus);
                   4963: 
1.985     raeburn  4964:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4965:          ($action ne 'reload')) {
                   4966:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4967:         $inststatus = $env{'environment.inststatus'};
                   4968:     } else {
1.1084    raeburn  4969:         if (ref($userenvref) eq 'HASH') {
                   4970:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   4971:             $inststatus = $userenvref->{'inststatus'};
                   4972:         } else {
                   4973:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   4974:             $toolstatus = $userenv{$context.'.'.$tool};
                   4975:             $inststatus = $userenv{'inststatus'};
                   4976:         }
1.976     raeburn  4977:     }
                   4978: 
                   4979:     if ($toolstatus ne '') {
                   4980:         if ($toolstatus) {
                   4981:             $access = 1;
                   4982:         } else {
                   4983:             $access = 0;
                   4984:         }
                   4985:         return $access;
                   4986:     }
                   4987: 
1.1084    raeburn  4988:     my ($is_adv,%domdef);
                   4989:     if (ref($is_advref) eq 'HASH') {
                   4990:         $is_adv = $is_advref->{'is_adv'};
                   4991:     } else {
                   4992:         $is_adv = &is_advanced_user($udom,$uname);
                   4993:     }
                   4994:     if (ref($domdefref) eq 'HASH') {
                   4995:         %domdef = %{$domdefref};
                   4996:     } else {
                   4997:         %domdef = &get_domain_defaults($udom);
                   4998:     }
1.976     raeburn  4999:     if (ref($domdef{$tool}) eq 'HASH') {
                   5000:         if ($is_adv) {
                   5001:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5002:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5003:                     $access = 1;
                   5004:                 } else {
                   5005:                     $access = 0;
                   5006:                 }
                   5007:                 return $access;
                   5008:             }
                   5009:         }
                   5010:         if ($inststatus ne '') {
                   5011:             my ($hasaccess,$hasnoaccess);
                   5012:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5013:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5014:                     if ($domdef{$tool}{$affiliation}) {
                   5015:                         $hasaccess = 1;
                   5016:                     } else {
                   5017:                         $hasnoaccess = 1;
                   5018:                     }
                   5019:                 }
                   5020:             }
                   5021:             if ($hasaccess || $hasnoaccess) {
                   5022:                 if ($hasaccess) {
                   5023:                     $access = 1;
                   5024:                 } elsif ($hasnoaccess) {
                   5025:                     $access = 0; 
                   5026:                 }
                   5027:                 return $access;
                   5028:             }
                   5029:         } else {
                   5030:             if ($domdef{$tool}{'default'} ne '') {
                   5031:                 if ($domdef{$tool}{'default'}) {
                   5032:                     $access = 1;
                   5033:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5034:                     $access = 0;
                   5035:                 }
                   5036:                 return $access;
                   5037:             }
                   5038:         }
                   5039:     } else {
1.985     raeburn  5040:         if ($context eq 'tools') {
                   5041:             $access = 1;
                   5042:         } else {
                   5043:             $access = 0;
                   5044:         }
1.976     raeburn  5045:         return $access;
                   5046:     }
                   5047: }
                   5048: 
1.1050    raeburn  5049: sub is_course_owner {
                   5050:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5051:     if (($udom eq '') || ($uname eq '')) {
                   5052:         $udom = $env{'user.domain'};
                   5053:         $uname = $env{'user.name'};
                   5054:     }
                   5055:     unless (($udom eq '') || ($uname eq '')) {
                   5056:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5057:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5058:                 return 1;
                   5059:             } else {
                   5060:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5061:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5062:                     return 1;
                   5063:                 }
                   5064:             }
                   5065:         }
                   5066:     }
                   5067:     return;
                   5068: }
                   5069: 
1.976     raeburn  5070: sub is_advanced_user {
                   5071:     my ($udom,$uname) = @_;
1.1085    raeburn  5072:     if ($udom ne '' && $uname ne '') {
                   5073:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5074:             return $env{'user.adv'};  
                   5075:         }
                   5076:     }
1.976     raeburn  5077:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5078:     my %allroles;
                   5079:     my $is_adv;
                   5080:     foreach my $role (keys(%roleshash)) {
                   5081:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5082:         my $area = '/'.$tdomain.'/'.$trest;
                   5083:         if ($sec ne '') {
                   5084:             $area .= '/'.$sec;
                   5085:         }
                   5086:         if (($area ne '') && ($trole ne '')) {
                   5087:             my $spec=$trole.'.'.$area;
                   5088:             if ($trole =~ /^cr\//) {
                   5089:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5090:             } elsif ($trole ne 'gr') {
                   5091:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5092:             }
                   5093:         }
                   5094:     }
                   5095:     foreach my $role (keys(%allroles)) {
                   5096:         last if ($is_adv);
                   5097:         foreach my $item (split(/:/,$allroles{$role})) {
                   5098:             if ($item ne '') {
                   5099:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5100:                 if ($privilege eq 'adv') {
                   5101:                     $is_adv = 1;
                   5102:                     last;
                   5103:                 }
                   5104:             }
                   5105:         }
                   5106:     }
                   5107:     return $is_adv;
                   5108: }
1.798     raeburn  5109: 
1.1035    raeburn  5110: sub check_can_request {
1.1036    raeburn  5111:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5112:     my $canreq = 0;
                   5113:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5114:     my @options = ('approval','validate','autolimit');
                   5115:     my $optregex = join('|',@options);
                   5116:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5117:         foreach my $type (@{$types}) {
                   5118:             if (&usertools_access($env{'user.name'},
                   5119:                                   $env{'user.domain'},
                   5120:                                   $type,undef,'requestcourses')) {
                   5121:                 $canreq ++;
1.1036    raeburn  5122:                 if (ref($request_domains) eq 'HASH') {
                   5123:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5124:                 }
1.1035    raeburn  5125:                 if ($dom eq $env{'user.domain'}) {
                   5126:                     $can_request->{$type} = 1;
                   5127:                 }
                   5128:             }
                   5129:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5130:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5131:                 if (@curr > 0) {
1.1036    raeburn  5132:                     foreach my $item (@curr) {
                   5133:                         if (ref($request_domains) eq 'HASH') {
                   5134:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5135:                             if ($otherdom ne '') {
                   5136:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5137:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5138:                                         push(@{$request_domains->{$type}},$otherdom);
                   5139:                                     }
                   5140:                                 } else {
                   5141:                                     push(@{$request_domains->{$type}},$otherdom);
                   5142:                                 }
                   5143:                             }
                   5144:                         }
                   5145:                     }
                   5146:                     unless($dom eq $env{'user.domain'}) {
                   5147:                         $canreq ++;
1.1035    raeburn  5148:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5149:                             $can_request->{$type} = 1;
                   5150:                         }
                   5151:                     }
                   5152:                 }
                   5153:             }
                   5154:         }
                   5155:     }
                   5156:     return $canreq;
                   5157: }
                   5158: 
1.341     www      5159: # ---------------------------------------------- Custom access rule evaluation
                   5160: 
                   5161: sub customaccess {
                   5162:     my ($priv,$uri)=@_;
1.807     albertel 5163:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5164:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5165:     $udom = &LONCAPA::clean_domain($udom);
                   5166:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5167:     my $access=0;
1.800     albertel 5168:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5169: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5170: 	if ($type eq 'user') {
                   5171: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5172: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5173: 		if ($tdom) {
                   5174: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5175: 		}
1.896     albertel 5176: 		if ($tuname) {
                   5177: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5178: 		}
                   5179: 		$access=($effect eq 'allow');
                   5180: 		last;
                   5181: 	    }
                   5182: 	} else {
                   5183: 	    if ($role) {
                   5184: 		if ($role ne $urole) { next; }
                   5185: 	    }
                   5186: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5187: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5188: 		if ($tdom) {
                   5189: 		    if ($tdom ne $udom) { next; }
                   5190: 		}
                   5191: 		if ($tcrs) {
                   5192: 		    if ($tcrs ne $ucrs) { next; }
                   5193: 		}
                   5194: 		if ($tsec) {
                   5195: 		    if ($tsec ne $usec) { next; }
                   5196: 		}
                   5197: 		$access=($effect eq 'allow');
                   5198: 		last;
                   5199: 	    }
                   5200: 	    if ($realm eq '' && $role eq '') {
                   5201: 		$access=($effect eq 'allow');
                   5202: 	    }
1.402     bowersj2 5203: 	}
1.341     www      5204:     }
                   5205:     return $access;
                   5206: }
                   5207: 
1.103     harris41 5208: # ------------------------------------------------- Check for a user privilege
1.12      www      5209: 
                   5210: sub allowed {
1.810     raeburn  5211:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5212:     my $ver_orguri=$uri;
1.439     www      5213:     $uri=&deversion($uri);
1.152     www      5214:     my $orguri=$uri;
1.52      www      5215:     $uri=&declutter($uri);
1.809     raeburn  5216: 
1.810     raeburn  5217:     if ($priv eq 'evb') {
                   5218: # Evade communication block restrictions for specified role in a course
                   5219:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5220:             return $1;
                   5221:         } else {
                   5222:             return;
                   5223:         }
                   5224:     }
                   5225: 
1.620     albertel 5226:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5227: # Free bre access to adm and meta resources
1.775     albertel 5228:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5229: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5230: 	&& ($priv eq 'bre')) {
1.14      www      5231: 	return 'F';
1.159     www      5232:     }
                   5233: 
1.545     banghart 5234: # Free bre access to user's own portfolio contents
1.714     raeburn  5235:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5236:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5237: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5238:         my %setters;
                   5239:         my ($startblock,$endblock) = 
                   5240:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5241:         if ($startblock && $endblock) {
                   5242:             return 'B';
                   5243:         } else {
                   5244:             return 'F';
                   5245:         }
1.545     banghart 5246:     }
                   5247: 
1.762     raeburn  5248: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5249:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5250:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5251:         if (exists($env{'request.course.id'})) {
                   5252:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5253:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5254:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5255:                 my $courseprivid=$env{'request.course.id'};
                   5256:                 $courseprivid=~s/\_/\//;
                   5257:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5258:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5259:                     return $1; 
1.762     raeburn  5260:                 } else {
                   5261:                     if ($env{'request.course.sec'}) {
                   5262:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5263:                     }
                   5264:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5265:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5266:                         return $2;
                   5267:                     }
1.714     raeburn  5268:                 }
                   5269:             }
                   5270:         }
                   5271:     }
                   5272: 
1.159     www      5273: # Free bre to public access
                   5274: 
                   5275:     if ($priv eq 'bre') {
1.238     www      5276:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5277: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5278:            return 'F'; 
                   5279:         }
1.238     www      5280:         if ($copyright eq 'priv') {
                   5281:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5282: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5283: 		return '';
                   5284:             }
                   5285:         }
                   5286:         if ($copyright eq 'domain') {
                   5287:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5288: 	    unless (($env{'user.domain'} eq $1) ||
                   5289:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5290: 		return '';
                   5291:             }
1.262     matthew  5292:         }
1.620     albertel 5293:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5294:             # Library role, so allow browsing of resources in this domain.
                   5295:             return 'F';
1.238     www      5296:         }
1.341     www      5297:         if ($copyright eq 'custom') {
                   5298: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5299:         }
1.14      www      5300:     }
1.264     matthew  5301:     # Domain coordinator is trying to create a course
1.620     albertel 5302:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5303:         # uri is the requested domain in this case.
                   5304:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5305:         # a role of dc for the domain in question.
1.620     albertel 5306:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5307:     }
1.29      www      5308: 
1.52      www      5309:     my $thisallowed='';
                   5310:     my $statecond=0;
                   5311:     my $courseprivid='';
                   5312: 
1.1039    raeburn  5313:     my $ownaccess;
1.1043    raeburn  5314:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5315:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5316:         if ($uri eq '') {
                   5317:             $ownaccess = 1;
                   5318:         } else {
                   5319:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5320:                 my $udom = $env{'user.domain'};
                   5321:                 my $uname = $env{'user.name'};
                   5322:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5323:                     $ownaccess = 1;
1.1040    raeburn  5324:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5325:                     unless ($uri =~ m{\.\./}) {
                   5326:                         $ownaccess = 1;
                   5327:                     }
                   5328:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5329:                     my $now = time;
                   5330:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5331:                         my $adom = $1;
                   5332:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5333:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5334:                                 my ($start,$end) = split('.',$env{$key});
                   5335:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5336:                                     $ownaccess = 1;
                   5337:                                     last;
                   5338:                                 }
                   5339:                             }
                   5340:                         }
                   5341:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5342:                         my $adom = $1;
                   5343:                         my $aname = $2;
1.1042    raeburn  5344:                         foreach my $role ('ca','aa') { 
                   5345:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5346:                                 my ($start,$end) =
                   5347:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5348:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5349:                                     $ownaccess = 1;
                   5350:                                     last;
                   5351:                                 }
1.1039    raeburn  5352:                             }
                   5353:                         }
                   5354:                     }
                   5355:                 }
                   5356:             }
                   5357:         }
                   5358:     }
                   5359: 
1.52      www      5360: # Course
                   5361: 
1.620     albertel 5362:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5363:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5364:             $thisallowed.=$1;
                   5365:         }
1.52      www      5366:     }
1.29      www      5367: 
1.52      www      5368: # Domain
                   5369: 
1.620     albertel 5370:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5371:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5372:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5373:             $thisallowed.=$1;
                   5374:         }
1.12      www      5375:     }
1.52      www      5376: 
                   5377: # Course: uri itself is a course
1.66      www      5378:     my $courseuri=$uri;
                   5379:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5380:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5381: 
1.620     albertel 5382:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5383:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5384:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5385:             $thisallowed.=$1;
                   5386:         }
1.12      www      5387:     }
1.29      www      5388: 
1.665     albertel 5389: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5390: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5391:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5392: 	$thisallowed='';
1.671     raeburn  5393:         my ($match)=&is_on_map($uri);
                   5394:         if ($match) {
                   5395:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5396:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5397:                 $thisallowed.=$1;
                   5398:             }
                   5399:         } else {
1.705     albertel 5400:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5401:             if ($refuri) {
                   5402:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5403:                     $thisallowed='F';
1.671     raeburn  5404:                 } else {
                   5405:                     $refuri=&declutter($refuri);
                   5406:                     my ($match) = &is_on_map($refuri);
                   5407:                     if ($match) {
                   5408:                         $thisallowed='F';
                   5409:                     }
1.669     raeburn  5410:                 }
1.671     raeburn  5411:             }
                   5412:         }
1.314     www      5413:     }
1.492     albertel 5414: 
1.766     albertel 5415:     if ($priv eq 'bre'
                   5416: 	&& $thisallowed ne 'F' 
                   5417: 	&& $thisallowed ne '2'
                   5418: 	&& &is_portfolio_url($uri)) {
                   5419: 	$thisallowed = &portfolio_access($uri);
                   5420:     }
                   5421:     
1.52      www      5422: # Full access at system, domain or course-wide level? Exit.
1.29      www      5423:     if ($thisallowed=~/F/) {
                   5424: 	return 'F';
                   5425:     }
                   5426: 
1.52      www      5427: # If this is generating or modifying users, exit with special codes
1.29      www      5428: 
1.643     www      5429:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5430: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5431: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5432: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5433: 	    unless ($auname) { return $thisallowed; }
                   5434: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5435: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5436: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5437: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5438: 	}
1.52      www      5439: 	return $thisallowed;
                   5440:     }
                   5441: #
1.103     harris41 5442: # Gathered so far: system, domain and course wide privileges
1.52      www      5443: #
                   5444: # Course: See if uri or referer is an individual resource that is part of 
                   5445: # the course
                   5446: 
1.620     albertel 5447:     if ($env{'request.course.id'}) {
1.232     www      5448: 
1.620     albertel 5449:        $courseprivid=$env{'request.course.id'};
                   5450:        if ($env{'request.course.sec'}) {
                   5451:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5452:        }
                   5453:        $courseprivid=~s/\_/\//;
                   5454:        my $checkreferer=1;
1.232     www      5455:        my ($match,$cond)=&is_on_map($uri);
                   5456:        if ($match) {
                   5457:            $statecond=$cond;
1.620     albertel 5458:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5459:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5460:                $thisallowed.=$1;
                   5461:                $checkreferer=0;
                   5462:            }
1.29      www      5463:        }
1.83      www      5464:        
1.148     www      5465:        if ($checkreferer) {
1.620     albertel 5466: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5467:             unless ($refuri) {
1.800     albertel 5468:                 foreach my $key (keys(%env)) {
                   5469: 		    if ($key=~/^httpref\..*\*/) {
                   5470: 			my $pattern=$key;
1.156     www      5471:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5472:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5473:                         $pattern=~s/\//\\\//g;
1.152     www      5474:                         if ($orguri=~/$pattern/) {
1.800     albertel 5475: 			    $refuri=$env{$key};
1.148     www      5476:                         }
                   5477:                     }
1.191     harris41 5478:                 }
1.148     www      5479:             }
1.232     www      5480: 
1.148     www      5481:          if ($refuri) { 
1.152     www      5482: 	  $refuri=&declutter($refuri);
1.232     www      5483:           my ($match,$cond)=&is_on_map($refuri);
                   5484:             if ($match) {
                   5485:               my $refstatecond=$cond;
1.620     albertel 5486:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5487:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5488:                   $thisallowed.=$1;
1.53      www      5489:                   $uri=$refuri;
                   5490:                   $statecond=$refstatecond;
1.52      www      5491:               }
                   5492:           }
1.148     www      5493:         }
1.29      www      5494:        }
1.52      www      5495:    }
1.29      www      5496: 
1.52      www      5497: #
1.103     harris41 5498: # Gathered now: all privileges that could apply, and condition number
1.52      www      5499: # 
                   5500: #
                   5501: # Full or no access?
                   5502: #
1.29      www      5503: 
1.52      www      5504:     if ($thisallowed=~/F/) {
                   5505: 	return 'F';
                   5506:     }
1.29      www      5507: 
1.52      www      5508:     unless ($thisallowed) {
                   5509:         return '';
                   5510:     }
1.29      www      5511: 
1.52      www      5512: # Restrictions exist, deal with them
                   5513: #
                   5514: #   C:according to course preferences
                   5515: #   R:according to resource settings
                   5516: #   L:unless locked
                   5517: #   X:according to user session state
                   5518: #
                   5519: 
                   5520: # Possibly locked functionality, check all courses
1.54      www      5521: # Locks might take effect only after 10 minutes cache expiration for other
                   5522: # courses, and 2 minutes for current course
1.52      www      5523: 
                   5524:     my $envkey;
                   5525:     if ($thisallowed=~/L/) {
1.1000    raeburn  5526:         foreach $envkey (keys(%env)) {
1.54      www      5527:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5528:                my $courseid=$2;
                   5529:                my $roleid=$1.'.'.$2;
1.92      www      5530:                $courseid=~s/^\///;
1.54      www      5531:                my $expiretime=600;
1.620     albertel 5532:                if ($env{'request.role'} eq $roleid) {
1.54      www      5533: 		  $expiretime=120;
                   5534:                }
                   5535: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5536:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5537:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5538: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5539:                }
1.620     albertel 5540:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5541:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5542: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5543:                        &log($env{'user.domain'},$env{'user.name'},
                   5544:                             $env{'user.home'},
1.57      www      5545:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5546:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5547:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5548: 		       return '';
                   5549:                    }
                   5550:                }
1.620     albertel 5551:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5552:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5553: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5554:                        &log($env{'user.domain'},$env{'user.name'},
                   5555:                             $env{'user.home'},
1.57      www      5556:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5557:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5558:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5559: 		       return '';
                   5560:                    }
                   5561:                }
                   5562: 	   }
1.29      www      5563:        }
1.52      www      5564:     }
                   5565:    
                   5566: #
                   5567: # Rest of the restrictions depend on selected course
                   5568: #
                   5569: 
1.620     albertel 5570:     unless ($env{'request.course.id'}) {
1.766     albertel 5571: 	if ($thisallowed eq 'A') {
                   5572: 	    return 'A';
1.814     raeburn  5573:         } elsif ($thisallowed eq 'B') {
                   5574:             return 'B';
1.766     albertel 5575: 	} else {
                   5576: 	    return '1';
                   5577: 	}
1.52      www      5578:     }
1.29      www      5579: 
1.52      www      5580: #
                   5581: # Now user is definitely in a course
                   5582: #
1.53      www      5583: 
                   5584: 
                   5585: # Course preferences
                   5586: 
                   5587:    if ($thisallowed=~/C/) {
1.620     albertel 5588:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5589:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5590:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5591: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5592: 	   if ($priv ne 'pch') { 
                   5593: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5594: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5595: 			$env{'request.course.id'});
                   5596: 	   }
1.237     www      5597:            return '';
                   5598:        }
                   5599: 
1.620     albertel 5600:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5601: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5602: 	   if ($priv ne 'pch') { 
                   5603: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5604: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5605: 			$env{'request.course.id'});
                   5606: 	   }
1.54      www      5607:            return '';
                   5608:        }
1.53      www      5609:    }
                   5610: 
                   5611: # Resource preferences
                   5612: 
                   5613:    if ($thisallowed=~/R/) {
1.620     albertel 5614:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5615:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5616: 	   if ($priv ne 'pch') { 
                   5617: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5618: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5619: 	   }
                   5620: 	   return '';
1.54      www      5621:        }
1.53      www      5622:    }
1.30      www      5623: 
1.246     www      5624: # Restricted by state or randomout?
1.30      www      5625: 
1.52      www      5626:    if ($thisallowed=~/X/) {
1.620     albertel 5627:       if ($env{'acc.randomout'}) {
1.579     albertel 5628: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5629:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5630:             return ''; 
                   5631:          }
1.247     www      5632:       }
                   5633:       if (&condval($statecond)) {
1.52      www      5634: 	 return '2';
                   5635:       } else {
                   5636:          return '';
                   5637:       }
                   5638:    }
1.30      www      5639: 
1.766     albertel 5640:     if ($thisallowed eq 'A') {
                   5641: 	return 'A';
1.814     raeburn  5642:     } elsif ($thisallowed eq 'B') {
                   5643:         return 'B';
1.766     albertel 5644:     }
1.52      www      5645:    return 'F';
1.232     www      5646: }
                   5647: 
1.710     albertel 5648: sub split_uri_for_cond {
                   5649:     my $uri=&deversion(&declutter(shift));
                   5650:     my @uriparts=split(/\//,$uri);
                   5651:     my $filename=pop(@uriparts);
                   5652:     my $pathname=join('/',@uriparts);
                   5653:     return ($pathname,$filename);
                   5654: }
1.232     www      5655: # --------------------------------------------------- Is a resource on the map?
                   5656: 
                   5657: sub is_on_map {
1.710     albertel 5658:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5659:     #Trying to find the conditional for the file
1.620     albertel 5660:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5661: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5662:     if ($match) {
1.289     bowersj2 5663: 	return (1,$1);
                   5664:     } else {
1.434     www      5665: 	return (0,0);
1.289     bowersj2 5666:     }
1.12      www      5667: }
                   5668: 
1.427     www      5669: # --------------------------------------------------------- Get symb from alias
                   5670: 
                   5671: sub get_symb_from_alias {
                   5672:     my $symb=shift;
                   5673:     my ($map,$resid,$url)=&decode_symb($symb);
                   5674: # Already is a symb
                   5675:     if ($url) { return $symb; }
                   5676: # Must be an alias
                   5677:     my $aliassymb='';
                   5678:     my %bighash;
1.620     albertel 5679:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5680:                             &GDBM_READER(),0640)) {
                   5681:         my $rid=$bighash{'mapalias_'.$symb};
                   5682: 	if ($rid) {
                   5683: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5684: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5685: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5686: 	}
                   5687:         untie %bighash;
                   5688:     }
                   5689:     return $aliassymb;
                   5690: }
                   5691: 
1.12      www      5692: # ----------------------------------------------------------------- Define Role
                   5693: 
                   5694: sub definerole {
                   5695:   if (allowed('mcr','/')) {
                   5696:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5697:     foreach my $role (split(':',$sysrole)) {
                   5698: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5699:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5700:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5701: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5702:                return "refused:s:$crole&$cqual"; 
                   5703:             }
                   5704:         }
1.191     harris41 5705:     }
1.800     albertel 5706:     foreach my $role (split(':',$domrole)) {
                   5707: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5708:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5709:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5710: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5711:                return "refused:d:$crole&$cqual"; 
                   5712:             }
                   5713:         }
1.191     harris41 5714:     }
1.800     albertel 5715:     foreach my $role (split(':',$courole)) {
                   5716: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5717:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5718:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5719: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5720:                return "refused:c:$crole&$cqual"; 
                   5721:             }
                   5722:         }
1.191     harris41 5723:     }
1.620     albertel 5724:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5725:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5726: 	        "rolesdef_$rolename=".
                   5727:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5728:     return reply($command,$env{'user.home'});
1.12      www      5729:   } else {
                   5730:     return 'refused';
                   5731:   }
1.105     harris41 5732: }
                   5733: 
                   5734: # ---------------- Make a metadata query against the network of library servers
                   5735: 
                   5736: sub metadata_query {
1.244     matthew  5737:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5738:     my %rhash;
1.845     albertel 5739:     my %libserv = &all_library();
1.244     matthew  5740:     my @server_list = (defined($server_array) ? @$server_array
                   5741:                                               : keys(%libserv) );
                   5742:     for my $server (@server_list) {
1.118     harris41 5743: 	unless ($custom or $customshow) {
                   5744: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5745: 	    $rhash{$server}=$reply;
                   5746: 	}
                   5747: 	else {
                   5748: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5749: 			     &escape($custom).':'.&escape($customshow),
                   5750: 			     $server);
                   5751: 	    $rhash{$server}=$reply;
                   5752: 	}
1.112     harris41 5753:     }
1.118     harris41 5754:     return \%rhash;
1.240     www      5755: }
                   5756: 
                   5757: # ----------------------------------------- Send log queries and wait for reply
                   5758: 
                   5759: sub log_query {
                   5760:     my ($uname,$udom,$query,%filters)=@_;
                   5761:     my $uhome=&homeserver($uname,$udom);
                   5762:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5763:     my $uhost=&hostname($uhome);
1.800     albertel 5764:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5765:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5766:                        $uhome);
1.479     albertel 5767:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5768:     return get_query_reply($queryid);
                   5769: }
                   5770: 
1.818     raeburn  5771: # -------------------------- Update MySQL table for portfolio file
                   5772: 
                   5773: sub update_portfolio_table {
1.821     raeburn  5774:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5775:     if ($group ne '') {
                   5776:         $file_name =~s /^\Q$group\E//;
                   5777:     }
1.818     raeburn  5778:     my $homeserver = &homeserver($uname,$udom);
                   5779:     my $queryid=
1.821     raeburn  5780:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5781:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5782:     my $reply = &get_query_reply($queryid);
                   5783:     return $reply;
                   5784: }
                   5785: 
1.899     raeburn  5786: # -------------------------- Update MySQL allusers table
                   5787: 
                   5788: sub update_allusers_table {
                   5789:     my ($uname,$udom,$names) = @_;
                   5790:     my $homeserver = &homeserver($uname,$udom);
                   5791:     my $queryid=
                   5792:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5793:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5794:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5795:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5796:                'generation='.&escape($names->{'generation'}).'%%'.
                   5797:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5798:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  5799:     return;
1.899     raeburn  5800: }
                   5801: 
1.508     raeburn  5802: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5803: 
                   5804: sub fetch_enrollment_query {
1.511     raeburn  5805:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5806:     my $homeserver;
1.547     raeburn  5807:     my $maxtries = 1;
1.508     raeburn  5808:     if ($context eq 'automated') {
                   5809:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5810:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5811:     } else {
                   5812:         $homeserver = &homeserver($cnum,$dom);
                   5813:     }
1.838     albertel 5814:     my $host=&hostname($homeserver);
1.506     raeburn  5815:     my $cmd = '';
1.1000    raeburn  5816:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5817:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5818:     }
                   5819:     $cmd =~ s/%%$//;
                   5820:     $cmd = &escape($cmd);
                   5821:     my $query = 'fetchenrollment';
1.620     albertel 5822:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5823:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5824:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5825:         return 'error: '.$queryid;
                   5826:     }
1.506     raeburn  5827:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5828:     my $tries = 1;
                   5829:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5830:         $reply = &get_query_reply($queryid);
                   5831:         $tries ++;
                   5832:     }
1.526     raeburn  5833:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5834:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5835:     } else {
1.901     albertel 5836:         my @responses = split(/:/,$reply);
1.515     raeburn  5837:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5838:             foreach my $line (@responses) {
                   5839:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5840:                 $$replyref{$key} = $value;
                   5841:             }
                   5842:         } else {
1.506     raeburn  5843:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5844:             foreach my $line (@responses) {
                   5845:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5846:                 $$replyref{$key} = $value;
                   5847:                 if ($value > 0) {
1.800     albertel 5848:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5849:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5850:                         my $destname = $pathname.'/'.$filename;
                   5851:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5852:                         if ($xml_classlist =~ /^error/) {
                   5853:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5854:                         } else {
1.506     raeburn  5855:                             if ( open(FILE,">$destname") ) {
                   5856:                                 print FILE &unescape($xml_classlist);
                   5857:                                 close(FILE);
1.526     raeburn  5858:                             } else {
                   5859:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5860:                             }
                   5861:                         }
                   5862:                     }
                   5863:                 }
                   5864:             }
                   5865:         }
                   5866:         return 'ok';
                   5867:     }
                   5868:     return 'error';
                   5869: }
                   5870: 
1.242     www      5871: sub get_query_reply {
                   5872:     my $queryid=shift;
1.240     www      5873:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5874:     my $reply='';
                   5875:     for (1..100) {
                   5876: 	sleep 2;
                   5877:         if (-e $replyfile.'.end') {
1.448     albertel 5878: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5879: 		$reply = join('',<$fh>);
                   5880: 		close($fh);
1.240     www      5881: 	   } else { return 'error: reply_file_error'; }
1.242     www      5882:            return &unescape($reply);
                   5883: 	}
1.240     www      5884:     }
1.242     www      5885:     return 'timeout:'.$queryid;
1.240     www      5886: }
                   5887: 
                   5888: sub courselog_query {
1.241     www      5889: #
                   5890: # possible filters:
                   5891: # url: url or symb
                   5892: # username
                   5893: # domain
                   5894: # action: view, submit, grade
                   5895: # start: timestamp
                   5896: # end: timestamp
                   5897: #
1.240     www      5898:     my (%filters)=@_;
1.620     albertel 5899:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5900:     if ($filters{'url'}) {
                   5901: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5902:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5903:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5904:     }
1.620     albertel 5905:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5906:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5907:     return &log_query($cname,$cdom,'courselog',%filters);
                   5908: }
                   5909: 
                   5910: sub userlog_query {
1.858     raeburn  5911: #
                   5912: # possible filters:
                   5913: # action: log check role
                   5914: # start: timestamp
                   5915: # end: timestamp
                   5916: #
1.240     www      5917:     my ($uname,$udom,%filters)=@_;
                   5918:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5919: }
                   5920: 
1.506     raeburn  5921: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5922: 
                   5923: sub auto_run {
1.508     raeburn  5924:     my ($cnum,$cdom) = @_;
1.876     raeburn  5925:     my $response = 0;
                   5926:     my $settings;
                   5927:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5928:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5929:         $settings = $domconfig{'autoenroll'};
                   5930:         if ($settings->{'run'} eq '1') {
                   5931:             $response = 1;
                   5932:         }
                   5933:     } else {
1.934     raeburn  5934:         my $homeserver;
                   5935:         if (&is_course($cdom,$cnum)) {
                   5936:             $homeserver = &homeserver($cnum,$cdom);
                   5937:         } else {
                   5938:             $homeserver = &domain($cdom,'primary');
                   5939:         }
                   5940:         if ($homeserver ne 'no_host') {
                   5941:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5942:         }
1.876     raeburn  5943:     }
1.506     raeburn  5944:     return $response;
                   5945: }
1.776     albertel 5946: 
1.506     raeburn  5947: sub auto_get_sections {
1.508     raeburn  5948:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5949:     my $homeserver;
                   5950:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5951:         $homeserver = &homeserver($cnum,$cdom);
                   5952:     }
                   5953:     if (!defined($homeserver)) { 
                   5954:         if ($cdom =~ /^$match_domain$/) {
                   5955:             $homeserver = &domain($cdom,'primary');
                   5956:         }
                   5957:     }
                   5958:     my @secs;
                   5959:     if (defined($homeserver)) {
                   5960:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5961:         unless ($response eq 'refused') {
                   5962:             @secs = split(/:/,$response);
                   5963:         }
1.506     raeburn  5964:     }
                   5965:     return @secs;
                   5966: }
1.776     albertel 5967: 
1.506     raeburn  5968: sub auto_new_course {
1.508     raeburn  5969:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5970:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5971:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5972:     return $response;
                   5973: }
1.776     albertel 5974: 
1.506     raeburn  5975: sub auto_validate_courseID {
1.508     raeburn  5976:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5977:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5978:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5979:     return $response;
                   5980: }
1.776     albertel 5981: 
1.1007    raeburn  5982: sub auto_validate_instcode {
1.1020    raeburn  5983:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  5984:     my ($homeserver,$response);
                   5985:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5986:         $homeserver = &homeserver($cnum,$cdom);
                   5987:     }
                   5988:     if (!defined($homeserver)) {
                   5989:         if ($cdom =~ /^$match_domain$/) {
                   5990:             $homeserver = &domain($cdom,'primary');
                   5991:         }
                   5992:     }
1.1065    raeburn  5993:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   5994:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  5995:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   5996:     return ($outcome,$description);
1.1007    raeburn  5997: }
                   5998: 
1.506     raeburn  5999: sub auto_create_password {
1.873     raeburn  6000:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6001:     my ($homeserver,$response);
1.506     raeburn  6002:     my $create_passwd = 0;
                   6003:     my $authchk = '';
1.873     raeburn  6004:     if ($udom =~ /^$match_domain$/) {
                   6005:         $homeserver = &domain($udom,'primary');
                   6006:     }
                   6007:     if ($homeserver eq '') {
                   6008:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6009:             $homeserver = &homeserver($cnum,$cdom);
                   6010:         }
                   6011:     }
                   6012:     if ($homeserver eq '') {
                   6013:         $authchk = 'nodomain';
1.506     raeburn  6014:     } else {
1.873     raeburn  6015:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6016:         if ($response eq 'refused') {
                   6017:             $authchk = 'refused';
                   6018:         } else {
1.901     albertel 6019:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6020:         }
1.506     raeburn  6021:     }
                   6022:     return ($authparam,$create_passwd,$authchk);
                   6023: }
                   6024: 
1.706     raeburn  6025: sub auto_photo_permission {
                   6026:     my ($cnum,$cdom,$students) = @_;
                   6027:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6028:     my ($outcome,$perm_reqd,$conditions) = 
                   6029: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6030:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6031: 	return (undef,undef);
                   6032:     }
1.706     raeburn  6033:     return ($outcome,$perm_reqd,$conditions);
                   6034: }
                   6035: 
                   6036: sub auto_checkphotos {
                   6037:     my ($uname,$udom,$pid) = @_;
                   6038:     my $homeserver = &homeserver($uname,$udom);
                   6039:     my ($result,$resulttype);
                   6040:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6041: 				   &escape($uname).':'.&escape($pid),
                   6042: 				   $homeserver));
1.709     albertel 6043:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6044: 	return (undef,undef);
                   6045:     }
1.706     raeburn  6046:     if ($outcome) {
                   6047:         ($result,$resulttype) = split(/:/,$outcome);
                   6048:     } 
                   6049:     return ($result,$resulttype);
                   6050: }
                   6051: 
                   6052: sub auto_photochoice {
                   6053:     my ($cnum,$cdom) = @_;
                   6054:     my $homeserver = &homeserver($cnum,$cdom);
                   6055:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6056: 						       &escape($cdom),
                   6057: 						       $homeserver)));
1.709     albertel 6058:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6059: 	return (undef,undef);
                   6060:     }
1.706     raeburn  6061:     return ($update,$comment);
                   6062: }
                   6063: 
                   6064: sub auto_photoupdate {
                   6065:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6066:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6067:     my $host=&hostname($homeserver);
1.706     raeburn  6068:     my $cmd = '';
                   6069:     my $maxtries = 1;
1.800     albertel 6070:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6071:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6072:     }
                   6073:     $cmd =~ s/%%$//;
                   6074:     $cmd = &escape($cmd);
                   6075:     my $query = 'institutionalphotos';
                   6076:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6077:     unless ($queryid=~/^\Q$host\E\_/) {
                   6078:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6079:         return 'error: '.$queryid;
                   6080:     }
                   6081:     my $reply = &get_query_reply($queryid);
                   6082:     my $tries = 1;
                   6083:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6084:         $reply = &get_query_reply($queryid);
                   6085:         $tries ++;
                   6086:     }
                   6087:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6088:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6089:     } else {
                   6090:         my @responses = split(/:/,$reply);
                   6091:         my $outcome = shift(@responses); 
                   6092:         foreach my $item (@responses) {
                   6093:             my ($key,$value) = split(/=/,$item);
                   6094:             $$photo{$key} = $value;
                   6095:         }
                   6096:         return $outcome;
                   6097:     }
                   6098:     return 'error';
                   6099: }
                   6100: 
1.521     raeburn  6101: sub auto_instcode_format {
1.793     albertel 6102:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6103: 	$cat_order) = @_;
1.521     raeburn  6104:     my $courses = '';
1.772     raeburn  6105:     my @homeservers;
1.521     raeburn  6106:     if ($caller eq 'global') {
1.841     albertel 6107: 	my %servers = &get_servers($codedom,'library');
                   6108: 	foreach my $tryserver (keys(%servers)) {
                   6109: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6110: 		push(@homeservers,$tryserver);
                   6111: 	    }
1.584     raeburn  6112:         }
1.1022    raeburn  6113:     } elsif ($caller eq 'requests') {
                   6114:         if ($codedom =~ /^$match_domain$/) {
                   6115:             my $chome = &domain($codedom,'primary');
                   6116:             unless ($chome eq 'no_host') {
                   6117:                 push(@homeservers,$chome);
                   6118:             }
                   6119:         }
1.521     raeburn  6120:     } else {
1.772     raeburn  6121:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6122:     }
1.793     albertel 6123:     foreach my $code (keys(%{$instcodes})) {
                   6124:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6125:     }
                   6126:     chop($courses);
1.772     raeburn  6127:     my $ok_response = 0;
                   6128:     my $response;
                   6129:     while (@homeservers > 0 && $ok_response == 0) {
                   6130:         my $server = shift(@homeservers); 
                   6131:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6132:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6133:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6134: 		split(/:/,$response);
1.772     raeburn  6135:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6136:             push(@{$codetitles},&str2array($codetitles_str));
                   6137:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6138:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6139:             $ok_response = 1;
                   6140:         }
                   6141:     }
                   6142:     if ($ok_response) {
1.521     raeburn  6143:         return 'ok';
1.772     raeburn  6144:     } else {
                   6145:         return $response;
1.521     raeburn  6146:     }
                   6147: }
                   6148: 
1.792     raeburn  6149: sub auto_instcode_defaults {
                   6150:     my ($domain,$returnhash,$code_order) = @_;
                   6151:     my @homeservers;
1.841     albertel 6152: 
                   6153:     my %servers = &get_servers($domain,'library');
                   6154:     foreach my $tryserver (keys(%servers)) {
                   6155: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6156: 	    push(@homeservers,$tryserver);
                   6157: 	}
1.792     raeburn  6158:     }
1.841     albertel 6159: 
1.792     raeburn  6160:     my $response;
1.841     albertel 6161:     foreach my $server (@homeservers) {
1.792     raeburn  6162:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6163:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6164: 	
                   6165: 	foreach my $pair (split(/\&/,$response)) {
                   6166: 	    my ($name,$value)=split(/\=/,$pair);
                   6167: 	    if ($name eq 'code_order') {
                   6168: 		@{$code_order} = split(/\&/,&unescape($value));
                   6169: 	    } else {
                   6170: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6171: 	    }
                   6172: 	}
                   6173: 	return 'ok';
1.792     raeburn  6174:     }
1.841     albertel 6175: 
                   6176:     return $response;
1.1003    raeburn  6177: }
                   6178: 
                   6179: sub auto_possible_instcodes {
1.1007    raeburn  6180:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6181:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6182:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6183:         return;
                   6184:     }
1.1003    raeburn  6185:     my (@homeservers,$uhome);
                   6186:     if (defined(&domain($domain,'primary'))) {
                   6187:         $uhome=&domain($domain,'primary');
                   6188:         push(@homeservers,&domain($domain,'primary'));
                   6189:     } else {
                   6190:         my %servers = &get_servers($domain,'library');
                   6191:         foreach my $tryserver (keys(%servers)) {
                   6192:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6193:                 push(@homeservers,$tryserver);
                   6194:             }
                   6195:         }
                   6196:     }
                   6197:     my $response;
                   6198:     foreach my $server (@homeservers) {
                   6199:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6200:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6201:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6202:             split(':',$response);
                   6203:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6204:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6205:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6206:             my ($name,$value)=split('=',$item);
                   6207:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6208:         }
                   6209:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6210:             my ($name,$value)=split('=',$item);
                   6211:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6212:         }
                   6213:         return 'ok';
                   6214:     }
                   6215:     return $response;
                   6216: }
1.792     raeburn  6217: 
1.1010    raeburn  6218: sub auto_courserequest_checks {
                   6219:     my ($dom) = @_;
1.1020    raeburn  6220:     my ($homeserver,%validations);
                   6221:     if ($dom =~ /^$match_domain$/) {
                   6222:         $homeserver = &domain($dom,'primary');
                   6223:     }
                   6224:     unless ($homeserver eq 'no_host') {
                   6225:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6226:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6227:             my @items = split(/&/,$response);
                   6228:             foreach my $item (@items) {
                   6229:                 my ($key,$value) = split('=',$item);
                   6230:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6231:             }
                   6232:         }
                   6233:     }
1.1010    raeburn  6234:     return %validations; 
                   6235: }
                   6236: 
1.1020    raeburn  6237: sub auto_courserequest_validation {
                   6238:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6239:     my ($homeserver,$response);
                   6240:     if ($dom =~ /^$match_domain$/) {
                   6241:         $homeserver = &domain($dom,'primary');
                   6242:     }
                   6243:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6244:           
1.1020    raeburn  6245:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6246:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6247:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6248:                                     $homeserver));
                   6249:     }
                   6250:     return $response;
                   6251: }
                   6252: 
1.777     albertel 6253: sub auto_validate_class_sec {
1.918     raeburn  6254:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6255:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6256:     my $ownerlist;
                   6257:     if (ref($owners) eq 'ARRAY') {
                   6258:         $ownerlist = join(',',@{$owners});
                   6259:     } else {
                   6260:         $ownerlist = $owners;
                   6261:     }
1.773     raeburn  6262:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6263:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6264:     return $response;
                   6265: }
                   6266: 
1.679     raeburn  6267: # ------------------------------------------------------- Course Group routines
                   6268: 
                   6269: sub get_coursegroups {
1.809     raeburn  6270:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6271:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6272: }
                   6273: 
1.679     raeburn  6274: sub modify_coursegroup {
                   6275:     my ($cdom,$cnum,$groupsettings) = @_;
                   6276:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6277: }
                   6278: 
1.809     raeburn  6279: sub toggle_coursegroup_status {
                   6280:     my ($cdom,$cnum,$group,$action) = @_;
                   6281:     my ($from_namespace,$to_namespace);
                   6282:     if ($action eq 'delete') {
                   6283:         $from_namespace = 'coursegroups';
                   6284:         $to_namespace = 'deleted_groups';
                   6285:     } else {
                   6286:         $from_namespace = 'deleted_groups';
                   6287:         $to_namespace = 'coursegroups';
                   6288:     }
                   6289:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6290:     if (my $tmp = &error(%curr_group)) {
                   6291:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6292:         return ('read error',$tmp);
                   6293:     } else {
                   6294:         my %savedsettings = %curr_group; 
1.809     raeburn  6295:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6296:         my $deloutcome;
                   6297:         if ($result eq 'ok') {
1.809     raeburn  6298:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6299:         } else {
                   6300:             return ('write error',$result);
                   6301:         }
                   6302:         if ($deloutcome eq 'ok') {
                   6303:             return 'ok';
                   6304:         } else {
                   6305:             return ('delete error',$deloutcome);
                   6306:         }
                   6307:     }
                   6308: }
                   6309: 
1.679     raeburn  6310: sub modify_group_roles {
1.957     raeburn  6311:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6312:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6313:     my $role = 'gr/'.&escape($userprivs);
                   6314:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6315:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6316:     if ($result eq 'ok') {
                   6317:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6318:     }
1.679     raeburn  6319:     return $result;
                   6320: }
                   6321: 
                   6322: sub modify_coursegroup_membership {
                   6323:     my ($cdom,$cnum,$membership) = @_;
                   6324:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6325:     return $result;
                   6326: }
                   6327: 
1.682     raeburn  6328: sub get_active_groups {
                   6329:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6330:     my $now = time;
                   6331:     my %groups = ();
                   6332:     foreach my $key (keys(%env)) {
1.811     albertel 6333:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6334:             my ($start,$end) = split(/\./,$env{$key});
                   6335:             if (($end!=0) && ($end<$now)) { next; }
                   6336:             if (($start!=0) && ($start>$now)) { next; }
                   6337:             if ($1 eq $cdom && $2 eq $cnum) {
                   6338:                 $groups{$3} = $env{$key} ;
                   6339:             }
                   6340:         }
                   6341:     }
                   6342:     return %groups;
                   6343: }
                   6344: 
1.683     raeburn  6345: sub get_group_membership {
                   6346:     my ($cdom,$cnum,$group) = @_;
                   6347:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6348: }
                   6349: 
                   6350: sub get_users_groups {
                   6351:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6352:     my @usersgroups;
1.683     raeburn  6353:     my $cachetime=1800;
                   6354: 
                   6355:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6356:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6357:     if (defined($cached)) {
1.734     albertel 6358:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6359:     } else {  
                   6360:         $grouplist = '';
1.816     raeburn  6361:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6362:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6363:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6364:         my $access_end = $env{'course.'.$courseid.
                   6365:                               '.default_enrollment_end_date'};
                   6366:         my $now = time;
                   6367:         foreach my $key (keys(%roleshash)) {
                   6368:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6369:                 my $group = $1;
                   6370:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6371:                     my $start = $2;
                   6372:                     my $end = $1;
                   6373:                     if ($start == -1) { next; } # deleted from group
                   6374:                     if (($start!=0) && ($start>$now)) { next; }
                   6375:                     if (($end!=0) && ($end<$now)) {
                   6376:                         if ($access_end && $access_end < $now) {
                   6377:                             if ($access_end - $end < 86400) {
                   6378:                                 push(@usersgroups,$group);
1.733     raeburn  6379:                             }
                   6380:                         }
1.817     raeburn  6381:                         next;
1.733     raeburn  6382:                     }
1.817     raeburn  6383:                     push(@usersgroups,$group);
1.683     raeburn  6384:                 }
                   6385:             }
                   6386:         }
1.817     raeburn  6387:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6388:         $grouplist = join(':',@usersgroups);
                   6389:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6390:     }
1.733     raeburn  6391:     return @usersgroups;
1.683     raeburn  6392: }
                   6393: 
                   6394: sub devalidate_getgroups_cache {
                   6395:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6396:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6397: 
1.683     raeburn  6398:     my $hashid="$udom:$uname:$courseid";
                   6399:     &devalidate_cache_new('getgroups',$hashid);
                   6400: }
                   6401: 
1.12      www      6402: # ------------------------------------------------------------------ Plain Text
                   6403: 
                   6404: sub plaintext {
1.988     raeburn  6405:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6406:     if ($short =~ m{^cr/}) {
1.758     albertel 6407: 	return (split('/',$short))[-1];
                   6408:     }
1.742     raeburn  6409:     if (!defined($cid)) {
                   6410:         $cid = $env{'request.course.id'};
                   6411:     }
                   6412:     my %rolenames = (
1.1008    raeburn  6413:                       Course    => 'std',
                   6414:                       Community => 'alt1',
1.742     raeburn  6415:                     );
1.1037    raeburn  6416:     if ($cid ne '') {
                   6417:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6418:             unless ($forcedefault) {
                   6419:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6420:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6421:                 return &Apache::lonlocal::mt($roletext);
                   6422:             }
                   6423:         }
                   6424:     }
                   6425:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6426:         (defined($rolenames{$type})) && 
                   6427:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6428:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6429:     } elsif ($cid ne '') {
                   6430:         my $crstype = $env{'course.'.$cid.'.type'};
                   6431:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6432:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6433:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6434:         }
1.742     raeburn  6435:     }
1.1037    raeburn  6436:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6437: }
                   6438: 
                   6439: # ----------------------------------------------------------------- Assign Role
                   6440: 
                   6441: sub assignrole {
1.957     raeburn  6442:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6443:         $context)=@_;
1.21      www      6444:     my $mrole;
                   6445:     if ($role =~ /^cr\//) {
1.393     www      6446:         my $cwosec=$url;
1.811     albertel 6447:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6448: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6449:            my $refused = 1;
                   6450:            if ($context eq 'requestcourses') {
                   6451:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6452:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6453:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6454:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6455:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6456:                            if ($crsenv{'internal.courseowner'} eq
                   6457:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6458:                                $refused = '';
                   6459:                            }
                   6460:                        }
                   6461:                    }
                   6462:                }
                   6463:            }
                   6464:            if ($refused) {
                   6465:                &logthis('Refused custom assignrole: '.
                   6466:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6467:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6468:                return 'refused';
                   6469:            }
1.104     www      6470:         }
1.21      www      6471:         $mrole='cr';
1.678     raeburn  6472:     } elsif ($role =~ /^gr\//) {
                   6473:         my $cwogrp=$url;
1.811     albertel 6474:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6475:         unless (&allowed('mdg',$cwogrp)) {
                   6476:             &logthis('Refused group assignrole: '.
                   6477:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6478:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6479:             return 'refused';
                   6480:         }
                   6481:         $mrole='gr';
1.21      www      6482:     } else {
1.82      www      6483:         my $cwosec=$url;
1.811     albertel 6484:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6485:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6486:             my $refused;
                   6487:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6488:                 if (!(&allowed('c'.$role,$url))) {
                   6489:                     $refused = 1;
                   6490:                 }
                   6491:             } else {
                   6492:                 $refused = 1;
                   6493:             }
1.947     raeburn  6494:             if ($refused) {
1.1045    raeburn  6495:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6496:                 if (!$selfenroll && $context eq 'course') {
                   6497:                     my %crsenv;
                   6498:                     if ($role eq 'cc' || $role eq 'co') {
                   6499:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6500:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6501:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6502:                                 if ($crsenv{'internal.courseowner'} eq 
                   6503:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6504:                                     $refused = '';
                   6505:                                 }
                   6506:                             }
                   6507:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6508:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6509:                                 if ($crsenv{'internal.courseowner'} eq 
                   6510:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6511:                                     $refused = '';
                   6512:                                 }
                   6513:                             }
                   6514:                         }
                   6515:                     }
                   6516:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6517:                     $refused = '';
1.1017    raeburn  6518:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6519:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6520:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6521:                         my $wrongcc;
                   6522:                         if ($cnum =~ /^$match_community$/) {
                   6523:                             $wrongcc = 1 if ($role eq 'cc');
                   6524:                         } else {
                   6525:                             $wrongcc = 1 if ($role eq 'co');
                   6526:                         }
                   6527:                         unless ($wrongcc) {
                   6528:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6529:                             if ($crsenv{'internal.courseowner'} eq 
                   6530:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6531:                                 $refused = '';
                   6532:                             }
1.1017    raeburn  6533:                         }
                   6534:                     }
                   6535:                 }
                   6536:                 if ($refused) {
1.947     raeburn  6537:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6538:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6539: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6540:                     return 'refused';
                   6541:                 }
1.932     raeburn  6542:             }
1.104     www      6543:         }
1.21      www      6544:         $mrole=$role;
                   6545:     }
1.620     albertel 6546:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6547:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6548:     if ($end) { $command.='_'.$end; }
1.21      www      6549:     if ($start) {
                   6550: 	if ($end) { 
1.81      www      6551:            $command.='_'.$start; 
1.21      www      6552:         } else {
1.81      www      6553:            $command.='_0_'.$start;
1.21      www      6554:         }
                   6555:     }
1.739     raeburn  6556:     my $origstart = $start;
                   6557:     my $origend = $end;
1.957     raeburn  6558:     my $delflag;
1.357     www      6559: # actually delete
                   6560:     if ($deleteflag) {
1.373     www      6561: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6562: # modify command to delete the role
1.620     albertel 6563:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6564:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6565: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6566: # set start and finish to negative values for userrolelog
                   6567:            $start=-1;
                   6568:            $end=-1;
1.957     raeburn  6569:            $delflag = 1;
1.357     www      6570:         }
                   6571:     }
                   6572: # send command
1.349     www      6573:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6574: # log new user role if status is ok
1.349     www      6575:     if ($answer eq 'ok') {
1.663     raeburn  6576: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6577: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6578:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6579:         unless ($role =~ /^gr/) {
                   6580:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6581:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6582:         }
1.1053    raeburn  6583:         if ($role eq 'cc') {
                   6584:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6585:         }
1.349     www      6586:     }
                   6587:     return $answer;
1.169     harris41 6588: }
                   6589: 
1.1053    raeburn  6590: sub autoupdate_coowners {
                   6591:     my ($url,$end,$start,$uname,$udom) = @_;
                   6592:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6593:     if (($cdom ne '') && ($cnum ne '')) {
                   6594:         my $now = time;
                   6595:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6596:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6597:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6598:             my $instcode = $coursehash{'internal.coursecode'};
                   6599:             if ($instcode ne '') {
1.1056    raeburn  6600:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6601:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6602:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6603:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6604:                         if ($result eq 'valid') {
                   6605:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6606:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6607:                                     push(@newcoowners,$coowner);
                   6608:                                 }
                   6609:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6610:                                     push(@newcoowners,$uname.':'.$udom);
                   6611:                                 }
                   6612:                                 @newcoowners = sort(@newcoowners);
                   6613:                             } else {
                   6614:                                 push(@newcoowners,$uname.':'.$udom);
                   6615:                             }
                   6616:                         } else {
                   6617:                             if ($coursehash{'internal.co-owners'}) {
                   6618:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6619:                                     unless ($coowner eq $uname.':'.$udom) {
                   6620:                                         push(@newcoowners,$coowner);
                   6621:                                     }
                   6622:                                 }
                   6623:                                 unless (@newcoowners > 0) {
                   6624:                                     $delcoowners = 1;
                   6625:                                     $coowners = '';
                   6626:                                 }
                   6627:                             }
                   6628:                         }
                   6629:                         if (@newcoowners || $delcoowners) {
                   6630:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6631:                                             $delcoowners,@newcoowners);
                   6632:                         }
                   6633:                     }
                   6634:                 }
                   6635:             }
                   6636:         }
                   6637:     }
                   6638: }
                   6639: 
                   6640: sub store_coowners {
                   6641:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6642:     my $cid = $cdom.'_'.$cnum;
                   6643:     my ($coowners,$delresult,$putresult);
                   6644:     if (@newcoowners) {
                   6645:         $coowners = join(',',@newcoowners);
                   6646:         my %coownershash = (
                   6647:                             'internal.co-owners' => $coowners,
                   6648:                            );
                   6649:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6650:         if ($putresult eq 'ok') {
                   6651:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6652:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6653:             }
                   6654:         }
                   6655:     }
                   6656:     if ($delcoowners) {
                   6657:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6658:         if ($delresult eq 'ok') {
                   6659:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6660:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6661:             }
                   6662:         }
                   6663:     }
                   6664:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6665:         my %crsinfo =
                   6666:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6667:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6668:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6669:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6670:         }
                   6671:     }
                   6672: }
                   6673: 
1.169     harris41 6674: # -------------------------------------------------- Modify user authentication
1.197     www      6675: # Overrides without validation
                   6676: 
1.169     harris41 6677: sub modifyuserauth {
                   6678:     my ($udom,$uname,$umode,$upass)=@_;
                   6679:     my $uhome=&homeserver($uname,$udom);
1.197     www      6680:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6681:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6682:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6683:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6684:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6685: 		     &escape($upass),$uhome);
1.620     albertel 6686:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6687:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6688:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6689:     &log($udom,,$uname,$uhome,
1.620     albertel 6690:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6691:                                      $env{'user.name'}.', '.$umode.
1.197     www      6692:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6693:     unless ($reply eq 'ok') {
1.197     www      6694:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6695: 	return 'error: '.$reply;
                   6696:     }   
1.170     harris41 6697:     return 'ok';
1.80      www      6698: }
                   6699: 
1.81      www      6700: # --------------------------------------------------------------- Modify a user
1.80      www      6701: 
1.81      www      6702: sub modifyuser {
1.206     matthew  6703:     my ($udom,    $uname, $uid,
                   6704:         $umode,   $upass, $first,
                   6705:         $middle,  $last,  $gene,
1.1058    raeburn  6706:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6707:     $udom= &LONCAPA::clean_domain($udom);
                   6708:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6709:     my $showcandelete = 'none';
                   6710:     if (ref($candelete) eq 'ARRAY') {
                   6711:         if (@{$candelete} > 0) {
                   6712:             $showcandelete = join(', ',@{$candelete});
                   6713:         }
                   6714:     }
1.81      www      6715:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6716:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6717: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6718:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6719:                                      ' desiredhome not specified'). 
1.620     albertel 6720:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6721:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6722:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6723:     my $newuser;
                   6724:     if ($uhome eq 'no_host') {
                   6725:         $newuser = 1;
                   6726:     }
1.80      www      6727: # ----------------------------------------------------------------- Create User
1.406     albertel 6728:     if (($uhome eq 'no_host') && 
                   6729: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6730:         my $unhome='';
1.844     albertel 6731:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6732:             $unhome = $desiredhome;
1.620     albertel 6733: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6734: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6735:         } else { # load balancing routine for determining $unhome
1.81      www      6736:             my $loadm=10000000;
1.841     albertel 6737: 	    my %servers = &get_servers($udom,'library');
                   6738: 	    foreach my $tryserver (keys(%servers)) {
                   6739: 		my $answer=reply('load',$tryserver);
                   6740: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6741: 		    $loadm=$answer;
                   6742: 		    $unhome=$tryserver;
                   6743: 		}
1.80      www      6744: 	    }
                   6745:         }
                   6746:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6747: 	    return 'error: unable to find a home server for '.$uname.
                   6748:                    ' in domain '.$udom;
1.80      www      6749:         }
                   6750:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6751:                          &escape($upass),$unhome);
                   6752: 	unless ($reply eq 'ok') {
                   6753:             return 'error: '.$reply;
                   6754:         }   
1.230     stredwic 6755:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6756:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6757: 	    return 'error: unable verify users home machine.';
1.80      www      6758:         }
1.209     matthew  6759:     }   # End of creation of new user
1.80      www      6760: # ---------------------------------------------------------------------- Add ID
                   6761:     if ($uid) {
                   6762:        $uid=~tr/A-Z/a-z/;
                   6763:        my %uidhash=&idrget($udom,$uname);
1.196     www      6764:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6765:          && (!$forceid)) {
1.80      www      6766: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6767: 	      return 'error: user id "'.$uid.'" does not match '.
                   6768:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6769:           }
                   6770:        } else {
                   6771: 	  &idput($udom,($uname => $uid));
                   6772:        }
                   6773:     }
                   6774: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6775:     my @tmp=&get('environment',
1.899     raeburn  6776: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6777:                     'permanentemail','inststatus'],
1.134     albertel 6778: 		   $udom,$uname);
1.1075    raeburn  6779:     my (%names,%oldnames);
1.313     matthew  6780:     if ($tmp[0] =~ m/^error:.*/) { 
                   6781:         %names=(); 
                   6782:     } else {
                   6783:         %names = @tmp;
1.1075    raeburn  6784:         %oldnames = %names;
1.313     matthew  6785:     }
1.388     www      6786: #
1.1058    raeburn  6787: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6788: # of users did not contain them), do not overwrite existing values
                   6789: # unless field is in $candelete array ref.  
                   6790: #
                   6791: 
                   6792:     my @fields = ('firstname','middlename','lastname','generation',
                   6793:                   'permanentemail','id');
                   6794:     my %newvalues;
                   6795:     if (ref($candelete) eq 'ARRAY') {
                   6796:         foreach my $field (@fields) {
                   6797:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6798:                 if ($field eq 'firstname') {
                   6799:                     $names{$field} = $first;
                   6800:                 } elsif ($field eq 'middlename') {
                   6801:                     $names{$field} = $middle;
                   6802:                 } elsif ($field eq 'lastname') {
                   6803:                     $names{$field} = $last;
                   6804:                 } elsif ($field eq 'generation') { 
                   6805:                     $names{$field} = $gene;
                   6806:                 } elsif ($field eq 'permanentemail') {
                   6807:                     $names{$field} = $email;
                   6808:                 } elsif ($field eq 'id') {
                   6809:                     $names{$field}  = $uid;
                   6810:                 }
                   6811:             }
                   6812:         }
                   6813:     }
1.388     www      6814:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6815:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6816:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6817:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6818:     if ($email) {
                   6819:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6820:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6821:     }
1.899     raeburn  6822:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6823:     if (defined($inststatus)) {
                   6824:         $names{'inststatus'} = '';
                   6825:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6826:         if (ref($usertypes) eq 'HASH') {
                   6827:             my @okstatuses; 
                   6828:             foreach my $item (split(/:/,$inststatus)) {
                   6829:                 if (defined($usertypes->{$item})) {
                   6830:                     push(@okstatuses,$item);  
                   6831:                 }
                   6832:             }
                   6833:             if (@okstatuses) {
                   6834:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6835:             }
                   6836:         }
                   6837:     }
1.1075    raeburn  6838:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6839:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  6840:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6841:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6842:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6843:     } else {
                   6844:         $logmsg .= ' during self creation';
                   6845:     }
1.1075    raeburn  6846:     my $changed;
                   6847:     if ($newuser) {
                   6848:         $changed = 1;
                   6849:     } else {
                   6850:         foreach my $field (@fields) {
                   6851:             if ($names{$field} ne $oldnames{$field}) {
                   6852:                 $changed = 1;
                   6853:                 last;
                   6854:             }
                   6855:         }
                   6856:     }
                   6857:     unless ($changed) {
                   6858:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6859:         &logthis($logmsg);
                   6860:         return 'ok';
                   6861:     }
                   6862:     my $reply = &put('environment', \%names, $udom,$uname);
                   6863:     if ($reply ne 'ok') { 
                   6864:         return 'error: '.$reply;
                   6865:     }
1.1087    raeburn  6866:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   6867:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   6868:     }
1.1075    raeburn  6869:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6870:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6871:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6872:     &logthis($logmsg);
1.134     albertel 6873:     return 'ok';
1.80      www      6874: }
                   6875: 
1.81      www      6876: # -------------------------------------------------------------- Modify student
1.80      www      6877: 
1.81      www      6878: sub modifystudent {
                   6879:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6880:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6881:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6882:     if (!$cid) {
1.620     albertel 6883: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6884: 	    return 'not_in_class';
                   6885: 	}
1.80      www      6886:     }
                   6887: # --------------------------------------------------------------- Make the user
1.81      www      6888:     my $reply=&modifyuser
1.209     matthew  6889: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6890:          $desiredhome,$email,$inststatus);
1.80      www      6891:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6892:     # This will cause &modify_student_enrollment to get the uid from the
                   6893:     # students environment
                   6894:     $uid = undef if (!$forceid);
1.455     albertel 6895:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6896: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6897:     return $reply;
                   6898: }
                   6899: 
                   6900: sub modify_student_enrollment {
1.957     raeburn  6901:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6902:     my ($cdom,$cnum,$chome);
                   6903:     if (!$cid) {
1.620     albertel 6904: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6905: 	    return 'not_in_class';
                   6906: 	}
1.620     albertel 6907: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6908: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6909:     } else {
                   6910: 	($cdom,$cnum)=split(/_/,$cid);
                   6911:     }
1.620     albertel 6912:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6913:     if (!$chome) {
1.457     raeburn  6914: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6915:     }
1.455     albertel 6916:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6917:     # Make sure the user exists
1.81      www      6918:     my $uhome=&homeserver($uname,$udom);
                   6919:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6920: 	return 'error: no such user';
                   6921:     }
1.297     matthew  6922:     # Get student data if we were not given enough information
                   6923:     if (!defined($first)  || $first  eq '' || 
                   6924:         !defined($last)   || $last   eq '' || 
                   6925:         !defined($uid)    || $uid    eq '' || 
                   6926:         !defined($middle) || $middle eq '' || 
                   6927:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6928:         # They did not supply us with enough data to enroll the student, so
                   6929:         # we need to pick up more information.
1.297     matthew  6930:         my %tmp = &get('environment',
1.294     matthew  6931:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6932:                        ,$udom,$uname);
                   6933: 
1.800     albertel 6934:         #foreach my $key (keys(%tmp)) {
                   6935:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6936:         #}
1.294     matthew  6937:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6938:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6939:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6940:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6941:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6942:     }
1.556     albertel 6943:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6944:     my $reply=cput('classlist',
                   6945: 		   {"$uname:$udom" => 
1.515     raeburn  6946: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6947: 		   $cdom,$cnum);
1.81      www      6948:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6949: 	return 'error: '.$reply;
1.652     albertel 6950:     } else {
                   6951: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6952:     }
1.297     matthew  6953:     # Add student role to user
1.83      www      6954:     my $uurl='/'.$cid;
1.81      www      6955:     $uurl=~s/\_/\//g;
                   6956:     if ($usec) {
                   6957: 	$uurl.='/'.$usec;
                   6958:     }
1.957     raeburn  6959:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6960: }
                   6961: 
1.556     albertel 6962: sub format_name {
                   6963:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6964:     my $name;
                   6965:     if ($first ne 'lastname') {
                   6966: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6967:     } else {
                   6968: 	if ($lastname=~/\S/) {
                   6969: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6970: 	    $name=~s/\s+,/,/;
                   6971: 	} else {
                   6972: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6973: 	}
                   6974:     }
                   6975:     $name=~s/^\s+//;
                   6976:     $name=~s/\s+$//;
                   6977:     $name=~s/\s+/ /g;
                   6978:     return $name;
                   6979: }
                   6980: 
1.84      www      6981: # ------------------------------------------------- Write to course preferences
                   6982: 
                   6983: sub writecoursepref {
                   6984:     my ($courseid,%prefs)=@_;
                   6985:     $courseid=~s/^\///;
                   6986:     $courseid=~s/\_/\//g;
                   6987:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6988:     my $chome=homeserver($cnum,$cdomain);
                   6989:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6990: 	return 'error: no such course';
                   6991:     }
                   6992:     my $cstring='';
1.800     albertel 6993:     foreach my $pref (keys(%prefs)) {
                   6994: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6995:     }
1.84      www      6996:     $cstring=~s/\&$//;
                   6997:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6998: }
                   6999: 
                   7000: # ---------------------------------------------------------- Make/modify course
                   7001: 
                   7002: sub createcourse {
1.741     raeburn  7003:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7004:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7005:     $url=&declutter($url);
                   7006:     my $cid='';
1.1028    raeburn  7007:     if ($context eq 'requestcourses') {
                   7008:         my $can_create = 0;
                   7009:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7010:         if ($udom eq $ownerdom) {
                   7011:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7012:                                   $context)) {
                   7013:                 $can_create = 1;
                   7014:             }
                   7015:         } else {
                   7016:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7017:                                            $category);
                   7018:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7019:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7020:                 if (@curr > 0) {
                   7021:                     my @options = qw(approval validate autolimit);
                   7022:                     my $optregex = join('|',@options);
                   7023:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7024:                         $can_create = 1;
                   7025:                     }
                   7026:                 }
                   7027:             }
                   7028:         }
                   7029:         if ($can_create) {
                   7030:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7031:                 unless (&allowed('ccc',$udom)) {
                   7032:                     return 'refused'; 
                   7033:                 }
1.1017    raeburn  7034:             }
                   7035:         } else {
                   7036:             return 'refused';
                   7037:         }
1.1028    raeburn  7038:     } elsif (!&allowed('ccc',$udom)) {
                   7039:         return 'refused';
1.84      www      7040:     }
1.1011    raeburn  7041: # --------------------------------------------------------------- Get Unique ID
                   7042:     my $uname;
                   7043:     if ($cnum =~ /^$match_courseid$/) {
                   7044:         my $chome=&homeserver($cnum,$udom,'true');
                   7045:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7046:             $uname = $cnum;
                   7047:         } else {
1.1038    raeburn  7048:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7049:         }
                   7050:     } else {
1.1038    raeburn  7051:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7052:     }
                   7053:     return $uname if ($uname =~ /^error/);
                   7054: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7055:     if (!defined($course_server)) {
                   7056:         if (defined(&domain($udom,'primary'))) {
                   7057:             $course_server = &domain($udom,'primary');
                   7058:         } else {
                   7059:             $course_server = $env{'user.home'}; 
                   7060:         }
                   7061:     }
                   7062:     my %host_servers =
                   7063:         &Apache::lonnet::get_servers($udom,'library');
                   7064:     unless ($host_servers{$course_server}) {
                   7065:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7066:     }
1.84      www      7067: # ------------------------------------------------------------- Make the course
                   7068:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7069:                       $course_server);
1.84      www      7070:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7071:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7072:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7073: 	return 'error: no such course';
                   7074:     }
1.271     www      7075: # ----------------------------------------------------------------- Course made
1.516     raeburn  7076: # log existence
1.1029    raeburn  7077:     my $now = time;
1.918     raeburn  7078:     my $newcourse = {
                   7079:                     $udom.'_'.$uname => {
1.921     raeburn  7080:                                      description => $description,
                   7081:                                      inst_code   => $inst_code,
                   7082:                                      owner       => $course_owner,
                   7083:                                      type        => $crstype,
1.1029    raeburn  7084:                                      creator     => $env{'user.name'}.':'.
                   7085:                                                     $env{'user.domain'},
                   7086:                                      created     => $now,
                   7087:                                      context     => $context,
1.918     raeburn  7088:                                                 },
                   7089:                     };
1.921     raeburn  7090:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7091: # set toplevel url
1.271     www      7092:     my $topurl=$url;
                   7093:     unless ($nonstandard) {
                   7094: # ------------------------------------------ For standard courses, make top url
                   7095:         my $mapurl=&clutter($url);
1.278     www      7096:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7097:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7098: <map>
                   7099: <resource id="1" type="start"></resource>
                   7100: <resource id="2" src="$mapurl"></resource>
                   7101: <resource id="3" type="finish"></resource>
                   7102: <link index="1" from="1" to="2"></link>
                   7103: <link index="2" from="2" to="3"></link>
                   7104: </map>
                   7105: ENDINITMAP
                   7106:         $topurl=&declutter(
1.638     albertel 7107:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7108:                           );
                   7109:     }
                   7110: # ----------------------------------------------------------- Write preferences
1.84      www      7111:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7112:                      ('description'              => $description,
                   7113:                       'url'                      => $topurl,
                   7114:                       'internal.creator'         => $env{'user.name'}.':'.
                   7115:                                                     $env{'user.domain'},
                   7116:                       'internal.created'         => $now,
                   7117:                       'internal.creationcontext' => $context)
                   7118:                     );
1.84      www      7119:     return '/'.$udom.'/'.$uname;
                   7120: }
                   7121: 
1.1011    raeburn  7122: # ------------------------------------------------------------------- Create ID
                   7123: sub generate_coursenum {
1.1038    raeburn  7124:     my ($udom,$crstype) = @_;
1.1011    raeburn  7125:     my $domdesc = &domain($udom);
                   7126:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7127:     my $first;
                   7128:     if ($crstype eq 'Community') {
                   7129:         $first = '0';
                   7130:     } else {
                   7131:         $first = int(1+rand(9)); 
                   7132:     } 
                   7133:     my $uname=$first.
1.1011    raeburn  7134:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7135:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7136:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7137: # ----------------------------------------------- Make sure that does not exist
                   7138:     my $uhome=&homeserver($uname,$udom,'true');
                   7139:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7140:         if ($crstype eq 'Community') {
                   7141:             $first = '0';
                   7142:         } else {
                   7143:             $first = int(1+rand(9));
                   7144:         }
                   7145:         $uname=$first.
1.1011    raeburn  7146:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7147:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7148:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7149:         $uhome=&homeserver($uname,$udom,'true');
                   7150:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7151:             return 'error: unable to generate unique course-ID';
                   7152:         }
                   7153:     }
                   7154:     return $uname;
                   7155: }
                   7156: 
1.813     albertel 7157: sub is_course {
                   7158:     my ($cdom,$cnum) = @_;
                   7159:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7160: 				undef,'.');
1.813     albertel 7161:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7162:         return 1;
                   7163:     }
                   7164:     return 0;
                   7165: }
                   7166: 
1.1015    raeburn  7167: sub store_userdata {
                   7168:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7169:     my $result;
1.1016    raeburn  7170:     if ($datakey ne '') {
1.1013    raeburn  7171:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7172:             if ($udom eq '' || $uname eq '') {
                   7173:                 $udom = $env{'user.domain'};
                   7174:                 $uname = $env{'user.name'};
                   7175:             }
                   7176:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7177:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7178:                 $result = 'error: no_host';
                   7179:             } else {
                   7180:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7181:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7182: 
                   7183:                 my $namevalue='';
                   7184:                 foreach my $key (keys(%{$storehash})) {
                   7185:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7186:                 }
                   7187:                 $namevalue=~s/\&$//;
                   7188:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7189:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7190:             }
                   7191:         } else {
                   7192:             $result = 'error: data to store was not a hash reference'; 
                   7193:         }
                   7194:     } else {
                   7195:         $result= 'error: invalid requestkey'; 
                   7196:     }
                   7197:     return $result;
                   7198: }
                   7199: 
1.21      www      7200: # ---------------------------------------------------------- Assign Custom Role
                   7201: 
                   7202: sub assigncustomrole {
1.957     raeburn  7203:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7204:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7205:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7206: }
                   7207: 
                   7208: # ----------------------------------------------------------------- Revoke Role
                   7209: 
                   7210: sub revokerole {
1.957     raeburn  7211:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7212:     my $now=time;
1.965     raeburn  7213:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7214: }
                   7215: 
                   7216: # ---------------------------------------------------------- Revoke Custom Role
                   7217: 
                   7218: sub revokecustomrole {
1.957     raeburn  7219:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7220:     my $now=time;
1.357     www      7221:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7222:            $deleteflag,$selfenroll,$context);
1.17      www      7223: }
                   7224: 
1.533     banghart 7225: # ------------------------------------------------------------ Disk usage
1.535     albertel 7226: sub diskusage {
1.955     raeburn  7227:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7228:     $directorypath =~ s/\/$//;
                   7229:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7230:                        .&escape($getpropath).':'.&escape($uname).':'
                   7231:                        .&escape($udom),homeserver($uname,$udom));
                   7232:     if ($listing eq 'unknown_cmd') {
                   7233:         if ($getpropath) {
                   7234:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7235:         }
                   7236:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7237:     }
1.514     albertel 7238:     return $listing;
1.512     banghart 7239: }
                   7240: 
1.566     banghart 7241: sub is_locked {
                   7242:     my ($file_name, $domain, $user) = @_;
                   7243:     my @check;
                   7244:     my $is_locked;
                   7245:     push @check, $file_name;
1.613     albertel 7246:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7247: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7248:     my ($tmp)=keys(%locked);
                   7249:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7250:     
1.566     banghart 7251:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7252:         $is_locked = 'false';
                   7253:         foreach my $entry (@{$locked{$file_name}}) {
                   7254:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7255:                $is_locked = 'true';
                   7256:                last;
1.745     raeburn  7257:            }
                   7258:        }
1.566     banghart 7259:     } else {
                   7260:         $is_locked = 'false';
                   7261:     }
                   7262: }
                   7263: 
1.759     albertel 7264: sub declutter_portfile {
                   7265:     my ($file) = @_;
1.833     albertel 7266:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7267:     return $file;
                   7268: }
                   7269: 
1.559     banghart 7270: # ------------------------------------------------------------- Mark as Read Only
                   7271: 
                   7272: sub mark_as_readonly {
                   7273:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7274:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7275:     my ($tmp)=keys(%current_permissions);
                   7276:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7277:     foreach my $file (@{$files}) {
1.759     albertel 7278: 	$file = &declutter_portfile($file);
1.561     banghart 7279:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7280:     }
1.613     albertel 7281:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7282:     return;
                   7283: }
                   7284: 
1.572     banghart 7285: # ------------------------------------------------------------Save Selected Files
                   7286: 
                   7287: sub save_selected_files {
                   7288:     my ($user, $path, @files) = @_;
                   7289:     my $filename = $user."savedfiles";
1.573     banghart 7290:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7291:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7292:     foreach my $file (@files) {
1.620     albertel 7293:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7294:     }
                   7295:     foreach my $file (@other_files) {
1.574     banghart 7296:         print (OUT $file."\n");
1.572     banghart 7297:     }
1.574     banghart 7298:     close (OUT);
1.572     banghart 7299:     return 'ok';
                   7300: }
                   7301: 
1.574     banghart 7302: sub clear_selected_files {
                   7303:     my ($user) = @_;
                   7304:     my $filename = $user."savedfiles";
                   7305:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7306:     print (OUT undef);
                   7307:     close (OUT);
                   7308:     return ("ok");    
                   7309: }
                   7310: 
1.572     banghart 7311: sub files_in_path {
                   7312:     my ($user, $path) = @_;
                   7313:     my $filename = $user."savedfiles";
                   7314:     my %return_files;
1.574     banghart 7315:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7316:     while (my $line_in = <IN>) {
1.574     banghart 7317:         chomp ($line_in);
                   7318:         my @paths_and_file = split (m!/!, $line_in);
                   7319:         my $file_part = pop (@paths_and_file);
                   7320:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7321:         $path_part.='/';
                   7322:         my $path_and_file = $path_part.$file_part;
                   7323:         if ($path_part eq $path) {
                   7324:             $return_files{$file_part}= 'selected';
                   7325:         }
                   7326:     }
1.574     banghart 7327:     close (IN);
                   7328:     return (\%return_files);
1.572     banghart 7329: }
                   7330: 
                   7331: # called in portfolio select mode, to show files selected NOT in current directory
                   7332: sub files_not_in_path {
                   7333:     my ($user, $path) = @_;
                   7334:     my $filename = $user."savedfiles";
                   7335:     my @return_files;
                   7336:     my $path_part;
1.800     albertel 7337:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7338:     while (my $line = <IN>) {
1.572     banghart 7339:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7340:         my @paths_and_file = split(m|/|, $line);
                   7341:         my $file_part = pop(@paths_and_file);
                   7342:         chomp($file_part);
                   7343:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7344:         $path_part .= '/';
                   7345:         my $path_and_file = $path_part.$file_part;
                   7346:         if ($path_part ne $path) {
1.800     albertel 7347:             push(@return_files, ($path_and_file));
1.572     banghart 7348:         }
                   7349:     }
1.800     albertel 7350:     close(OUT);
1.574     banghart 7351:     return (@return_files);
1.572     banghart 7352: }
                   7353: 
1.745     raeburn  7354: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7355: 
1.745     raeburn  7356: sub get_portfile_permissions {
                   7357:     my ($domain,$user) = @_;
1.613     albertel 7358:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7359:     my ($tmp)=keys(%current_permissions);
                   7360:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7361:     return \%current_permissions;
                   7362: }
                   7363: 
                   7364: #---------------------------------------------Get portfolio file access controls
                   7365: 
1.749     raeburn  7366: sub get_access_controls {
1.745     raeburn  7367:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7368:     my %access;
                   7369:     my $real_file = $file;
                   7370:     $file =~ s/\.meta$//;
1.745     raeburn  7371:     if (defined($file)) {
1.749     raeburn  7372:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7373:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7374:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7375:             }
                   7376:         }
1.745     raeburn  7377:     } else {
1.749     raeburn  7378:         foreach my $key (keys(%{$current_permissions})) {
                   7379:             if ($key =~ /\0accesscontrol$/) {
                   7380:                 if (defined($group)) {
                   7381:                     if ($key !~ m-^\Q$group\E/-) {
                   7382:                         next;
                   7383:                     }
                   7384:                 }
                   7385:                 my ($fullpath) = split(/\0/,$key);
                   7386:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7387:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7388:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7389:                     }
                   7390:                 }
                   7391:             }
                   7392:         }
                   7393:     }
                   7394:     return %access;
                   7395: }
                   7396: 
                   7397: sub modify_access_controls {
                   7398:     my ($file_name,$changes,$domain,$user)=@_;
                   7399:     my ($outcome,$deloutcome);
                   7400:     my %store_permissions;
                   7401:     my %new_values;
                   7402:     my %new_control;
                   7403:     my %translation;
                   7404:     my @deletions = ();
                   7405:     my $now = time;
                   7406:     if (exists($$changes{'activate'})) {
                   7407:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7408:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7409:             my $numnew = scalar(@newitems);
                   7410:             for (my $i=0; $i<$numnew; $i++) {
                   7411:                 my $newkey = $newitems[$i];
                   7412:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7413:                 if ($newkey =~ /^\d+:/) { 
                   7414:                     $newkey =~ s/^(\d+)/$newid/;
                   7415:                     $translation{$1} = $newid;
                   7416:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7417:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7418:                     $translation{$1} = $newid;
                   7419:                 }
1.749     raeburn  7420:                 $new_values{$file_name."\0".$newkey} = 
                   7421:                                           $$changes{'activate'}{$newitems[$i]};
                   7422:                 $new_control{$newkey} = $now;
                   7423:             }
                   7424:         }
                   7425:     }
                   7426:     my %todelete;
                   7427:     my %changed_items;
                   7428:     foreach my $action ('delete','update') {
                   7429:         if (exists($$changes{$action})) {
                   7430:             if (ref($$changes{$action}) eq 'HASH') {
                   7431:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7432:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7433:                     if ($action eq 'delete') { 
                   7434:                         $todelete{$itemnum} = 1;
                   7435:                     } else {
                   7436:                         $changed_items{$itemnum} = $key;
                   7437:                     }
                   7438:                 }
1.745     raeburn  7439:             }
                   7440:         }
1.749     raeburn  7441:     }
                   7442:     # get lock on access controls for file.
                   7443:     my $lockhash = {
                   7444:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7445:                                                        ':'.$env{'user.domain'},
                   7446:                    }; 
                   7447:     my $tries = 0;
                   7448:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7449:    
                   7450:     while (($gotlock ne 'ok') && $tries <3) {
                   7451:         $tries ++;
                   7452:         sleep 1;
                   7453:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7454:     }
                   7455:     if ($gotlock eq 'ok') {
                   7456:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7457:         my ($tmp)=keys(%curr_permissions);
                   7458:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7459:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7460:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7461:             if (ref($curr_controls) eq 'HASH') {
                   7462:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7463:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7464:                     if (defined($todelete{$itemnum})) {
                   7465:                         push(@deletions,$file_name."\0".$control_item);
                   7466:                     } else {
                   7467:                         if (defined($changed_items{$itemnum})) {
                   7468:                             $new_control{$changed_items{$itemnum}} = $now;
                   7469:                             push(@deletions,$file_name."\0".$control_item);
                   7470:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7471:                         } else {
                   7472:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7473:                         }
                   7474:                     }
1.745     raeburn  7475:                 }
                   7476:             }
                   7477:         }
1.970     raeburn  7478:         my ($group);
                   7479:         if (&is_course($domain,$user)) {
                   7480:             ($group,my $file) = split(/\//,$file_name,2);
                   7481:         }
1.749     raeburn  7482:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7483:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7484:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7485:         #  remove lock
                   7486:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7487:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7488:         my $sqlresult =
1.970     raeburn  7489:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7490:                                     $group);
1.749     raeburn  7491:     } else {
                   7492:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7493:     }
1.749     raeburn  7494:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7495: }
                   7496: 
1.827     raeburn  7497: sub make_public_indefinitely {
                   7498:     my ($requrl) = @_;
                   7499:     my $now = time;
                   7500:     my $action = 'activate';
                   7501:     my $aclnum = 0;
                   7502:     if (&is_portfolio_url($requrl)) {
                   7503:         my (undef,$udom,$unum,$file_name,$group) =
                   7504:             &parse_portfolio_url($requrl);
                   7505:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7506:         my %access_controls = &get_access_controls($current_perms,
                   7507:                                                    $group,$file_name);
                   7508:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7509:             my ($num,$scope,$end,$start) = 
                   7510:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7511:             if ($scope eq 'public') {
                   7512:                 if ($start <= $now && $end == 0) {
                   7513:                     $action = 'none';
                   7514:                 } else {
                   7515:                     $action = 'update';
                   7516:                     $aclnum = $num;
                   7517:                 }
                   7518:                 last;
                   7519:             }
                   7520:         }
                   7521:         if ($action eq 'none') {
                   7522:              return 'ok';
                   7523:         } else {
                   7524:             my %changes;
                   7525:             my $newend = 0;
                   7526:             my $newstart = $now;
                   7527:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7528:             $changes{$action}{$newkey} = {
                   7529:                 type => 'public',
                   7530:                 time => {
                   7531:                     start => $newstart,
                   7532:                     end   => $newend,
                   7533:                 },
                   7534:             };
                   7535:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7536:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7537:             return $outcome;
                   7538:         }
                   7539:     } else {
                   7540:         return 'invalid';
                   7541:     }
                   7542: }
                   7543: 
1.745     raeburn  7544: #------------------------------------------------------Get Marked as Read Only
                   7545: 
                   7546: sub get_marked_as_readonly {
                   7547:     my ($domain,$user,$what,$group) = @_;
                   7548:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7549:     my @readonly_files;
1.629     banghart 7550:     my $cmp1=$what;
                   7551:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7552:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7553:         if (defined($group)) {
                   7554:             if ($file_name !~ m-^\Q$group\E/-) {
                   7555:                 next;
                   7556:             }
                   7557:         }
1.561     banghart 7558:         if (ref($value) eq "ARRAY"){
                   7559:             foreach my $stored_what (@{$value}) {
1.629     banghart 7560:                 my $cmp2=$stored_what;
1.759     albertel 7561:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7562:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7563:                 }
1.629     banghart 7564:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7565:                     push(@readonly_files, $file_name);
1.745     raeburn  7566:                     last;
1.563     banghart 7567:                 } elsif (!defined($what)) {
                   7568:                     push(@readonly_files, $file_name);
1.745     raeburn  7569:                     last;
1.561     banghart 7570:                 }
                   7571:             }
1.745     raeburn  7572:         }
1.561     banghart 7573:     }
                   7574:     return @readonly_files;
                   7575: }
1.577     banghart 7576: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7577: 
1.577     banghart 7578: sub get_marked_as_readonly_hash {
1.745     raeburn  7579:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7580:     my %readonly_files;
1.745     raeburn  7581:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7582:         if (defined($group)) {
                   7583:             if ($file_name !~ m-^\Q$group\E/-) {
                   7584:                 next;
                   7585:             }
                   7586:         }
1.577     banghart 7587:         if (ref($value) eq "ARRAY"){
                   7588:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7589:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7590:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7591:                         if ($lock_descriptor eq 'graded') {
                   7592:                             $readonly_files{$file_name} = 'graded';
                   7593:                         } elsif ($lock_descriptor eq 'handback') {
                   7594:                             $readonly_files{$file_name} = 'handback';
                   7595:                         } else {
                   7596:                             if (!exists($readonly_files{$file_name})) {
                   7597:                                 $readonly_files{$file_name} = 'locked';
                   7598:                             }
                   7599:                         }
1.745     raeburn  7600:                     }
1.750     banghart 7601:                 } 
1.577     banghart 7602:             }
                   7603:         } 
                   7604:     }
                   7605:     return %readonly_files;
                   7606: }
1.559     banghart 7607: # ------------------------------------------------------------ Unmark as Read Only
                   7608: 
                   7609: sub unmark_as_readonly {
1.629     banghart 7610:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7611:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7612:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7613:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7614:     my $symb_crs = $what;
                   7615:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7616:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7617:     my ($tmp)=keys(%current_permissions);
                   7618:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7619:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7620:     foreach my $file (@readonly_files) {
1.759     albertel 7621: 	my $clean_file = &declutter_portfile($file);
                   7622: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7623: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7624:         my @new_locks;
                   7625:         my @del_keys;
                   7626:         if (ref($current_locks) eq "ARRAY"){
                   7627:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7628:                 my $compare=$locker;
1.749     raeburn  7629:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7630:                     $compare=join('',@{$locker});
1.746     raeburn  7631:                     if ($compare ne $symb_crs) {
                   7632:                         push(@new_locks, $locker);
                   7633:                     }
1.563     banghart 7634:                 }
                   7635:             }
1.650     albertel 7636:             if (scalar(@new_locks) > 0) {
1.563     banghart 7637:                 $current_permissions{$file} = \@new_locks;
                   7638:             } else {
                   7639:                 push(@del_keys, $file);
1.613     albertel 7640:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7641:                 delete($current_permissions{$file});
1.563     banghart 7642:             }
                   7643:         }
1.561     banghart 7644:     }
1.613     albertel 7645:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7646:     return;
                   7647: }
1.512     banghart 7648: 
1.17      www      7649: # ------------------------------------------------------------ Directory lister
                   7650: 
                   7651: sub dirlist {
1.955     raeburn  7652:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7653:     $uri=~s/^\///;
                   7654:     $uri=~s/\/$//;
1.253     stredwic 7655:     my ($udom, $uname);
1.955     raeburn  7656:     if ($getuserdir) {
1.253     stredwic 7657:         $udom = $userdomain;
                   7658:         $uname = $username;
1.955     raeburn  7659:     } else {
                   7660:         (undef,$udom,$uname)=split(/\//,$uri);
                   7661:         if(defined($userdomain)) {
                   7662:             $udom = $userdomain;
                   7663:         }
                   7664:         if(defined($username)) {
                   7665:             $uname = $username;
                   7666:         }
1.253     stredwic 7667:     }
1.955     raeburn  7668:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7669: 
1.955     raeburn  7670:     $dirRoot = $perlvar{'lonDocRoot'};
                   7671:     if (defined($getpropath)) {
                   7672:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7673:         $dirRoot =~ s/\/$//;
1.955     raeburn  7674:     } elsif (defined($getuserdir)) {
                   7675:         my $subdir=$uname.'__';
                   7676:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7677:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7678:                    ."/$udom/$subdir/$uname";
                   7679:     } elsif (defined($alternateRoot)) {
                   7680:         $dirRoot = $alternateRoot;
1.751     banghart 7681:     }
1.253     stredwic 7682: 
                   7683:     if($udom) {
                   7684:         if($uname) {
1.955     raeburn  7685:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7686:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7687:                               .':'.&escape($uname).':'.&escape($udom),
                   7688:                               &homeserver($uname,$udom));
                   7689:             if ($listing eq 'unknown_cmd') {
                   7690:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7691:                                   &homeserver($uname,$udom));
                   7692:             } else {
                   7693:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7694:             }
1.605     matthew  7695:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7696:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7697: 				  &homeserver($uname,$udom));
1.605     matthew  7698:                 @listing_results = split(/:/,$listing);
                   7699:             } else {
                   7700:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7701:             }
                   7702:             return @listing_results;
1.955     raeburn  7703:         } elsif(!$alternateRoot) {
1.800     albertel 7704:             my %allusers;
1.841     albertel 7705: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7706:  	    foreach my $tryserver (keys(%servers)) {
                   7707:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7708:                                   &escape($udom),$tryserver);
                   7709:                 if ($listing eq 'unknown_cmd') {
                   7710: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7711: 				      $udom, $tryserver);
                   7712:                 } else {
                   7713:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7714:                 }
1.841     albertel 7715: 		if ($listing eq 'unknown_cmd') {
                   7716: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7717: 				      $udom, $tryserver);
                   7718: 		    @listing_results = split(/:/,$listing);
                   7719: 		} else {
                   7720: 		    @listing_results =
                   7721: 			map { &unescape($_); } split(/:/,$listing);
                   7722: 		}
                   7723: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7724: 		    $listing_results[0] ne 'empty'       &&
                   7725: 		    $listing_results[0] ne 'con_lost') {
                   7726: 		    foreach my $line (@listing_results) {
                   7727: 			my ($entry) = split(/&/,$line,2);
                   7728: 			$allusers{$entry} = 1;
                   7729: 		    }
                   7730: 		}
1.253     stredwic 7731:             }
                   7732:             my $alluserstr='';
1.800     albertel 7733:             foreach my $user (sort(keys(%allusers))) {
                   7734:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7735:             }
                   7736:             $alluserstr=~s/:$//;
                   7737:             return split(/:/,$alluserstr);
                   7738:         } else {
1.800     albertel 7739:             return ('missing user name');
1.253     stredwic 7740:         }
1.955     raeburn  7741:     } elsif(!defined($getpropath)) {
1.841     albertel 7742:         my @all_domains = sort(&all_domains());
1.955     raeburn  7743:         foreach my $domain (@all_domains) {
                   7744:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7745:         }
                   7746:         return @all_domains;
                   7747:     } else {
1.800     albertel 7748:         return ('missing domain');
1.275     stredwic 7749:     }
                   7750: }
                   7751: 
                   7752: # --------------------------------------------- GetFileTimestamp
                   7753: # This function utilizes dirlist and returns the date stamp for
                   7754: # when it was last modified.  It will also return an error of -1
                   7755: # if an error occurs
                   7756: 
                   7757: sub GetFileTimestamp {
1.955     raeburn  7758:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7759:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7760:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7761:     my ($fileStat) = 
                   7762:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7763:                                  undef,$getuserdir);
1.275     stredwic 7764:     my @stats = split('&', $fileStat);
                   7765:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7766:         # @stats contains first the filename, then the stat output
                   7767:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7768:     } else {
                   7769:         return -1;
1.253     stredwic 7770:     }
1.26      www      7771: }
                   7772: 
1.712     albertel 7773: sub stat_file {
                   7774:     my ($uri) = @_;
1.787     albertel 7775:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7776: 
1.955     raeburn  7777:     my ($udom,$uname,$file);
1.712     albertel 7778:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7779: 	($udom,$uname,$file) =
1.811     albertel 7780: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7781: 	$file = 'userfiles/'.$file;
                   7782:     }
                   7783:     if ($uri =~ m-^/res/-) {
                   7784: 	($udom,$uname) = 
1.807     albertel 7785: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7786: 	$file = $uri;
                   7787:     }
                   7788: 
                   7789:     if (!$udom || !$uname || !$file) {
                   7790: 	# unable to handle the uri
                   7791: 	return ();
                   7792:     }
1.956     raeburn  7793:     my $getpropath;
                   7794:     if ($file =~ /^userfiles\//) {
                   7795:         $getpropath = 1;
                   7796:     }
1.955     raeburn  7797:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7798:     my @stats = split('&', $result);
1.721     banghart 7799:     
1.712     albertel 7800:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7801: 	shift(@stats); #filename is first
                   7802: 	return @stats;
                   7803:     }
                   7804:     return ();
                   7805: }
                   7806: 
1.26      www      7807: # -------------------------------------------------------- Value of a Condition
                   7808: 
1.713     albertel 7809: # gets the value of a specific preevaluated condition
                   7810: #    stored in the string  $env{user.state.<cid>}
                   7811: # or looks up a condition reference in the bighash and if if hasn't
                   7812: # already been evaluated recurses into docondval to get the value of
                   7813: # the condition, then memoizing it to 
                   7814: #   $env{user.state.<cid>.<condition>}
1.40      www      7815: sub directcondval {
                   7816:     my $number=shift;
1.620     albertel 7817:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7818: 	&Apache::lonuserstate::evalstate();
                   7819:     }
1.713     albertel 7820:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7821: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7822:     } elsif ($number =~ /^_/) {
                   7823: 	my $sub_condition;
                   7824: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7825: 		&GDBM_READER(),0640)) {
                   7826: 	    $sub_condition=$bighash{'conditions'.$number};
                   7827: 	    untie(%bighash);
                   7828: 	}
                   7829: 	my $value = &docondval($sub_condition);
1.949     raeburn  7830: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7831: 	return $value;
                   7832:     }
1.620     albertel 7833:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7834:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7835:     } else {
                   7836:        return 2;
                   7837:     }
                   7838: }
                   7839: 
1.713     albertel 7840: # get the collection of conditions for this resource
1.26      www      7841: sub condval {
                   7842:     my $condidx=shift;
1.54      www      7843:     my $allpathcond='';
1.713     albertel 7844:     foreach my $cond (split(/\|/,$condidx)) {
                   7845: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7846: 	    $allpathcond.=
                   7847: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7848: 	}
1.191     harris41 7849:     }
1.54      www      7850:     $allpathcond=~s/\|$//;
1.713     albertel 7851:     return &docondval($allpathcond);
                   7852: }
                   7853: 
                   7854: #evaluates an expression of conditions
                   7855: sub docondval {
                   7856:     my ($allpathcond) = @_;
                   7857:     my $result=0;
                   7858:     if ($env{'request.course.id'}
                   7859: 	&& defined($allpathcond)) {
                   7860: 	my $operand='|';
                   7861: 	my @stack;
                   7862: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7863: 	    if ($chunk eq '(') {
                   7864: 		push @stack,($operand,$result);
                   7865: 	    } elsif ($chunk eq ')') {
                   7866: 		my $before=pop @stack;
                   7867: 		if (pop @stack eq '&') {
                   7868: 		    $result=$result>$before?$before:$result;
                   7869: 		} else {
                   7870: 		    $result=$result>$before?$result:$before;
                   7871: 		}
                   7872: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7873: 		$operand=$chunk;
                   7874: 	    } else {
                   7875: 		my $new=directcondval($chunk);
                   7876: 		if ($operand eq '&') {
                   7877: 		    $result=$result>$new?$new:$result;
                   7878: 		} else {
                   7879: 		    $result=$result>$new?$result:$new;
                   7880: 		}
                   7881: 	    }
                   7882: 	}
1.26      www      7883:     }
                   7884:     return $result;
1.421     albertel 7885: }
                   7886: 
                   7887: # ---------------------------------------------------- Devalidate courseresdata
                   7888: 
                   7889: sub devalidatecourseresdata {
                   7890:     my ($coursenum,$coursedomain)=@_;
                   7891:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7892:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7893: }
                   7894: 
1.763     www      7895: 
1.200     www      7896: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7897: #
                   7898: #  Parameters:
                   7899: #      $coursenum    - Number of the course.
                   7900: #      $coursedomain - Domain at which the course was created.
                   7901: #  Returns:
                   7902: #     A hash of the course parameters along (I think) with timestamps
                   7903: #     and version info.
1.877     foxr     7904: 
1.624     albertel 7905: sub get_courseresdata {
                   7906:     my ($coursenum,$coursedomain)=@_;
1.200     www      7907:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7908:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7909:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7910:     my %dumpreply;
1.417     albertel 7911:     unless (defined($cached)) {
1.624     albertel 7912: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7913: 	$result=\%dumpreply;
1.251     albertel 7914: 	my ($tmp) = keys(%dumpreply);
                   7915: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7916: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7917: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7918: 	    return $tmp;
1.416     albertel 7919: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7920: 	    $result=undef;
1.599     albertel 7921: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7922: 	}
                   7923:     }
1.624     albertel 7924:     return $result;
                   7925: }
                   7926: 
1.633     albertel 7927: sub devalidateuserresdata {
                   7928:     my ($uname,$udom)=@_;
                   7929:     my $hashid="$udom:$uname";
                   7930:     &devalidate_cache_new('userres',$hashid);
                   7931: }
                   7932: 
1.624     albertel 7933: sub get_userresdata {
                   7934:     my ($uname,$udom)=@_;
                   7935:     #most student don\'t have any data set, check if there is some data
                   7936:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7937: 
                   7938:     my $hashid="$udom:$uname";
                   7939:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7940:     if (!defined($cached)) {
                   7941: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7942: 	$result=\%resourcedata;
                   7943: 	&do_cache_new('userres',$hashid,$result,600);
                   7944:     }
                   7945:     my ($tmp)=keys(%$result);
                   7946:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7947: 	return $result;
                   7948:     }
                   7949:     #error 2 occurs when the .db doesn't exist
                   7950:     if ($tmp!~/error: 2 /) {
1.672     albertel 7951: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7952: 		 " Trying to get resource data for ".
                   7953: 		 $uname." at ".$udom.": ".
                   7954: 		 $tmp."</font>");
                   7955:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7956: 	#&EXT_cache_set($udom,$uname);
                   7957: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7958: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7959:     }
                   7960:     return $tmp;
                   7961: }
1.879     foxr     7962: #----------------------------------------------- resdata - return resource data
                   7963: #  Purpose:
                   7964: #    Return resource data for either users or for a course.
                   7965: #  Parameters:
                   7966: #     $name      - Course/user name.
                   7967: #     $domain    - Name of the domain the user/course is registered on.
                   7968: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7969: #     @which     - Array of names of resources desired.
                   7970: #  Returns:
                   7971: #     The value of the first reasource in @which that is found in the
                   7972: #     resource hash.
                   7973: #  Exceptional Conditions:
                   7974: #     If the $type passed in is not valid (not the string 'course' or 
                   7975: #     'user', an undefined  reference is returned.
                   7976: #     If none of the resources are found, an undef is returned
1.624     albertel 7977: sub resdata {
                   7978:     my ($name,$domain,$type,@which)=@_;
                   7979:     my $result;
                   7980:     if ($type eq 'course') {
                   7981: 	$result=&get_courseresdata($name,$domain);
                   7982:     } elsif ($type eq 'user') {
                   7983: 	$result=&get_userresdata($name,$domain);
                   7984:     }
                   7985:     if (!ref($result)) { return $result; }    
1.251     albertel 7986:     foreach my $item (@which) {
1.927     albertel 7987: 	if (defined($result->{$item->[0]})) {
                   7988: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7989: 	}
1.250     albertel 7990:     }
1.291     albertel 7991:     return undef;
1.200     www      7992: }
                   7993: 
1.379     matthew  7994: #
                   7995: # EXT resource caching routines
                   7996: #
                   7997: 
                   7998: sub clear_EXT_cache_status {
1.383     albertel 7999:     &delenv('cache.EXT.');
1.379     matthew  8000: }
                   8001: 
                   8002: sub EXT_cache_status {
                   8003:     my ($target_domain,$target_user) = @_;
1.383     albertel 8004:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8005:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8006:         # We know already the user has no data
                   8007:         return 1;
                   8008:     } else {
                   8009:         return 0;
                   8010:     }
                   8011: }
                   8012: 
                   8013: sub EXT_cache_set {
                   8014:     my ($target_domain,$target_user) = @_;
1.383     albertel 8015:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8016:     #&appenv({$cachename => time});
1.379     matthew  8017: }
                   8018: 
1.28      www      8019: # --------------------------------------------------------- Value of a Variable
1.58      www      8020: sub EXT {
1.715     albertel 8021: 
1.395     albertel 8022:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8023:     unless ($varname) { return ''; }
1.218     albertel 8024:     #get real user name/domain, courseid and symb
                   8025:     my $courseid;
1.359     albertel 8026:     my $publicuser;
1.427     www      8027:     if ($symbparm) {
                   8028: 	$symbparm=&get_symb_from_alias($symbparm);
                   8029:     }
1.218     albertel 8030:     if (!($uname && $udom)) {
1.790     albertel 8031:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8032:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8033:     } else {
1.620     albertel 8034: 	$courseid=$env{'request.course.id'};
1.218     albertel 8035:     }
1.48      www      8036:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8037:     my $rest;
1.320     albertel 8038:     if (defined($therest[0])) {
1.48      www      8039:        $rest=join('.',@therest);
                   8040:     } else {
                   8041:        $rest='';
                   8042:     }
1.320     albertel 8043: 
1.57      www      8044:     my $qualifierrest=$qualifier;
                   8045:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8046:     my $spacequalifierrest=$space;
                   8047:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8048:     if ($realm eq 'user') {
1.48      www      8049: # --------------------------------------------------------------- user.resource
                   8050: 	if ($space eq 'resource') {
1.651     albertel 8051: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8052: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8053: 		 &&
1.744     albertel 8054: 		 ($symbparm eq &symbread()) ) {	
                   8055: 		# if we are in the middle of processing the resource the
                   8056: 		# get the value we are planning on committing
                   8057:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8058:                     return $Apache::lonhomework::results{$qualifierrest};
                   8059:                 } else {
                   8060:                     return $Apache::lonhomework::history{$qualifierrest};
                   8061:                 }
1.335     albertel 8062: 	    } else {
1.359     albertel 8063: 		my %restored;
1.620     albertel 8064: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8065: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8066: 		} else {
                   8067: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8068: 		}
1.335     albertel 8069: 		return $restored{$qualifierrest};
                   8070: 	    }
1.48      www      8071: # ----------------------------------------------------------------- user.access
                   8072:         } elsif ($space eq 'access') {
1.218     albertel 8073: 	    # FIXME - not supporting calls for a specific user
1.48      www      8074:             return &allowed($qualifier,$rest);
                   8075: # ------------------------------------------ user.preferences, user.environment
                   8076:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8077: 	    if (($uname eq $env{'user.name'}) &&
                   8078: 		($udom eq $env{'user.domain'})) {
                   8079: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8080: 	    } else {
1.359     albertel 8081: 		my %returnhash;
                   8082: 		if (!$publicuser) {
                   8083: 		    %returnhash=&userenvironment($udom,$uname,
                   8084: 						 $qualifierrest);
                   8085: 		}
1.218     albertel 8086: 		return $returnhash{$qualifierrest};
                   8087: 	    }
1.48      www      8088: # ----------------------------------------------------------------- user.course
                   8089:         } elsif ($space eq 'course') {
1.218     albertel 8090: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8091:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8092: # ------------------------------------------------------------------- user.role
                   8093:         } elsif ($space eq 'role') {
1.218     albertel 8094: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8095:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8096:             if ($qualifier eq 'value') {
                   8097: 		return $role;
                   8098:             } elsif ($qualifier eq 'extent') {
                   8099:                 return $where;
                   8100:             }
                   8101: # ----------------------------------------------------------------- user.domain
                   8102:         } elsif ($space eq 'domain') {
1.218     albertel 8103:             return $udom;
1.48      www      8104: # ------------------------------------------------------------------- user.name
                   8105:         } elsif ($space eq 'name') {
1.218     albertel 8106:             return $uname;
1.48      www      8107: # ---------------------------------------------------- Any other user namespace
1.29      www      8108:         } else {
1.359     albertel 8109: 	    my %reply;
                   8110: 	    if (!$publicuser) {
                   8111: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8112: 	    }
                   8113: 	    return $reply{$qualifierrest};
1.48      www      8114:         }
1.236     www      8115:     } elsif ($realm eq 'query') {
                   8116: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8117:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8118: 						[$spacequalifierrest]);
1.620     albertel 8119: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8120:    } elsif ($realm eq 'request') {
1.48      www      8121: # ------------------------------------------------------------- request.browser
                   8122:         if ($space eq 'browser') {
1.430     www      8123: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8124: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8125: 		    return 1;
                   8126: 		} else {
                   8127: 		    return 0;
                   8128: 		}
                   8129: 	    } else {
1.620     albertel 8130: 		return $env{'browser.'.$qualifier};
1.430     www      8131: 	    }
1.57      www      8132: # ------------------------------------------------------------ request.filename
                   8133:         } else {
1.620     albertel 8134:             return $env{'request.'.$spacequalifierrest};
1.29      www      8135:         }
1.28      www      8136:     } elsif ($realm eq 'course') {
1.48      www      8137: # ---------------------------------------------------------- course.description
1.620     albertel 8138:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8139:     } elsif ($realm eq 'resource') {
1.165     www      8140: 
1.620     albertel 8141: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8142: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8143: 	}
1.693     albertel 8144: 
                   8145: 	if ($space eq 'title') {
                   8146: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8147: 	    return &gettitle($symbparm);
                   8148: 	}
                   8149: 	
                   8150: 	if ($space eq 'map') {
                   8151: 	    my ($map) = &decode_symb($symbparm);
                   8152: 	    return &symbread($map);
                   8153: 	}
1.905     albertel 8154: 	if ($space eq 'filename') {
                   8155: 	    if ($symbparm) {
                   8156: 		return &clutter((&decode_symb($symbparm))[2]);
                   8157: 	    }
                   8158: 	    return &hreflocation('',$env{'request.filename'});
                   8159: 	}
1.693     albertel 8160: 
                   8161: 	my ($section, $group, @groups);
1.593     albertel 8162: 	my ($courselevelm,$courselevel);
1.539     albertel 8163: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8164: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8165: 
1.218     albertel 8166: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8167: 
1.60      www      8168: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8169: 	    my $symbp=$symbparm;
1.735     albertel 8170: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8171: 
                   8172: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8173: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8174: 
1.620     albertel 8175: 	    if (($env{'user.name'} eq $uname) &&
                   8176: 		($env{'user.domain'} eq $udom)) {
                   8177: 		$section=$env{'request.course.sec'};
1.733     raeburn  8178:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8179:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8180: 	    } else {
1.539     albertel 8181: 		if (! defined($usection)) {
1.551     albertel 8182: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8183: 		} else {
                   8184: 		    $section = $usection;
                   8185: 		}
1.733     raeburn  8186:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8187: 	    }
                   8188: 
                   8189: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8190: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8191: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8192: 
1.593     albertel 8193: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8194: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8195: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8196: 
1.60      www      8197: # ----------------------------------------------------------- first, check user
1.624     albertel 8198: 
                   8199: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8200: 				       ([$courselevelr,'resource'],
                   8201: 					[$courselevelm,'map'     ],
                   8202: 					[$courselevel, 'course'  ]));
1.931     albertel 8203: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8204: 
1.594     albertel 8205: # ------------------------------------------------ second, check some of course
1.684     raeburn  8206:             my $coursereply;
1.691     raeburn  8207:             if (@groups > 0) {
                   8208:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8209:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8210:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8211:             }
1.96      www      8212: 
1.684     raeburn  8213: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8214: 				  $env{'course.'.$courseid.'.domain'},
                   8215: 				  'course',
                   8216: 				  ([$seclevelr,   'resource'],
                   8217: 				   [$seclevelm,   'map'     ],
                   8218: 				   [$seclevel,    'course'  ],
                   8219: 				   [$courselevelr,'resource']));
                   8220: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8221: 
1.60      www      8222: # ------------------------------------------------------ third, check map parms
1.218     albertel 8223: 	    my %parmhash=();
                   8224: 	    my $thisparm='';
                   8225: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8226: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8227: 		    &GDBM_READER(),0640)) {
1.218     albertel 8228: 		$thisparm=$parmhash{$symbparm};
                   8229: 		untie(%parmhash);
                   8230: 	    }
1.927     albertel 8231: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8232: 	}
1.594     albertel 8233: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8234: 
1.218     albertel 8235: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8236: 	my $filename;
                   8237: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8238: 	if ($symbparm) {
1.409     www      8239: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8240: 	} else {
1.620     albertel 8241: 	    $filename=$env{'request.filename'};
1.282     albertel 8242: 	}
                   8243: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8244: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8245: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8246: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8247: 
1.927     albertel 8248: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8249: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8250: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8251: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8252: 				     $env{'course.'.$courseid.'.domain'},
                   8253: 				     'course',
1.927     albertel 8254: 				     ([$courselevelm,'map'   ],
                   8255: 				      [$courselevel, 'course']));
                   8256: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8257: 	}
1.145     www      8258: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8259: 	unless ($space eq '0') {
1.336     albertel 8260: 	    my @parts=split(/_/,$space);
                   8261: 	    my $id=pop(@parts);
                   8262: 	    my $part=join('_',@parts);
                   8263: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8264: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8265: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8266: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8267: 	}
1.395     albertel 8268: 	if ($recurse) { return undef; }
                   8269: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8270: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8271: # ---------------------------------------------------- Any other user namespace
                   8272:     } elsif ($realm eq 'environment') {
                   8273: # ----------------------------------------------------------------- environment
1.620     albertel 8274: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8275: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8276: 	} else {
1.770     albertel 8277: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8278: 		return '';
                   8279: 	    }
1.219     albertel 8280: 	    my %returnhash=&userenvironment($udom,$uname,
                   8281: 					    $spacequalifierrest);
                   8282: 	    return $returnhash{$spacequalifierrest};
                   8283: 	}
1.28      www      8284:     } elsif ($realm eq 'system') {
1.48      www      8285: # ----------------------------------------------------------------- system.time
                   8286: 	if ($space eq 'time') {
                   8287: 	    return time;
                   8288:         }
1.696     albertel 8289:     } elsif ($realm eq 'server') {
                   8290: # ----------------------------------------------------------------- system.time
                   8291: 	if ($space eq 'name') {
                   8292: 	    return $ENV{'SERVER_NAME'};
                   8293:         }
1.28      www      8294:     }
1.48      www      8295:     return '';
1.61      www      8296: }
                   8297: 
1.927     albertel 8298: sub get_reply {
                   8299:     my ($reply_value) = @_;
1.940     raeburn  8300:     if (ref($reply_value) eq 'ARRAY') {
                   8301:         if (wantarray) {
                   8302: 	    return @$reply_value;
                   8303:         }
                   8304:         return $reply_value->[0];
                   8305:     } else {
                   8306:         return $reply_value;
1.927     albertel 8307:     }
                   8308: }
                   8309: 
1.691     raeburn  8310: sub check_group_parms {
                   8311:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8312:     my @groupitems = ();
                   8313:     my $resultitem;
1.927     albertel 8314:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8315:     foreach my $group (@{$groups}) {
                   8316:         foreach my $level (@levels) {
1.927     albertel 8317:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8318:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8319:         }
                   8320:     }
                   8321:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8322:                             $env{'course.'.$courseid.'.domain'},
                   8323:                                      'course',@groupitems);
                   8324:     return $coursereply;
                   8325: }
                   8326: 
                   8327: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8328:     my ($courseid,@groups) = @_;
                   8329:     @groups = sort(@groups);
1.691     raeburn  8330:     return @groups;
                   8331: }
                   8332: 
1.395     albertel 8333: sub packages_tab_default {
                   8334:     my ($uri,$varname)=@_;
                   8335:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8336: 
                   8337:     my (@extension,@specifics,$do_default);
                   8338:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8339: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8340: 	if ($pack_type eq 'default') {
                   8341: 	    $do_default=1;
                   8342: 	} elsif ($pack_type eq 'extension') {
                   8343: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8344: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8345: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8346: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8347: 	}
                   8348:     }
                   8349:     # first look for a package that matches the requested part id
                   8350:     foreach my $package (@specifics) {
                   8351: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8352: 	next if ($pack_part ne $part);
                   8353: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8354: 	    return $packagetab{"$pack_type&$name&default"};
                   8355: 	}
                   8356:     }
                   8357:     # look for any possible matching non extension_ package
                   8358:     foreach my $package (@specifics) {
                   8359: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8360: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8361: 	    return $packagetab{"$pack_type&$name&default"};
                   8362: 	}
1.585     albertel 8363: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8364: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8365: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8366: 	}
                   8367:     }
1.738     albertel 8368:     # look for any posible extension_ match
                   8369:     foreach my $package (@extension) {
                   8370: 	my ($package,$pack_type)=@{$package};
                   8371: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8372: 	    return $packagetab{"$pack_type&$name&default"};
                   8373: 	}
                   8374: 	if (defined($packagetab{$package."&$name&default"})) {
                   8375: 	    return $packagetab{$package."&$name&default"};
                   8376: 	}
                   8377:     }
                   8378:     # look for a global default setting
                   8379:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8380: 	return $packagetab{"default&$name&default"};
                   8381:     }
1.395     albertel 8382:     return undef;
                   8383: }
                   8384: 
1.334     albertel 8385: sub add_prefix_and_part {
                   8386:     my ($prefix,$part)=@_;
                   8387:     my $keyroot;
                   8388:     if (defined($prefix) && $prefix !~ /^__/) {
                   8389: 	# prefix that has a part already
                   8390: 	$keyroot=$prefix;
                   8391:     } elsif (defined($prefix)) {
                   8392: 	# prefix that is missing a part
                   8393: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8394:     } else {
                   8395: 	# no prefix at all
                   8396: 	if (defined($part)) { $keyroot='_'.$part; }
                   8397:     }
                   8398:     return $keyroot;
                   8399: }
                   8400: 
1.71      www      8401: # ---------------------------------------------------------------- Get metadata
                   8402: 
1.599     albertel 8403: my %metaentry;
1.1070    www      8404: my %importedpartids;
1.71      www      8405: sub metadata {
1.176     www      8406:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8407:     $uri=&declutter($uri);
1.288     albertel 8408:     # if it is a non metadata possible uri return quickly
1.529     albertel 8409:     if (($uri eq '') || 
                   8410: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8411: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8412:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8413: 	return undef;
                   8414:     }
                   8415:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8416: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8417: 	return undef;
1.288     albertel 8418:     }
1.73      www      8419:     my $filename=$uri;
                   8420:     $uri=~s/\.meta$//;
1.172     www      8421: #
                   8422: # Is the metadata already cached?
1.177     www      8423: # Look at timestamp of caching
1.172     www      8424: # Everything is cached by the main uri, libraries are never directly cached
                   8425: #
1.428     albertel 8426:     if (!defined($liburi)) {
1.599     albertel 8427: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8428: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8429:     }
                   8430:     {
1.1069    www      8431: # Imported parts would go here
1.1070    www      8432:         my %importedids=();
                   8433:         my @origfileimportpartids=();
1.1069    www      8434:         my $importedparts=0;
1.172     www      8435: #
                   8436: # Is this a recursive call for a library?
                   8437: #
1.599     albertel 8438: #	if (! exists($metacache{$uri})) {
                   8439: #	    $metacache{$uri}={};
                   8440: #	}
1.924     albertel 8441: 	my $cachetime = 60*60;
1.171     www      8442:         if ($liburi) {
                   8443: 	    $liburi=&declutter($liburi);
                   8444:             $filename=$liburi;
1.401     bowersj2 8445:         } else {
1.599     albertel 8446: 	    &devalidate_cache_new('meta',$uri);
                   8447: 	    undef(%metaentry);
1.401     bowersj2 8448: 	}
1.140     www      8449:         my %metathesekeys=();
1.73      www      8450:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8451: 	my $metastring;
1.924     albertel 8452: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8453: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8454: 	    $metastring = 
1.929     albertel 8455: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8456: 					  ('grade_target' => 'meta'));
                   8457: 	    $cachetime = 1; # only want this cached in the child not long term
                   8458: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8459: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8460: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8461: 	    $metastring=&getfile($file);
1.489     albertel 8462: 	}
1.208     albertel 8463:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8464:         my $token;
1.140     www      8465:         undef %metathesekeys;
1.71      www      8466:         while ($token=$parser->get_token) {
1.339     albertel 8467: 	    if ($token->[0] eq 'S') {
                   8468: 		if (defined($token->[2]->{'package'})) {
1.172     www      8469: #
                   8470: # This is a package - get package info
                   8471: #
1.339     albertel 8472: 		    my $package=$token->[2]->{'package'};
                   8473: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8474: 		    if (defined($token->[2]->{'id'})) { 
                   8475: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8476: 		    }
1.599     albertel 8477: 		    if ($metaentry{':packages'}) {
                   8478: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8479: 		    } else {
1.599     albertel 8480: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8481: 		    }
1.736     albertel 8482: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8483: 			my $part=$keyroot;
                   8484: 			$part=~s/^\_//;
1.736     albertel 8485: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8486: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8487: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8488: 			    # ignore package.tab specified default values
                   8489:                             # here &package_tab_default() will fetch those
                   8490: 			    if ($subp eq 'default') { next; }
1.736     albertel 8491: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8492: 			    my $unikey;
                   8493: 			    if ($pack =~ /_0$/) {
                   8494: 				$unikey='parameter_0_'.$name;
                   8495: 				$part=0;
                   8496: 			    } else {
                   8497: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8498: 			    }
1.339     albertel 8499: 			    if ($subp eq 'display') {
                   8500: 				$value.=' [Part: '.$part.']';
                   8501: 			    }
1.599     albertel 8502: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8503: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8504: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8505: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8506: 			    }
1.599     albertel 8507: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8508: 				$metaentry{':'.$unikey}=
                   8509: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8510: 			    }
1.339     albertel 8511: 			}
                   8512: 		    }
                   8513: 		} else {
1.172     www      8514: #
                   8515: # This is not a package - some other kind of start tag
1.339     albertel 8516: #
                   8517: 		    my $entry=$token->[1];
1.1068    www      8518: 		    my $unikey='';
1.175     www      8519: 
1.339     albertel 8520: 		    if ($entry eq 'import') {
1.175     www      8521: #
                   8522: # Importing a library here
1.339     albertel 8523: #
1.1067    www      8524:                         my $location=$parser->get_text('/import');
                   8525:                         my $dir=$filename;
                   8526:                         $dir=~s|[^/]*$||;
                   8527:                         $location=&filelocation($dir,$location);
1.1069    www      8528:                        
1.1068    www      8529:                         my $importmode=$token->[2]->{'importmode'};
                   8530:                         if ($importmode eq 'problem') {
1.1069    www      8531: # Import as problem/response
1.1068    www      8532:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8533:                         } elsif ($importmode eq 'part') {
                   8534: # Import as part(s)
1.1069    www      8535:                            $importedparts=1;
                   8536: # We need to get the original file and the imported file to get the part order correct
                   8537: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8538: # Load and inspect original file
1.1070    www      8539:                            if ($#origfileimportpartids<0) {
                   8540:                               undef(%importedpartids);
                   8541:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8542:                               my $origfile=&getfile($origfilelocation);
                   8543:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8544:                            }
                   8545: 
1.1069    www      8546: # Load and inspect imported file
                   8547:                            my $impfile=&getfile($location);
                   8548:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8549:                            if ($#impfilepartids>=0) {
                   8550: # This problem had parts
1.1070    www      8551:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8552:                            } else {
                   8553: # Importing by turning a single problem into a problem part
                   8554: # It gets the import-tags ID as part-ID
                   8555:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8556:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8557:                            }
1.1068    www      8558:                         } else {
                   8559: # Normal import
                   8560:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8561:                            if (defined($token->[2]->{'id'})) {
                   8562:                               $unikey.='_'.$token->[2]->{'id'};
                   8563:                            }
1.1067    www      8564:                         }
                   8565: 
1.339     albertel 8566: 			if ($depthcount<20) {
1.736     albertel 8567: 			    my $metadata = 
                   8568: 				&metadata($uri,'keys', $location,$unikey,
                   8569: 					  $depthcount+1);
                   8570: 			    foreach my $meta (split(',',$metadata)) {
                   8571: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8572: 				$metathesekeys{$meta}=1;
1.339     albertel 8573: 			    }
1.1068    www      8574: 			
                   8575:                         }
1.1067    www      8576: 		    } else {
                   8577: #
                   8578: # Not importing, some other kind of non-package, non-library start tag
                   8579: # 
                   8580:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8581:                         if (defined($token->[2]->{'id'})) {
                   8582:                             $unikey.='_'.$token->[2]->{'id'};
                   8583:                         }
1.339     albertel 8584: 			if (defined($token->[2]->{'name'})) { 
                   8585: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8586: 			}
                   8587: 			$metathesekeys{$unikey}=1;
1.736     albertel 8588: 			foreach my $param (@{$token->[3]}) {
                   8589: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8590: 				$token->[2]->{$param};
1.339     albertel 8591: 			}
                   8592: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8593: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8594: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8595: 		 # only ws inside the tag, and not in default, so use default
                   8596: 		 # as value
1.599     albertel 8597: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8598: 			} elsif ( $internaltext =~ /\S/ ) {
                   8599: 		  # something interesting inside the tag
                   8600: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8601: 			} else {
1.908     albertel 8602: 		  # no interesting values, don't set a default
1.339     albertel 8603: 			}
1.172     www      8604: # end of not-a-package not-a-library import
1.339     albertel 8605: 		    }
1.172     www      8606: # end of not-a-package start tag
1.339     albertel 8607: 		}
1.172     www      8608: # the next is the end of "start tag"
1.339     albertel 8609: 	    }
                   8610: 	}
1.483     albertel 8611: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8612: 	$extension = lc($extension);
                   8613: 	if ($extension eq 'htm') { $extension='html'; }
                   8614: 
1.737     albertel 8615: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8616: 	    #no specific packages #how's our extension
                   8617: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8618: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8619: 					 \%metathesekeys);
                   8620: 	}
1.883     albertel 8621: 
                   8622: 	if (!exists($metaentry{':packages'})
                   8623: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8624: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8625: 		#no specific packages well let's get default then
                   8626: 		if ($key!~/^default&/) { next; }
1.488     albertel 8627: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8628: 					     \%metathesekeys);
                   8629: 	    }
                   8630: 	}
1.338     www      8631: # are there custom rights to evaluate
1.599     albertel 8632: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8633: 
1.338     www      8634:     #
                   8635:     # Importing a rights file here
1.339     albertel 8636:     #
                   8637: 	    unless ($depthcount) {
1.599     albertel 8638: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8639: 		my $dir=$filename;
                   8640: 		$dir=~s|[^/]*$||;
                   8641: 		$location=&filelocation($dir,$location);
1.736     albertel 8642: 		my $rights_metadata =
                   8643: 		    &metadata($uri,'keys',$location,'_rights',
                   8644: 			      $depthcount+1);
                   8645: 		foreach my $rights (split(',',$rights_metadata)) {
                   8646: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8647: 		    $metathesekeys{$rights}=1;
1.339     albertel 8648: 		}
                   8649: 	    }
                   8650: 	}
1.737     albertel 8651: 	# uniqifiy package listing
                   8652: 	my %seen;
                   8653: 	my @uniq_packages =
                   8654: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8655: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8656: 
1.1070    www      8657:         if ($importedparts) {
                   8658: # We had imported parts and need to rebuild partorder
                   8659:            $metaentry{':partorder'}='';
                   8660:            $metathesekeys{'partorder'}=1;
                   8661:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8662:                if ($origfileimportpartids[$index] eq 'part') {
                   8663: # original part, part of the problem
                   8664:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8665:                } else {
                   8666: # we have imported parts at this position
                   8667:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8668:                }
                   8669:            }
                   8670:            $metaentry{':partorder'}=~s/^\,//;
                   8671:         }
                   8672: 
1.737     albertel 8673: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8674: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8675: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8676: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8677: # this is the end of "was not already recently cached
1.71      www      8678:     }
1.599     albertel 8679:     return $metaentry{':'.$what};
1.261     albertel 8680: }
                   8681: 
1.488     albertel 8682: sub metadata_create_package_def {
1.483     albertel 8683:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8684:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8685:     if ($subp eq 'default') { next; }
                   8686:     
1.599     albertel 8687:     if (defined($metaentry{':packages'})) {
                   8688: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8689:     } else {
1.599     albertel 8690: 	$metaentry{':packages'}=$package;
1.483     albertel 8691:     }
                   8692:     my $value=$packagetab{$key};
                   8693:     my $unikey;
                   8694:     $unikey='parameter_0_'.$name;
1.599     albertel 8695:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8696:     $$metathesekeys{$unikey}=1;
1.599     albertel 8697:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8698: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8699:     }
1.599     albertel 8700:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8701: 	$metaentry{':'.$unikey}=
                   8702: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8703:     }
                   8704: }
                   8705: 
1.261     albertel 8706: sub metadata_generate_part0 {
                   8707:     my ($metadata,$metacache,$uri) = @_;
                   8708:     my %allnames;
1.737     albertel 8709:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8710: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8711: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8712: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8713: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8714: 	    $allnames{$name}=$part;
                   8715: 	  }
                   8716: 	}
                   8717:     }
                   8718:     foreach my $name (keys(%allnames)) {
                   8719:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8720:       my $key=":parameter_0_$name";
1.261     albertel 8721:       $$metacache{"$key.part"}='0';
                   8722:       $$metacache{"$key.name"}=$name;
1.428     albertel 8723:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8724: 					   $allnames{$name}.'_'.$name.
                   8725: 					   '.type'};
1.428     albertel 8726:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8727: 			     '.display'};
1.644     www      8728:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8729:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8730:       $$metacache{"$key.display"}=$olddis;
                   8731:     }
1.71      www      8732: }
                   8733: 
1.764     albertel 8734: # ------------------------------------------------------ Devalidate title cache
                   8735: 
                   8736: sub devalidate_title_cache {
                   8737:     my ($url)=@_;
                   8738:     if (!$env{'request.course.id'}) { return; }
                   8739:     my $symb=&symbread($url);
                   8740:     if (!$symb) { return; }
                   8741:     my $key=$env{'request.course.id'}."\0".$symb;
                   8742:     &devalidate_cache_new('title',$key);
                   8743: }
                   8744: 
1.1014    droeschl 8745: # ------------------------------------------------- Get the title of a course
                   8746: 
                   8747: sub current_course_title {
                   8748:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8749: }
1.301     www      8750: # ------------------------------------------------- Get the title of a resource
                   8751: 
                   8752: sub gettitle {
                   8753:     my $urlsymb=shift;
                   8754:     my $symb=&symbread($urlsymb);
1.534     albertel 8755:     if ($symb) {
1.620     albertel 8756: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8757: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8758: 	if (defined($cached)) { 
                   8759: 	    return $result;
                   8760: 	}
1.534     albertel 8761: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8762: 	my $title='';
1.907     albertel 8763: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8764: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8765: 	} else {
                   8766: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8767: 		    &GDBM_READER(),0640)) {
                   8768: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8769: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8770: 		untie(%bighash);
                   8771: 	    }
1.534     albertel 8772: 	}
                   8773: 	$title=~s/\&colon\;/\:/gs;
                   8774: 	if ($title) {
1.599     albertel 8775: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8776: 	}
                   8777: 	$urlsymb=$url;
                   8778:     }
                   8779:     my $title=&metadata($urlsymb,'title');
                   8780:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8781:     return $title;
1.301     www      8782: }
1.613     albertel 8783: 
1.614     albertel 8784: sub get_slot {
                   8785:     my ($which,$cnum,$cdom)=@_;
                   8786:     if (!$cnum || !$cdom) {
1.790     albertel 8787: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8788: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8789: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8790:     }
1.703     albertel 8791:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8792:     my %slotinfo;
                   8793:     if (exists($remembered{$key})) {
                   8794: 	$slotinfo{$which} = $remembered{$key};
                   8795:     } else {
                   8796: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8797: 	&Apache::lonhomework::showhash(%slotinfo);
                   8798: 	my ($tmp)=keys(%slotinfo);
                   8799: 	if ($tmp=~/^error:/) { return (); }
                   8800: 	$remembered{$key} = $slotinfo{$which};
                   8801:     }
1.616     albertel 8802:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8803: 	return %{$slotinfo{$which}};
                   8804:     }
                   8805:     return $slotinfo{$which};
1.614     albertel 8806: }
1.31      www      8807: # ------------------------------------------------- Update symbolic store links
                   8808: 
                   8809: sub symblist {
                   8810:     my ($mapname,%newhash)=@_;
1.438     www      8811:     $mapname=&deversion(&declutter($mapname));
1.31      www      8812:     my %hash;
1.620     albertel 8813:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8814:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8815:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8816: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8817: 		next if ($url eq 'last_known'
                   8818: 			 && $env{'form.no_update_last_known'});
                   8819: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8820: 						    $newhash{$url}->[1],
                   8821: 						    $newhash{$url}->[0]);
1.191     harris41 8822:             }
1.31      www      8823:             if (untie(%hash)) {
                   8824: 		return 'ok';
                   8825:             }
                   8826:         }
                   8827:     }
                   8828:     return 'error';
1.212     www      8829: }
                   8830: 
                   8831: # --------------------------------------------------------------- Verify a symb
                   8832: 
                   8833: sub symbverify {
1.510     www      8834:     my ($symb,$thisurl)=@_;
                   8835:     my $thisfn=$thisurl;
1.439     www      8836:     $thisfn=&declutter($thisfn);
1.215     www      8837: # direct jump to resource in page or to a sequence - will construct own symbs
                   8838:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8839: # check URL part
1.409     www      8840:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8841: 
1.431     www      8842:     unless ($url eq $thisfn) { return 0; }
1.213     www      8843: 
1.216     www      8844:     $symb=&symbclean($symb);
1.510     www      8845:     $thisurl=&deversion($thisurl);
1.439     www      8846:     $thisfn=&deversion($thisfn);
1.213     www      8847: 
                   8848:     my %bighash;
                   8849:     my $okay=0;
1.431     www      8850: 
1.620     albertel 8851:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8852:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8853:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8854:             $thisurl =~ s/\?.+$//;
                   8855:         }
1.510     www      8856:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8857:         unless ($ids) { 
1.510     www      8858:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8859:         }
                   8860:         if ($ids) {
                   8861: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8862: 	    foreach my $id (split(/\,/,$ids)) {
                   8863: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8864:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8865:                    $symb =~ s/\?.+$//;
                   8866:                }
1.216     www      8867:                if (
                   8868:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8869:    eq $symb) { 
1.620     albertel 8870: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8871: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8872: 		       $okay=1; 
                   8873: 		   }
                   8874: 	       }
1.216     www      8875: 	   }
                   8876:         }
1.213     www      8877: 	untie(%bighash);
                   8878:     }
                   8879:     return $okay;
1.31      www      8880: }
                   8881: 
1.210     www      8882: # --------------------------------------------------------------- Clean-up symb
                   8883: 
                   8884: sub symbclean {
                   8885:     my $symb=shift;
1.568     albertel 8886:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8887: # remove version from map
                   8888:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8889: 
1.210     www      8890: # remove version from URL
                   8891:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8892: 
1.507     www      8893: # remove wrapper
                   8894: 
1.510     www      8895:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8896:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8897:     return $symb;
1.409     www      8898: }
                   8899: 
                   8900: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8901: 
                   8902: sub encode_symb {
                   8903:     my ($map,$resid,$url)=@_;
                   8904:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8905: }
1.409     www      8906: 
                   8907: sub decode_symb {
1.568     albertel 8908:     my $symb=shift;
                   8909:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8910:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8911:     return (&fixversion($map),$resid,&fixversion($url));
                   8912: }
                   8913: 
                   8914: sub fixversion {
                   8915:     my $fn=shift;
1.609     banghart 8916:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8917:     my %bighash;
                   8918:     my $uri=&clutter($fn);
1.620     albertel 8919:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8920: # is this cached?
1.599     albertel 8921:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8922:     if (defined($cached)) { return $result; }
                   8923: # unfortunately not cached, or expired
1.620     albertel 8924:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8925: 	    &GDBM_READER(),0640)) {
                   8926:  	if ($bighash{'version_'.$uri}) {
                   8927:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8928:  	    unless (($version eq 'mostrecent') || 
                   8929: 		    ($version==&getversion($uri))) {
1.440     www      8930:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8931:  	    }
                   8932:  	}
                   8933:  	untie %bighash;
1.413     www      8934:     }
1.599     albertel 8935:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8936: }
                   8937: 
                   8938: sub deversion {
                   8939:     my $url=shift;
                   8940:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8941:     return $url;
1.210     www      8942: }
                   8943: 
1.31      www      8944: # ------------------------------------------------------ Return symb list entry
                   8945: 
                   8946: sub symbread {
1.249     www      8947:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8948:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8949:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8950: # no filename provided? try from environment
1.44      www      8951:     unless ($thisfn) {
1.620     albertel 8952:         if ($env{'request.symb'}) {
                   8953: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8954: 	}
1.620     albertel 8955: 	$thisfn=$env{'request.filename'};
1.44      www      8956:     }
1.569     albertel 8957:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8958: # is that filename actually a symb? Verify, clean, and return
                   8959:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8960: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8961: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8962: 	}
1.242     www      8963:     }
1.44      www      8964:     $thisfn=declutter($thisfn);
1.31      www      8965:     my %hash;
1.37      www      8966:     my %bighash;
                   8967:     my $syval='';
1.620     albertel 8968:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8969:         my $targetfn = $thisfn;
1.609     banghart 8970:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8971:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8972:         }
1.687     albertel 8973: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8974: 	    $targetfn=$1;
                   8975: 	}
1.620     albertel 8976:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8977:                       &GDBM_READER(),0640)) {
1.481     raeburn  8978: 	    $syval=$hash{$targetfn};
1.37      www      8979:             untie(%hash);
                   8980:         }
                   8981: # ---------------------------------------------------------- There was an entry
                   8982:         if ($syval) {
1.601     albertel 8983: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8984: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8985: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8986: 		    #return $env{$cache_str}='';
1.601     albertel 8987: 		#}    
                   8988: 		#$syval.=$1;
                   8989: 	    #}
1.37      www      8990:         } else {
                   8991: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8992:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8993:                             &GDBM_READER(),0640)) {
1.37      www      8994: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8995:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8996:               unless ($ids) { 
                   8997:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8998:               }
                   8999:               unless ($ids) {
                   9000: # alias?
                   9001: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9002:               }
1.37      www      9003:               if ($ids) {
                   9004: # ------------------------------------------------------------------- Has ID(s)
                   9005:                  my @possibilities=split(/\,/,$ids);
1.39      www      9006:                  if ($#possibilities==0) {
                   9007: # ----------------------------------------------- There is only one possibility
1.37      www      9008: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9009: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9010: 						    $resid,$thisfn);
1.249     www      9011:                  } elsif (!$donotrecurse) {
1.39      www      9012: # ------------------------------------------ There is more than one possibility
                   9013:                      my $realpossible=0;
1.800     albertel 9014:                      foreach my $id (@possibilities) {
                   9015: 			 my $file=$bighash{'src_'.$id};
1.39      www      9016:                          if (&allowed('bre',$file)) {
1.800     albertel 9017:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9018:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9019: 				$realpossible++;
1.626     albertel 9020:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9021: 						    $resid,$thisfn);
1.39      www      9022:                             }
                   9023: 			 }
1.191     harris41 9024:                      }
1.39      www      9025: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9026:                  } else {
                   9027:                      $syval='';
1.37      www      9028:                  }
                   9029: 	      }
                   9030:               untie(%bighash)
1.481     raeburn  9031:            }
1.31      www      9032:         }
1.62      www      9033:         if ($syval) {
1.620     albertel 9034: 	    return $env{$cache_str}=$syval;
1.62      www      9035:         }
1.31      www      9036:     }
1.949     raeburn  9037:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9038:     return $env{$cache_str}='';
1.31      www      9039: }
                   9040: 
                   9041: # ---------------------------------------------------------- Return random seed
                   9042: 
1.32      www      9043: sub numval {
                   9044:     my $txt=shift;
                   9045:     $txt=~tr/A-J/0-9/;
                   9046:     $txt=~tr/a-j/0-9/;
                   9047:     $txt=~tr/K-T/0-9/;
                   9048:     $txt=~tr/k-t/0-9/;
                   9049:     $txt=~tr/U-Z/0-5/;
                   9050:     $txt=~tr/u-z/0-5/;
                   9051:     $txt=~s/\D//g;
1.564     albertel 9052:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9053:     return int($txt);
1.368     albertel 9054: }
                   9055: 
1.484     albertel 9056: sub numval2 {
                   9057:     my $txt=shift;
                   9058:     $txt=~tr/A-J/0-9/;
                   9059:     $txt=~tr/a-j/0-9/;
                   9060:     $txt=~tr/K-T/0-9/;
                   9061:     $txt=~tr/k-t/0-9/;
                   9062:     $txt=~tr/U-Z/0-5/;
                   9063:     $txt=~tr/u-z/0-5/;
                   9064:     $txt=~s/\D//g;
                   9065:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9066:     my $total;
                   9067:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9068:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9069:     return int($total);
                   9070: }
                   9071: 
1.575     albertel 9072: sub numval3 {
                   9073:     use integer;
                   9074:     my $txt=shift;
                   9075:     $txt=~tr/A-J/0-9/;
                   9076:     $txt=~tr/a-j/0-9/;
                   9077:     $txt=~tr/K-T/0-9/;
                   9078:     $txt=~tr/k-t/0-9/;
                   9079:     $txt=~tr/U-Z/0-5/;
                   9080:     $txt=~tr/u-z/0-5/;
                   9081:     $txt=~s/\D//g;
                   9082:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9083:     my $total;
                   9084:     foreach my $val (@txts) { $total+=$val; }
                   9085:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9086:     return $total;
                   9087: }
                   9088: 
1.675     albertel 9089: sub digest {
                   9090:     my ($data)=@_;
                   9091:     my $digest=&Digest::MD5::md5($data);
                   9092:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9093:     my ($e,$f);
                   9094:     {
                   9095:         use integer;
                   9096:         $e=($a+$b);
                   9097:         $f=($c+$d);
                   9098:         if ($_64bit) {
                   9099:             $e=(($e<<32)>>32);
                   9100:             $f=(($f<<32)>>32);
                   9101:         }
                   9102:     }
                   9103:     if (wantarray) {
                   9104: 	return ($e,$f);
                   9105:     } else {
                   9106: 	my $g;
                   9107: 	{
                   9108: 	    use integer;
                   9109: 	    $g=($e+$f);
                   9110: 	    if ($_64bit) {
                   9111: 		$g=(($g<<32)>>32);
                   9112: 	    }
                   9113: 	}
                   9114: 	return $g;
                   9115:     }
                   9116: }
                   9117: 
1.368     albertel 9118: sub latest_rnd_algorithm_id {
1.675     albertel 9119:     return '64bit5';
1.366     albertel 9120: }
1.32      www      9121: 
1.503     albertel 9122: sub get_rand_alg {
                   9123:     my ($courseid)=@_;
1.790     albertel 9124:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9125:     if ($courseid) {
1.620     albertel 9126: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9127:     }
                   9128:     return &latest_rnd_algorithm_id();
                   9129: }
                   9130: 
1.562     albertel 9131: sub validCODE {
                   9132:     my ($CODE)=@_;
                   9133:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9134:     return 0;
                   9135: }
                   9136: 
1.491     albertel 9137: sub getCODE {
1.620     albertel 9138:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9139:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9140: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9141: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9142: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9143:     }
                   9144:     return undef;
                   9145: }
                   9146: 
1.31      www      9147: sub rndseed {
1.155     albertel 9148:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9149:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9150:     if (!defined($symb)) {
1.366     albertel 9151: 	unless ($symb=$wsymb) { return time; }
                   9152:     }
                   9153:     if (!$courseid) { $courseid=$wcourseid; }
                   9154:     if (!$domain) { $domain=$wdomain; }
                   9155:     if (!$username) { $username=$wusername }
1.503     albertel 9156:     my $which=&get_rand_alg();
1.803     albertel 9157: 
1.491     albertel 9158:     if (defined(&getCODE())) {
1.675     albertel 9159: 	if ($which eq '64bit5') {
                   9160: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9161: 	} elsif ($which eq '64bit4') {
1.575     albertel 9162: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9163: 	} else {
                   9164: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9165: 	}
1.675     albertel 9166:     } elsif ($which eq '64bit5') {
                   9167: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9168:     } elsif ($which eq '64bit4') {
                   9169: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9170:     } elsif ($which eq '64bit3') {
                   9171: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9172:     } elsif ($which eq '64bit2') {
                   9173: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9174:     } elsif ($which eq '64bit') {
                   9175: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9176:     }
                   9177:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9178: }
                   9179: 
                   9180: sub rndseed_32bit {
                   9181:     my ($symb,$courseid,$domain,$username)=@_;
                   9182:     {
                   9183: 	use integer;
                   9184: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9185: 	my $symbseed=numval($symb) << 22;
                   9186: 	my $namechck=unpack("%32C*",$username) << 17;
                   9187: 	my $nameseed=numval($username) << 12;
                   9188: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9189: 	my $courseseed=unpack("%32C*",$courseid);
                   9190: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9191: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9192: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9193: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9194: 	return $num;
                   9195:     }
                   9196: }
                   9197: 
                   9198: sub rndseed_64bit {
                   9199:     my ($symb,$courseid,$domain,$username)=@_;
                   9200:     {
                   9201: 	use integer;
                   9202: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9203: 	my $symbseed=numval($symb) << 10;
                   9204: 	my $namechck=unpack("%32S*",$username);
                   9205: 	
                   9206: 	my $nameseed=numval($username) << 21;
                   9207: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9208: 	my $courseseed=unpack("%32S*",$courseid);
                   9209: 	
                   9210: 	my $num1=$symbchck+$symbseed+$namechck;
                   9211: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9212: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9213: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9214: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9215: 	return "$num1,$num2";
1.155     albertel 9216:     }
1.366     albertel 9217: }
                   9218: 
1.443     albertel 9219: sub rndseed_64bit2 {
                   9220:     my ($symb,$courseid,$domain,$username)=@_;
                   9221:     {
                   9222: 	use integer;
                   9223: 	# strings need to be an even # of cahracters long, it it is odd the
                   9224:         # last characters gets thrown away
                   9225: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9226: 	my $symbseed=numval($symb) << 10;
                   9227: 	my $namechck=unpack("%32S*",$username.' ');
                   9228: 	
                   9229: 	my $nameseed=numval($username) << 21;
1.501     albertel 9230: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9231: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9232: 	
                   9233: 	my $num1=$symbchck+$symbseed+$namechck;
                   9234: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9235: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9236: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9237: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9238: 	return "$num1,$num2";
                   9239:     }
                   9240: }
                   9241: 
                   9242: sub rndseed_64bit3 {
                   9243:     my ($symb,$courseid,$domain,$username)=@_;
                   9244:     {
                   9245: 	use integer;
                   9246: 	# strings need to be an even # of cahracters long, it it is odd the
                   9247:         # last characters gets thrown away
                   9248: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9249: 	my $symbseed=numval2($symb) << 10;
                   9250: 	my $namechck=unpack("%32S*",$username.' ');
                   9251: 	
                   9252: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9253: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9254: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9255: 	
                   9256: 	my $num1=$symbchck+$symbseed+$namechck;
                   9257: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9258: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9259: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9260: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9261: 	
1.503     albertel 9262: 	return "$num1:$num2";
1.443     albertel 9263:     }
                   9264: }
                   9265: 
1.575     albertel 9266: sub rndseed_64bit4 {
                   9267:     my ($symb,$courseid,$domain,$username)=@_;
                   9268:     {
                   9269: 	use integer;
                   9270: 	# strings need to be an even # of cahracters long, it it is odd the
                   9271:         # last characters gets thrown away
                   9272: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9273: 	my $symbseed=numval3($symb) << 10;
                   9274: 	my $namechck=unpack("%32S*",$username.' ');
                   9275: 	
                   9276: 	my $nameseed=numval3($username) << 21;
                   9277: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9278: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9279: 	
                   9280: 	my $num1=$symbchck+$symbseed+$namechck;
                   9281: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9282: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9283: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9284: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9285: 	
                   9286: 	return "$num1:$num2";
                   9287:     }
                   9288: }
                   9289: 
1.675     albertel 9290: sub rndseed_64bit5 {
                   9291:     my ($symb,$courseid,$domain,$username)=@_;
                   9292:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9293:     return "$num1:$num2";
                   9294: }
                   9295: 
1.366     albertel 9296: sub rndseed_CODE_64bit {
                   9297:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9298:     {
1.366     albertel 9299: 	use integer;
1.443     albertel 9300: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9301: 	my $symbseed=numval2($symb);
1.491     albertel 9302: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9303: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9304: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9305: 	my $num1=$symbseed+$CODEchck;
                   9306: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9307: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9308: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9309: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9310: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9311: 	return "$num1:$num2";
1.366     albertel 9312:     }
                   9313: }
                   9314: 
1.575     albertel 9315: sub rndseed_CODE_64bit4 {
                   9316:     my ($symb,$courseid,$domain,$username)=@_;
                   9317:     {
                   9318: 	use integer;
                   9319: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9320: 	my $symbseed=numval3($symb);
                   9321: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9322: 	my $CODEseed=numval3(&getCODE());
                   9323: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9324: 	my $num1=$symbseed+$CODEchck;
                   9325: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9326: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9327: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9328: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9329: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9330: 	return "$num1:$num2";
                   9331:     }
                   9332: }
                   9333: 
1.675     albertel 9334: sub rndseed_CODE_64bit5 {
                   9335:     my ($symb,$courseid,$domain,$username)=@_;
                   9336:     my $code = &getCODE();
                   9337:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9338:     return "$num1:$num2";
                   9339: }
                   9340: 
1.366     albertel 9341: sub setup_random_from_rndseed {
                   9342:     my ($rndseed)=@_;
1.503     albertel 9343:     if ($rndseed =~/([,:])/) {
                   9344: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9345: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9346:     } else {
                   9347: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9348:     }
1.36      albertel 9349: }
                   9350: 
1.474     albertel 9351: sub latest_receipt_algorithm_id {
1.835     albertel 9352:     return 'receipt3';
1.474     albertel 9353: }
                   9354: 
1.480     www      9355: sub recunique {
                   9356:     my $fucourseid=shift;
                   9357:     my $unique;
1.835     albertel 9358:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9359: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9360: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9361:     } else {
                   9362: 	$unique=$perlvar{'lonReceipt'};
                   9363:     }
                   9364:     return unpack("%32C*",$unique);
                   9365: }
                   9366: 
                   9367: sub recprefix {
                   9368:     my $fucourseid=shift;
                   9369:     my $prefix;
1.835     albertel 9370:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9371: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9372: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9373:     } else {
                   9374: 	$prefix=$perlvar{'lonHostID'};
                   9375:     }
                   9376:     return unpack("%32C*",$prefix);
                   9377: }
                   9378: 
1.76      www      9379: sub ireceipt {
1.474     albertel 9380:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9381: 
                   9382:     my $return =&recprefix($fucourseid).'-';
                   9383: 
                   9384:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9385: 	$env{'request.state'} eq 'construct') {
                   9386: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9387: 	return $return;
                   9388:     }
                   9389: 
1.76      www      9390:     my $cuname=unpack("%32C*",$funame);
                   9391:     my $cudom=unpack("%32C*",$fudom);
                   9392:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9393:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9394:     my $cunique=&recunique($fucourseid);
1.474     albertel 9395:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9396:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9397: 
1.790     albertel 9398: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9399: 			       
                   9400: 	$return.= ($cunique%$cuname+
                   9401: 		   $cunique%$cudom+
                   9402: 		   $cusymb%$cuname+
                   9403: 		   $cusymb%$cudom+
                   9404: 		   $cucourseid%$cuname+
                   9405: 		   $cucourseid%$cudom+
                   9406: 		   $cpart%$cuname+
                   9407: 		   $cpart%$cudom);
                   9408:     } else {
                   9409: 	$return.= ($cunique%$cuname+
                   9410: 		   $cunique%$cudom+
                   9411: 		   $cusymb%$cuname+
                   9412: 		   $cusymb%$cudom+
                   9413: 		   $cucourseid%$cuname+
                   9414: 		   $cucourseid%$cudom);
                   9415:     }
                   9416:     return $return;
1.76      www      9417: }
                   9418: 
                   9419: sub receipt {
1.474     albertel 9420:     my ($part)=@_;
1.790     albertel 9421:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9422:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9423: }
1.260     ng       9424: 
1.790     albertel 9425: sub whichuser {
                   9426:     my ($passedsymb)=@_;
                   9427:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9428:     if (defined($env{'form.grade_symb'})) {
                   9429: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9430: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9431: 	if (!$allowed &&
                   9432: 	    exists($env{'request.course.sec'}) &&
                   9433: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9434: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9435: 			      '/'.$env{'request.course.sec'});
                   9436: 	}
                   9437: 	if ($allowed) {
                   9438: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9439: 	    $courseid=$tmp_courseid;
                   9440: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9441: 	    ($name)=&get_env_multiple('form.grade_username');
                   9442: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9443: 	}
                   9444:     }
                   9445:     if (!$passedsymb) {
                   9446: 	$symb=&symbread();
                   9447:     } else {
                   9448: 	$symb=$passedsymb;
                   9449:     }
                   9450:     $courseid=$env{'request.course.id'};
                   9451:     $domain=$env{'user.domain'};
                   9452:     $name=$env{'user.name'};
                   9453:     if ($name eq 'public' && $domain eq 'public') {
                   9454: 	if (!defined($env{'form.username'})) {
                   9455: 	    $env{'form.username'}.=time.rand(10000000);
                   9456: 	}
                   9457: 	$name.=$env{'form.username'};
                   9458:     }
                   9459:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9460: 
                   9461: }
                   9462: 
1.36      albertel 9463: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9464: # returns either the contents of the file or 
                   9465: # -1 if the file doesn't exist
1.481     raeburn  9466: #
                   9467: # if the target is a file that was uploaded via DOCS, 
                   9468: # a check will be made to see if a current copy exists on the local server,
                   9469: # if it does this will be served, otherwise a copy will be retrieved from
                   9470: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9471: # the local server.   
1.472     albertel 9472: 
1.36      albertel 9473: sub getfile {
1.538     albertel 9474:     my ($file) = @_;
1.609     banghart 9475:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9476:     &repcopy($file);
                   9477:     return &readfile($file);
                   9478: }
                   9479: 
                   9480: sub repcopy_userfile {
                   9481:     my ($file)=@_;
1.609     banghart 9482:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9483:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9484:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9485: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9486:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9487:     if (-e "$file") {
1.828     www      9488: # we already have a local copy, check it out
1.538     albertel 9489: 	my @fileinfo = stat($file);
1.828     www      9490: 	my $rtncode;
                   9491: 	my $info;
1.538     albertel 9492: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9493: 	if ($lwpresp ne 'ok') {
1.828     www      9494: # there is no such file anymore, even though we had a local copy
1.482     albertel 9495: 	    if ($rtncode eq '404') {
1.538     albertel 9496: 		unlink($file);
1.482     albertel 9497: 	    }
                   9498: 	    return -1;
                   9499: 	}
                   9500: 	if ($info < $fileinfo[9]) {
1.828     www      9501: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9502: 	    return 'ok';
1.828     www      9503: 	} else {
                   9504: # the file is outdated, get rid of it
                   9505: 	    unlink($file);
1.482     albertel 9506: 	}
1.828     www      9507:     }
                   9508: # one way or the other, at this point, we don't have the file
                   9509: # construct the correct path for the file
                   9510:     my @parts = ($cdom,$cnum); 
                   9511:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9512: 	push @parts, split(/\//,$1);
                   9513:     }
                   9514:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9515:     foreach my $part (@parts) {
                   9516: 	$path .= '/'.$part;
                   9517: 	if (!-e $path) {
                   9518: 	    mkdir($path,0770);
1.482     albertel 9519: 	}
                   9520:     }
1.828     www      9521: # now the path exists for sure
                   9522: # get a user agent
                   9523:     my $ua=new LWP::UserAgent;
                   9524:     my $transferfile=$file.'.in.transfer';
                   9525: # FIXME: this should flock
                   9526:     if (-e $transferfile) { return 'ok'; }
                   9527:     my $request;
                   9528:     $uri=~s/^\///;
1.980     raeburn  9529:     my $homeserver = &homeserver($cnum,$cdom);
                   9530:     my $protocol = $protocol{$homeserver};
                   9531:     $protocol = 'http' if ($protocol ne 'https');
                   9532:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9533:     my $response=$ua->request($request,$transferfile);
                   9534: # did it work?
                   9535:     if ($response->is_error()) {
                   9536: 	unlink($transferfile);
                   9537: 	&logthis("Userfile repcopy failed for $uri");
                   9538: 	return -1;
                   9539:     }
                   9540: # worked, rename the transfer file
                   9541:     rename($transferfile,$file);
1.607     raeburn  9542:     return 'ok';
1.481     raeburn  9543: }
                   9544: 
1.517     albertel 9545: sub tokenwrapper {
                   9546:     my $uri=shift;
1.980     raeburn  9547:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9548:     $uri=~s|^/||;
1.620     albertel 9549:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9550:     my $token=$1;
1.552     albertel 9551:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9552:     if ($udom && $uname && $file) {
                   9553: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9554:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9555:         my $homeserver = &homeserver($uname,$udom);
                   9556:         my $protocol = $protocol{$homeserver};
                   9557:         $protocol = 'http' if ($protocol ne 'https');
                   9558:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9559:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9560:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9561:     } else {
                   9562:         return '/adm/notfound.html';
                   9563:     }
                   9564: }
                   9565: 
1.828     www      9566: # call with reqtype HEAD: get last modification time
                   9567: # call with reqtype GET: get the file contents
                   9568: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9569: #
1.481     raeburn  9570: sub getuploaded {
                   9571:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9572:     $uri=~s/^\///;
1.980     raeburn  9573:     my $homeserver = &homeserver($cnum,$cdom);
                   9574:     my $protocol = $protocol{$homeserver};
                   9575:     $protocol = 'http' if ($protocol ne 'https');
                   9576:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9577:     my $ua=new LWP::UserAgent;
                   9578:     my $request=new HTTP::Request($reqtype,$uri);
                   9579:     my $response=$ua->request($request);
                   9580:     $$rtncode = $response->code;
1.482     albertel 9581:     if (! $response->is_success()) {
                   9582: 	return 'failed';
                   9583:     }      
                   9584:     if ($reqtype eq 'HEAD') {
1.486     www      9585: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9586:     } elsif ($reqtype eq 'GET') {
                   9587: 	$$info = $response->content;
1.472     albertel 9588:     }
1.482     albertel 9589:     return 'ok';
1.36      albertel 9590: }
                   9591: 
1.481     raeburn  9592: sub readfile {
                   9593:     my $file = shift;
                   9594:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9595:     my $fh;
                   9596:     open($fh,"<$file");
                   9597:     my $a='';
1.800     albertel 9598:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9599:     return $a;
                   9600: }
                   9601: 
1.36      albertel 9602: sub filelocation {
1.590     banghart 9603:     my ($dir,$file) = @_;
                   9604:     my $location;
                   9605:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9606: 
                   9607:     if ($file =~ m-^/adm/-) {
                   9608: 	$file=~s-^/adm/wrapper/-/-;
                   9609: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9610:     }
1.882     albertel 9611: 
1.590     banghart 9612:     if ($file=~m:^/~:) { # is a contruction space reference
                   9613:         $location = $file;
                   9614:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9615:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9616: 	# is a correct contruction space reference
                   9617:         $location = $file;
1.956     raeburn  9618:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9619:         $location = $file;
1.609     banghart 9620:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9621:         my ($udom,$uname,$filename)=
1.811     albertel 9622:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9623:         my $home=&homeserver($uname,$udom);
                   9624:         my $is_me=0;
                   9625:         my @ids=&current_machine_ids();
                   9626:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9627:         if ($is_me) {
1.955     raeburn  9628:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9629:         } else {
                   9630:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9631:   	      $udom.'/'.$uname.'/'.$filename;
                   9632:         }
1.882     albertel 9633:     } elsif ($file =~ m-^/adm/-) {
                   9634: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9635:     } else {
                   9636:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9637:         $file=~s:^/res/:/:;
                   9638:         if ( !( $file =~ m:^/:) ) {
                   9639:             $location = $dir. '/'.$file;
                   9640:         } else {
                   9641:             $location = '/home/httpd/html/res'.$file;
                   9642:         }
1.59      albertel 9643:     }
1.590     banghart 9644:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9645:     while ($location=~m{/\.\./}) {
                   9646: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9647: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9648: 	} else {
                   9649: 	    $location=~ s{/\.\./}{/}g;
                   9650: 	}
                   9651:     } #remove dir/..
1.590     banghart 9652:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9653:     return $location;
1.46      www      9654: }
1.36      albertel 9655: 
1.46      www      9656: sub hreflocation {
                   9657:     my ($dir,$file)=@_;
1.980     raeburn  9658:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9659: 	$file=filelocation($dir,$file);
1.700     albertel 9660:     } elsif ($file=~m-^/adm/-) {
                   9661: 	$file=~s-^/adm/wrapper/-/-;
                   9662: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9663:     }
                   9664:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9665: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9666:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9667: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9668:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9669: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9670: 	    -/uploaded/$1/$2/-x;
1.46      www      9671:     }
1.913     albertel 9672:     if ($file=~ m{^/userfiles/}) {
                   9673: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9674:     }
1.462     albertel 9675:     return $file;
1.465     albertel 9676: }
                   9677: 
                   9678: sub current_machine_domains {
1.853     albertel 9679:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9680: }
                   9681: 
                   9682: sub machine_domains {
                   9683:     my ($hostname) = @_;
1.465     albertel 9684:     my @domains;
1.838     albertel 9685:     my %hostname = &all_hostnames();
1.465     albertel 9686:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9687: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9688: 	if ($hostname eq $name) {
1.844     albertel 9689: 	    push(@domains,&host_domain($id));
1.465     albertel 9690: 	}
                   9691:     }
                   9692:     return @domains;
                   9693: }
                   9694: 
                   9695: sub current_machine_ids {
1.853     albertel 9696:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9697: }
                   9698: 
                   9699: sub machine_ids {
                   9700:     my ($hostname) = @_;
                   9701:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9702:     my @ids;
1.888     albertel 9703:     my %name_to_host = &all_names();
1.889     albertel 9704:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9705: 	return @{ $name_to_host{$hostname} };
                   9706:     }
                   9707:     return;
1.31      www      9708: }
                   9709: 
1.824     raeburn  9710: sub additional_machine_domains {
                   9711:     my @domains;
                   9712:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9713:     while( my $line = <$fh>) {
                   9714:         $line =~ s/\s//g;
                   9715:         push(@domains,$line);
                   9716:     }
                   9717:     return @domains;
                   9718: }
                   9719: 
                   9720: sub default_login_domain {
                   9721:     my $domain = $perlvar{'lonDefDomain'};
                   9722:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9723:     foreach my $posdom (&current_machine_domains(),
                   9724:                         &additional_machine_domains()) {
                   9725:         if (lc($posdom) eq lc($testdomain)) {
                   9726:             $domain=$posdom;
                   9727:             last;
                   9728:         }
                   9729:     }
                   9730:     return $domain;
                   9731: }
                   9732: 
1.31      www      9733: # ------------------------------------------------------------- Declutters URLs
                   9734: 
                   9735: sub declutter {
                   9736:     my $thisfn=shift;
1.569     albertel 9737:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9738:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9739:     $thisfn=~s/^\///;
1.697     albertel 9740:     $thisfn=~s|^adm/wrapper/||;
                   9741:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9742:     $thisfn=~s/^res\///;
1.1032    raeburn  9743:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9744:         $thisfn=~s/\?.+$//;
                   9745:     }
1.268     www      9746:     return $thisfn;
                   9747: }
                   9748: 
                   9749: # ------------------------------------------------------------- Clutter up URLs
                   9750: 
                   9751: sub clutter {
                   9752:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9753:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9754: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9755:        $thisfn='/res'.$thisfn; 
                   9756:     }
1.1031    raeburn  9757:     if ($thisfn !~m|^/adm|) {
                   9758: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9759: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9760: 	} else {
                   9761: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9762: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9763: 	    if ($embstyle eq 'ssi'
                   9764: 		|| ($embstyle eq 'hdn')
                   9765: 		|| ($embstyle eq 'rat')
                   9766: 		|| ($embstyle eq 'prv')
                   9767: 		|| ($embstyle eq 'ign')) {
                   9768: 		#do nothing with these
                   9769: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9770: 		|| ($embstyle eq 'emb')
                   9771: 		|| ($embstyle eq 'wrp')) {
                   9772: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9773: 	    } elsif ($embstyle eq 'unk'
                   9774: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9775: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9776: 	    } else {
1.718     www      9777: #		&logthis("Got a blank emb style");
1.695     albertel 9778: 	    }
1.694     albertel 9779: 	}
                   9780:     }
1.31      www      9781:     return $thisfn;
1.12      www      9782: }
                   9783: 
1.787     albertel 9784: sub clutter_with_no_wrapper {
                   9785:     my $uri = &clutter(shift);
                   9786:     if ($uri =~ m-^/adm/-) {
                   9787: 	$uri =~ s-^/adm/wrapper/-/-;
                   9788: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9789:     }
                   9790:     return $uri;
                   9791: }
                   9792: 
1.557     albertel 9793: sub freeze_escape {
                   9794:     my ($value)=@_;
                   9795:     if (ref($value)) {
                   9796: 	$value=&nfreeze($value);
                   9797: 	return '__FROZEN__'.&escape($value);
                   9798:     }
                   9799:     return &escape($value);
                   9800: }
                   9801: 
1.11      www      9802: 
1.557     albertel 9803: sub thaw_unescape {
                   9804:     my ($value)=@_;
                   9805:     if ($value =~ /^__FROZEN__/) {
                   9806: 	substr($value,0,10,undef);
                   9807: 	$value=&unescape($value);
                   9808: 	return &thaw($value);
                   9809:     }
                   9810:     return &unescape($value);
                   9811: }
                   9812: 
1.436     albertel 9813: sub correct_line_ends {
                   9814:     my ($result)=@_;
                   9815:     $$result =~s/\r\n/\n/mg;
                   9816:     $$result =~s/\r/\n/mg;
1.415     albertel 9817: }
1.1       albertel 9818: # ================================================================ Main Program
                   9819: 
1.184     www      9820: sub goodbye {
1.204     albertel 9821:    &logthis("Starting Shut down");
1.443     albertel 9822: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9823:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9824: #converted
1.599     albertel 9825: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9826:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9827: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9828: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9829: #1.1 only
1.870     albertel 9830: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9831: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9832: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9833: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9834:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9835:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9836:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9837:    &flushcourselogs();
                   9838:    &logthis("Shutting down");
                   9839: }
                   9840: 
1.852     albertel 9841: sub get_dns {
1.869     albertel 9842:     my ($url,$func,$ignore_cache) = @_;
                   9843:     if (!$ignore_cache) {
                   9844: 	my ($content,$cached)=
                   9845: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9846: 	if ($cached) {
                   9847: 	    &$func($content);
                   9848: 	    return;
                   9849: 	}
                   9850:     }
                   9851: 
                   9852:     my %alldns;
1.852     albertel 9853:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9854:     foreach my $dns (<$config>) {
                   9855: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9856:         my $line = $1;
                   9857:         my ($host,$protocol) = split(/:/,$line);
                   9858:         if ($protocol ne 'https') {
                   9859:             $protocol = 'http';
                   9860:         }
                   9861: 	$alldns{$host} = $protocol;
1.869     albertel 9862:     }
                   9863:     while (%alldns) {
                   9864: 	my ($dns) = keys(%alldns);
1.852     albertel 9865: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9866: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9867: 	my $response=$ua->request($request);
1.979     raeburn  9868:         delete($alldns{$dns});
1.852     albertel 9869: 	next if ($response->is_error());
                   9870: 	my @content = split("\n",$response->content);
1.869     albertel 9871: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9872: 	&$func(\@content);
1.869     albertel 9873: 	return;
1.852     albertel 9874:     }
                   9875:     close($config);
1.871     albertel 9876:     my $which = (split('/',$url))[3];
                   9877:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9878:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9879:     my @content = <$config>;
                   9880:     &$func(\@content);
                   9881:     return;
1.852     albertel 9882: }
1.327     albertel 9883: # ------------------------------------------------------------ Read domain file
                   9884: {
1.852     albertel 9885:     my $loaded;
1.846     albertel 9886:     my %domain;
                   9887: 
1.852     albertel 9888:     sub parse_domain_tab {
                   9889: 	my ($lines) = @_;
                   9890: 	foreach my $line (@$lines) {
                   9891: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9892: 
1.846     albertel 9893: 	    chomp($line);
1.852     albertel 9894: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9895: 	    my %this_domain;
                   9896: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9897: 			       'lang_def', 'city', 'longi', 'lati',
                   9898: 			       'primary') {
                   9899: 		$this_domain{$field} = shift(@elements);
                   9900: 	    }
                   9901: 	    $domain{$name} = \%this_domain;
1.852     albertel 9902: 	}
                   9903:     }
1.864     albertel 9904: 
                   9905:     sub reset_domain_info {
                   9906: 	undef($loaded);
                   9907: 	undef(%domain);
                   9908:     }
                   9909: 
1.852     albertel 9910:     sub load_domain_tab {
1.869     albertel 9911: 	my ($ignore_cache) = @_;
                   9912: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9913: 	my $fh;
                   9914: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9915: 	    my @lines = <$fh>;
                   9916: 	    &parse_domain_tab(\@lines);
1.448     albertel 9917: 	}
1.852     albertel 9918: 	close($fh);
                   9919: 	$loaded = 1;
1.327     albertel 9920:     }
1.846     albertel 9921: 
                   9922:     sub domain {
1.852     albertel 9923: 	&load_domain_tab() if (!$loaded);
                   9924: 
1.846     albertel 9925: 	my ($name,$what) = @_;
                   9926: 	return if ( !exists($domain{$name}) );
                   9927: 
                   9928: 	if (!$what) {
                   9929: 	    return $domain{$name}{'description'};
                   9930: 	}
                   9931: 	return $domain{$name}{$what};
                   9932:     }
1.974     raeburn  9933: 
                   9934:     sub domain_info {
                   9935:         &load_domain_tab() if (!$loaded);
                   9936:         return %domain;
                   9937:     }
                   9938: 
1.327     albertel 9939: }
                   9940: 
                   9941: 
1.1       albertel 9942: # ------------------------------------------------------------- Read hosts file
                   9943: {
1.838     albertel 9944:     my %hostname;
1.844     albertel 9945:     my %hostdom;
1.845     albertel 9946:     my %libserv;
1.852     albertel 9947:     my $loaded;
1.888     albertel 9948:     my %name_to_host;
1.1074    raeburn  9949:     my %internetdom;
1.852     albertel 9950: 
                   9951:     sub parse_hosts_tab {
                   9952: 	my ($file) = @_;
                   9953: 	foreach my $configline (@$file) {
                   9954: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9955: 	    next if ($configline =~ /^\^/);
                   9956: 	    chomp($configline);
1.1074    raeburn  9957: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 9958: 	    $name=~s/\s//g;
                   9959: 	    if ($id && $domain && $role && $name) {
                   9960: 		$hostname{$id}=$name;
1.888     albertel 9961: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9962: 		$hostdom{$id}=$domain;
                   9963: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9964:                 if (defined($protocol)) {
                   9965:                     if ($protocol eq 'https') {
                   9966:                         $protocol{$id} = $protocol;
                   9967:                     } else {
                   9968:                         $protocol{$id} = 'http'; 
                   9969:                     }
1.968     raeburn  9970:                 } else {
1.969     raeburn  9971:                     $protocol{$id} = 'http';
1.968     raeburn  9972:                 }
1.1074    raeburn  9973:                 if (defined($intdom)) {
                   9974:                     $internetdom{$id} = $intdom;
                   9975:                 }
1.852     albertel 9976: 	    }
                   9977: 	}
                   9978:     }
1.864     albertel 9979:     
                   9980:     sub reset_hosts_info {
1.897     albertel 9981: 	&purge_remembered();
1.864     albertel 9982: 	&reset_domain_info();
                   9983: 	&reset_hosts_ip_info();
1.892     albertel 9984: 	undef(%name_to_host);
1.864     albertel 9985: 	undef(%hostname);
                   9986: 	undef(%hostdom);
                   9987: 	undef(%libserv);
                   9988: 	undef($loaded);
                   9989:     }
1.1       albertel 9990: 
1.852     albertel 9991:     sub load_hosts_tab {
1.869     albertel 9992: 	my ($ignore_cache) = @_;
                   9993: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9994: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9995: 	my @config = <$config>;
                   9996: 	&parse_hosts_tab(\@config);
                   9997: 	close($config);
                   9998: 	$loaded=1;
1.1       albertel 9999:     }
1.852     albertel 10000: 
1.838     albertel 10001:     sub hostname {
1.852     albertel 10002: 	&load_hosts_tab() if (!$loaded);
                   10003: 
1.838     albertel 10004: 	my ($lonid) = @_;
                   10005: 	return $hostname{$lonid};
                   10006:     }
1.845     albertel 10007: 
1.838     albertel 10008:     sub all_hostnames {
1.852     albertel 10009: 	&load_hosts_tab() if (!$loaded);
                   10010: 
1.838     albertel 10011: 	return %hostname;
                   10012:     }
1.845     albertel 10013: 
1.888     albertel 10014:     sub all_names {
                   10015: 	&load_hosts_tab() if (!$loaded);
                   10016: 
                   10017: 	return %name_to_host;
                   10018:     }
                   10019: 
1.974     raeburn  10020:     sub all_host_domain {
                   10021:         &load_hosts_tab() if (!$loaded);
                   10022:         return %hostdom;
                   10023:     }
                   10024: 
1.845     albertel 10025:     sub is_library {
1.852     albertel 10026: 	&load_hosts_tab() if (!$loaded);
                   10027: 
1.845     albertel 10028: 	return exists($libserv{$_[0]});
                   10029:     }
                   10030: 
                   10031:     sub all_library {
1.852     albertel 10032: 	&load_hosts_tab() if (!$loaded);
                   10033: 
1.845     albertel 10034: 	return %libserv;
                   10035:     }
                   10036: 
1.1062    droeschl 10037:     sub unique_library {
                   10038: 	#2x reverse removes all hostnames that appear more than once
                   10039:         my %unique = reverse &all_library();
                   10040:         return reverse %unique;
                   10041:     }
                   10042: 
1.841     albertel 10043:     sub get_servers {
1.852     albertel 10044: 	&load_hosts_tab() if (!$loaded);
                   10045: 
1.841     albertel 10046: 	my ($domain,$type) = @_;
                   10047: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10048: 	                                          : %hostname;
                   10049: 	my %result;
1.842     albertel 10050: 	if (ref($domain) eq 'ARRAY') {
                   10051: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10052: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10053: 		    $result{$host} = $hostname;
                   10054: 		}
                   10055: 	    }
                   10056: 	} else {
                   10057: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10058: 		if ($hostdom{$host} eq $domain) {
                   10059: 		    $result{$host} = $hostname;
                   10060: 		}
1.841     albertel 10061: 	    }
                   10062: 	}
                   10063: 	return %result;
                   10064:     }
1.845     albertel 10065: 
1.1062    droeschl 10066:     sub get_unique_servers {
                   10067:         my %unique = reverse &get_servers(@_);
                   10068: 	return reverse %unique;
                   10069:     }
                   10070: 
1.844     albertel 10071:     sub host_domain {
1.852     albertel 10072: 	&load_hosts_tab() if (!$loaded);
                   10073: 
1.844     albertel 10074: 	my ($lonid) = @_;
                   10075: 	return $hostdom{$lonid};
                   10076:     }
                   10077: 
1.841     albertel 10078:     sub all_domains {
1.852     albertel 10079: 	&load_hosts_tab() if (!$loaded);
                   10080: 
1.841     albertel 10081: 	my %seen;
                   10082: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10083: 	return @uniq;
                   10084:     }
1.1074    raeburn  10085: 
                   10086:     sub internet_dom {
                   10087:         &load_hosts_tab() if (!$loaded);
                   10088: 
                   10089:         my ($lonid) = @_;
                   10090:         return $internetdom{$lonid};
                   10091:     }
1.1       albertel 10092: }
                   10093: 
1.847     albertel 10094: { 
                   10095:     my %iphost;
1.856     albertel 10096:     my %name_to_ip;
                   10097:     my %lonid_to_ip;
1.869     albertel 10098: 
1.847     albertel 10099:     sub get_hosts_from_ip {
                   10100: 	my ($ip) = @_;
                   10101: 	my %iphosts = &get_iphost();
                   10102: 	if (ref($iphosts{$ip})) {
                   10103: 	    return @{$iphosts{$ip}};
                   10104: 	}
                   10105: 	return;
1.839     albertel 10106:     }
1.864     albertel 10107:     
                   10108:     sub reset_hosts_ip_info {
                   10109: 	undef(%iphost);
                   10110: 	undef(%name_to_ip);
                   10111: 	undef(%lonid_to_ip);
                   10112:     }
1.856     albertel 10113: 
                   10114:     sub get_host_ip {
                   10115: 	my ($lonid) = @_;
                   10116: 	if (exists($lonid_to_ip{$lonid})) {
                   10117: 	    return $lonid_to_ip{$lonid};
                   10118: 	}
                   10119: 	my $name=&hostname($lonid);
                   10120:    	my $ip = gethostbyname($name);
                   10121: 	return if (!$ip || length($ip) ne 4);
                   10122: 	$ip=inet_ntoa($ip);
                   10123: 	$name_to_ip{$name}   = $ip;
                   10124: 	$lonid_to_ip{$lonid} = $ip;
                   10125: 	return $ip;
                   10126:     }
1.847     albertel 10127:     
                   10128:     sub get_iphost {
1.869     albertel 10129: 	my ($ignore_cache) = @_;
1.894     albertel 10130: 
1.869     albertel 10131: 	if (!$ignore_cache) {
                   10132: 	    if (%iphost) {
                   10133: 		return %iphost;
                   10134: 	    }
                   10135: 	    my ($ip_info,$cached)=
                   10136: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10137: 	    if ($cached) {
                   10138: 		%iphost      = %{$ip_info->[0]};
                   10139: 		%name_to_ip  = %{$ip_info->[1]};
                   10140: 		%lonid_to_ip = %{$ip_info->[2]};
                   10141: 		return %iphost;
                   10142: 	    }
                   10143: 	}
1.894     albertel 10144: 
                   10145: 	# get yesterday's info for fallback
                   10146: 	my %old_name_to_ip;
                   10147: 	my ($ip_info,$cached)=
                   10148: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10149: 	if ($cached) {
                   10150: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10151: 	}
                   10152: 
1.888     albertel 10153: 	my %name_to_host = &all_names();
                   10154: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10155: 	    my $ip;
                   10156: 	    if (!exists($name_to_ip{$name})) {
                   10157: 		$ip = gethostbyname($name);
                   10158: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10159: 		    if (defined($old_name_to_ip{$name})) {
                   10160: 			$ip = $old_name_to_ip{$name};
                   10161: 			&logthis("Can't find $name defaulting to old $ip");
                   10162: 		    } else {
                   10163: 			&logthis("Name $name no IP found");
                   10164: 			next;
                   10165: 		    }
                   10166: 		} else {
                   10167: 		    $ip=inet_ntoa($ip);
1.847     albertel 10168: 		}
                   10169: 		$name_to_ip{$name} = $ip;
                   10170: 	    } else {
                   10171: 		$ip = $name_to_ip{$name};
1.653     albertel 10172: 	    }
1.888     albertel 10173: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10174: 		$lonid_to_ip{$id} = $ip;
                   10175: 	    }
                   10176: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10177: 	}
1.869     albertel 10178: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10179: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10180: 				      48*60*60);
1.869     albertel 10181: 
1.847     albertel 10182: 	return %iphost;
1.598     albertel 10183:     }
                   10184: 
1.992     raeburn  10185:     #
                   10186:     #  Given a DNS returns the loncapa host name for that DNS 
                   10187:     # 
                   10188:     sub host_from_dns {
                   10189:         my ($dns) = @_;
                   10190:         my @hosts;
                   10191:         my $ip;
                   10192: 
1.993     raeburn  10193:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10194:             $ip = $name_to_ip{$dns};
                   10195:         }
                   10196:         if (!$ip) {
                   10197:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10198:             if (length($ip) == 4) { 
                   10199: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10200:             }
                   10201:         }
                   10202:         if ($ip) {
                   10203: 	    @hosts = get_hosts_from_ip($ip);
                   10204: 	    return $hosts[0];
                   10205:         }
                   10206:         return undef;
1.986     foxr     10207:     }
1.992     raeburn  10208: 
1.1074    raeburn  10209:     sub get_internet_names {
                   10210:         my ($lonid) = @_;
                   10211:         return if ($lonid eq '');
                   10212:         my ($idnref,$cached)=
                   10213:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10214:         if ($cached) {
                   10215:             return $idnref;
                   10216:         }
                   10217:         my $ip = &get_host_ip($lonid);
                   10218:         my @hosts = &get_hosts_from_ip($ip);
                   10219:         my %iphost = &get_iphost();
                   10220:         my (@idns,%seen);
                   10221:         foreach my $id (@hosts) {
                   10222:             my $dom = &host_domain($id);
                   10223:             my $prim_id = &domain($dom,'primary');
                   10224:             my $prim_ip = &get_host_ip($prim_id);
                   10225:             next if ($seen{$prim_ip});
                   10226:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10227:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10228:                     my $intdom = &internet_dom($id);
                   10229:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10230:                         push(@idns,$intdom);
                   10231:                     }
                   10232:                 }
                   10233:             }
                   10234:             $seen{$prim_ip} = 1;
                   10235:         }
                   10236:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10237:     }
                   10238: 
1.986     foxr     10239: }
                   10240: 
1.1079    raeburn  10241: sub all_loncaparevs {
                   10242:     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);
                   10243: }
                   10244: 
1.862     albertel 10245: BEGIN {
                   10246: 
                   10247: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10248:     unless ($readit) {
                   10249: {
                   10250:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10251:     %perlvar = (%perlvar,%{$configvars});
                   10252: }
                   10253: 
                   10254: 
1.1       albertel 10255: # ------------------------------------------------------ Read spare server file
                   10256: {
1.448     albertel 10257:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10258: 
                   10259:     while (my $configline=<$config>) {
                   10260:        chomp($configline);
1.284     matthew  10261:        if ($configline) {
1.784     albertel 10262: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10263: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10264: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10265:        }
                   10266:     }
1.448     albertel 10267:     close($config);
1.1       albertel 10268: }
1.11      www      10269: # ------------------------------------------------------------ Read permissions
                   10270: {
1.448     albertel 10271:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10272: 
                   10273:     while (my $configline=<$config>) {
1.448     albertel 10274: 	chomp($configline);
                   10275: 	if ($configline) {
                   10276: 	    my ($role,$perm)=split(/ /,$configline);
                   10277: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10278: 	}
1.11      www      10279:     }
1.448     albertel 10280:     close($config);
1.11      www      10281: }
                   10282: 
                   10283: # -------------------------------------------- Read plain texts for permissions
                   10284: {
1.448     albertel 10285:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10286: 
                   10287:     while (my $configline=<$config>) {
1.448     albertel 10288: 	chomp($configline);
                   10289: 	if ($configline) {
1.742     raeburn  10290: 	    my ($short,@plain)=split(/:/,$configline);
                   10291:             %{$prp{$short}} = ();
                   10292: 	    if (@plain > 0) {
                   10293:                 $prp{$short}{'std'} = $plain[0];
                   10294:                 for (my $i=1; $i<@plain; $i++) {
                   10295:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10296:                 }
                   10297:             }
1.448     albertel 10298: 	}
1.135     www      10299:     }
1.448     albertel 10300:     close($config);
1.135     www      10301: }
                   10302: 
                   10303: # ---------------------------------------------------------- Read package table
                   10304: {
1.448     albertel 10305:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10306: 
                   10307:     while (my $configline=<$config>) {
1.483     albertel 10308: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10309: 	chomp($configline);
                   10310: 	my ($short,$plain)=split(/:/,$configline);
                   10311: 	my ($pack,$name)=split(/\&/,$short);
                   10312: 	if ($plain ne '') {
                   10313: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10314: 	    $packagetab{$short}=$plain; 
                   10315: 	}
1.11      www      10316:     }
1.448     albertel 10317:     close($config);
1.329     matthew  10318: }
                   10319: 
1.1073    raeburn  10320: # ---------------------------------------------------------- Read loncaparev table
                   10321: {
                   10322:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10323:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10324:             while (my $configline=<$config>) {
                   10325:                 chomp($configline);
                   10326:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10327:                 $loncaparevs{$hostid}=$loncaparev;
                   10328:             }
                   10329:             close($config);
                   10330:         }
                   10331:     }
                   10332: }
                   10333: 
1.1074    raeburn  10334: # ---------------------------------------------------------- Read serverhostID table
                   10335: {
                   10336:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10337:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10338:             while (my $configline=<$config>) {
                   10339:                 chomp($configline);
                   10340:                 my ($name,$id)=split(/:/,$configline);
                   10341:                 $serverhomeIDs{$name}=$id;
                   10342:             }
                   10343:             close($config);
                   10344:         }
                   10345:     }
                   10346: }
                   10347: 
1.1079    raeburn  10348: {
                   10349:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10350:     if (-e $file) {
                   10351:         my $parser = HTML::LCParser->new($file);
                   10352:         while (my $token = $parser->get_token()) {
                   10353:             if ($token->[0] eq 'S') {
                   10354:                 my $item = $token->[1];
                   10355:                 my $name = $token->[2]{'name'};
                   10356:                 my $value = $token->[2]{'value'};
                   10357:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10358:                     my $release = $parser->get_text();
                   10359:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10360:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10361:                 }
                   10362:             }
                   10363:         }
                   10364:     }
1.1073    raeburn  10365: }
                   10366: 
1.329     matthew  10367: # ------------- set up temporary directory
                   10368: {
                   10369:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10370: 
1.11      www      10371: }
                   10372: 
1.794     albertel 10373: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10374: 				'compress_threshold'=> 20_000,
                   10375:  			        });
1.185     www      10376: 
1.281     www      10377: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10378: $dumpcount=0;
1.958     www      10379: $locknum=0;
1.22      www      10380: 
1.163     harris41 10381: &logtouch();
1.672     albertel 10382: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10383: $readit=1;
1.564     albertel 10384:     {
                   10385: 	use integer;
                   10386: 	my $test=(2**32)+1;
1.568     albertel 10387: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10388: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10389:     }
1.195     www      10390: }
1.1       albertel 10391: }
1.179     www      10392: 
1.1       albertel 10393: 1;
1.191     harris41 10394: __END__
                   10395: 
1.243     albertel 10396: =pod
                   10397: 
1.191     harris41 10398: =head1 NAME
                   10399: 
1.243     albertel 10400: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10401: 
                   10402: =head1 SYNOPSIS
                   10403: 
1.243     albertel 10404: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10405: 
                   10406:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10407: 
1.243     albertel 10408: Common parameters:
                   10409: 
                   10410: =over 4
                   10411: 
                   10412: =item *
                   10413: 
                   10414: $uname : an internal username (if $cname expecting a course Id specifically)
                   10415: 
                   10416: =item *
                   10417: 
                   10418: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10419: 
                   10420: =item *
                   10421: 
                   10422: $symb : a resource instance identifier
                   10423: 
                   10424: =item *
                   10425: 
                   10426: $namespace : the name of a .db file that contains the data needed or
                   10427: being set.
                   10428: 
                   10429: =back
                   10430: 
1.394     bowersj2 10431: =head1 OVERVIEW
1.191     harris41 10432: 
1.394     bowersj2 10433: lonnet provides subroutines which interact with the
                   10434: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10435: about classes, users, and resources.
1.243     albertel 10436: 
                   10437: For many of these objects you can also use this to store data about
                   10438: them or modify them in various ways.
1.191     harris41 10439: 
1.394     bowersj2 10440: =head2 Symbs
1.191     harris41 10441: 
1.394     bowersj2 10442: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10443: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10444: map, the resource number of the resource in the map, and the URL of
                   10445: the resource itself. The latter is somewhat redundant, but might help
                   10446: if maps change.
                   10447: 
                   10448: An example is
                   10449: 
                   10450:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10451: 
                   10452: The respective map entry is
                   10453: 
                   10454:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10455:   title="Problem 2">
                   10456:  </resource>
                   10457: 
                   10458: Symbs are used by the random number generator, as well as to store and
                   10459: restore data specific to a certain instance of for example a problem.
                   10460: 
                   10461: =head2 Storing And Retrieving Data
                   10462: 
                   10463: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10464: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10465: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10466: is is the non-critical message twin of cstore. These functions are for
                   10467: handlers to store a perl hash to a user's permanent data space in an
                   10468: easy manner, and to retrieve it again on another call. It is expected
                   10469: that a handler would use this once at the beginning to retrieve data,
                   10470: and then again once at the end to send only the new data back.
                   10471: 
                   10472: The data is stored in the user's data directory on the user's
                   10473: homeserver under the ID of the course.
                   10474: 
                   10475: The hash that is returned by restore will have all of the previous
                   10476: value for all of the elements of the hash.
                   10477: 
                   10478: Example:
                   10479: 
                   10480:  #creating a hash
                   10481:  my %hash;
                   10482:  $hash{'foo'}='bar';
                   10483: 
                   10484:  #storing it
                   10485:  &Apache::lonnet::cstore(\%hash);
                   10486: 
                   10487:  #changing a value
                   10488:  $hash{'foo'}='notbar';
                   10489: 
                   10490:  #adding a new value
                   10491:  $hash{'bar'}='foo';
                   10492:  &Apache::lonnet::cstore(\%hash);
                   10493: 
                   10494:  #retrieving the hash
                   10495:  my %history=&Apache::lonnet::restore();
                   10496: 
                   10497:  #print the hash
                   10498:  foreach my $key (sort(keys(%history))) {
                   10499:    print("\%history{$key} = $history{$key}");
                   10500:  }
                   10501: 
                   10502: Will print out:
1.191     harris41 10503: 
1.394     bowersj2 10504:  %history{1:foo} = bar
                   10505:  %history{1:keys} = foo:timestamp
                   10506:  %history{1:timestamp} = 990455579
                   10507:  %history{2:bar} = foo
                   10508:  %history{2:foo} = notbar
                   10509:  %history{2:keys} = foo:bar:timestamp
                   10510:  %history{2:timestamp} = 990455580
                   10511:  %history{bar} = foo
                   10512:  %history{foo} = notbar
                   10513:  %history{timestamp} = 990455580
                   10514:  %history{version} = 2
                   10515: 
                   10516: Note that the special hash entries C<keys>, C<version> and
                   10517: C<timestamp> were added to the hash. C<version> will be equal to the
                   10518: total number of versions of the data that have been stored. The
                   10519: C<timestamp> attribute will be the UNIX time the hash was
                   10520: stored. C<keys> is available in every historical section to list which
                   10521: keys were added or changed at a specific historical revision of a
                   10522: hash.
                   10523: 
                   10524: B<Warning>: do not store the hash that restore returns directly. This
                   10525: will cause a mess since it will restore the historical keys as if the
                   10526: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10527: 
1.394     bowersj2 10528: Calling convention:
1.191     harris41 10529: 
1.394     bowersj2 10530:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10531:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10532: 
1.394     bowersj2 10533: For more detailed information, see lonnet specific documentation.
1.191     harris41 10534: 
1.394     bowersj2 10535: =head1 RETURN MESSAGES
1.191     harris41 10536: 
1.394     bowersj2 10537: =over 4
1.191     harris41 10538: 
1.394     bowersj2 10539: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10540: 
1.394     bowersj2 10541: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10542: when the connection is brought back up
1.191     harris41 10543: 
1.394     bowersj2 10544: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10545: for later delivery
1.191     harris41 10546: 
1.967     bisitz   10547: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10548: 
1.394     bowersj2 10549: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10550: that was requested
1.191     harris41 10551: 
1.243     albertel 10552: =back
1.191     harris41 10553: 
1.243     albertel 10554: =head1 PUBLIC SUBROUTINES
1.191     harris41 10555: 
1.243     albertel 10556: =head2 Session Environment Functions
1.191     harris41 10557: 
1.243     albertel 10558: =over 4
1.191     harris41 10559: 
1.394     bowersj2 10560: =item * 
                   10561: X<appenv()>
1.949     raeburn  10562: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10563: the user envirnoment file, and will be restored for each access this
1.620     albertel 10564: user makes during this session, also modifies the %env for the current
1.949     raeburn  10565: process. Optional rolesarrayref - if defined contains a reference to an array
                   10566: of roles which are exempt from the restriction on modifying user.role entries 
                   10567: in the user's environment.db and in %env.    
1.191     harris41 10568: 
                   10569: =item *
1.394     bowersj2 10570: X<delenv()>
1.987     raeburn  10571: B<delenv($delthis,$regexp)>: removes all items from the session
                   10572: environment file that begin with $delthis. If the 
                   10573: optional second arg - $regexp - is true, $delthis is treated as a 
                   10574: regular expression, otherwise \Q$delthis\E is used. 
                   10575: The values are also deleted from the current processes %env.
1.191     harris41 10576: 
1.795     albertel 10577: =item * get_env_multiple($name) 
                   10578: 
                   10579: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10580: values may be defined and end up as an array ref.
                   10581: 
                   10582: returns an array of values
                   10583: 
1.243     albertel 10584: =back
                   10585: 
                   10586: =head2 User Information
1.191     harris41 10587: 
1.243     albertel 10588: =over 4
1.191     harris41 10589: 
                   10590: =item *
1.394     bowersj2 10591: X<queryauthenticate()>
                   10592: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10593: authentication scheme
                   10594: 
                   10595: =item *
1.394     bowersj2 10596: X<authenticate()>
1.1073    raeburn  10597: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10598: authenticate user from domain's lib servers (first use the current
                   10599: one). C<$upass> should be the users password.
1.1073    raeburn  10600: $checkdefauth is optional (value is 1 if a check should be made to
                   10601:    authenticate user using default authentication method, and allow
                   10602:    account creation if username does not have account in the domain).
                   10603: $clientcancheckhost is optional (value is 1 if checking whether the
                   10604:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10605: 
                   10606: =item *
1.394     bowersj2 10607: X<homeserver()>
                   10608: B<homeserver($uname,$udom)>: find the server which has
                   10609: the user's directory and files (there must be only one), this caches
                   10610: the answer, and also caches if there is a borken connection.
1.191     harris41 10611: 
                   10612: =item *
1.394     bowersj2 10613: X<idget()>
                   10614: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10615: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10616: username, and only 1 username per ID in a specific domain) (returns
                   10617: hash: id=>name,id=>name)
1.191     harris41 10618: 
                   10619: =item *
1.394     bowersj2 10620: X<idrget()>
                   10621: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10622: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10623: 
                   10624: =item *
1.394     bowersj2 10625: X<idput()>
                   10626: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10627: 
                   10628: =item *
1.394     bowersj2 10629: X<rolesinit()>
                   10630: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10631: 
                   10632: =item *
1.551     albertel 10633: X<getsection()>
                   10634: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10635: course $cname, return section name/number or '' for "not in course"
                   10636: and '-1' for "no section"
                   10637: 
                   10638: =item *
1.394     bowersj2 10639: X<userenvironment()>
                   10640: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10641: passed in @what from the requested user's environment, returns a hash
                   10642: 
1.858     raeburn  10643: =item * 
                   10644: X<userlog_query()>
1.859     albertel 10645: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10646: activity.log file. %filters defines filters applied when parsing the
                   10647: log file. These can be start or end timestamps, or the type of action
                   10648: - log to look for Login or Logout events, check for Checkin or
                   10649: Checkout, role for role selection. The response is in the form
                   10650: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10651: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10652: 
1.243     albertel 10653: =back
                   10654: 
                   10655: =head2 User Roles
                   10656: 
                   10657: =over 4
                   10658: 
                   10659: =item *
                   10660: 
1.810     raeburn  10661: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10662:  F: full access
                   10663:  U,I,K: authentication modes (cxx only)
                   10664:  '': forbidden
                   10665:  1: user needs to choose course
                   10666:  2: browse allowed
1.766     albertel 10667:  A: passphrase authentication needed
1.243     albertel 10668: 
                   10669: =item *
                   10670: 
                   10671: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10672: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10673: and course level
                   10674: 
                   10675: =item *
                   10676: 
1.988     raeburn  10677: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10678: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10679: $type is Course (default) or Community.
1.988     raeburn  10680: If $forcedefault evaluates to true, text returned will be default 
                   10681: text for $type. Otherwise, if this is a course, the text returned 
                   10682: will be a custom name for the role (if defined in the course's 
                   10683: environment).  If no custom name is defined the default is returned.
                   10684:    
1.832     raeburn  10685: =item *
                   10686: 
1.935     raeburn  10687: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10688: All arguments are optional. Returns a hash of a roles, either for
                   10689: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10690: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10691: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10692: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10693: For each key, value is set to colon-separated start and end times for
                   10694: the role.  If no username and domain are specified, will default to
1.934     raeburn  10695: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10696: of role statuses (active, future or previous), roles 
                   10697: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10698: to restrict the list of roles reported. If no array ref is 
                   10699: provided for types, will default to return only active roles.
1.834     albertel 10700: 
1.243     albertel 10701: =back
                   10702: 
                   10703: =head2 User Modification
                   10704: 
                   10705: =over 4
                   10706: 
                   10707: =item *
                   10708: 
1.957     raeburn  10709: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10710: user for the level given by URL.  Optional start and end dates (leave empty
                   10711: string or zero for "no date")
1.191     harris41 10712: 
                   10713: =item *
                   10714: 
1.243     albertel 10715: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10716: change a users, password, possible return values are: ok,
                   10717: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10718: refused
1.191     harris41 10719: 
                   10720: =item *
                   10721: 
1.243     albertel 10722: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10723: 
                   10724: =item *
                   10725: 
1.1058    raeburn  10726: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10727:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10728: 
                   10729: will update user information (firstname,middlename,lastname,generation,
                   10730: permanentemail), and if forceid is true, student/employee ID also.
                   10731: A user's institutional affiliation(s) can also be updated.
                   10732: User information fields will not be overwritten with empty entries 
                   10733: unless the field is included in the $candelete array reference.
                   10734: This array is included when a single user is modified via "Manage Users",
                   10735: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10736: 
                   10737: =item *
                   10738: 
1.286     matthew  10739: modifystudent
                   10740: 
1.957     raeburn  10741: modify a student's enrollment and identification information.
1.286     matthew  10742: The course id is resolved based on the current users environment.  
                   10743: This means the envoking user must be a course coordinator or otherwise
                   10744: associated with a course.
                   10745: 
1.297     matthew  10746: This call is essentially a wrapper for lonnet::modifyuser and
                   10747: lonnet::modify_student_enrollment
1.286     matthew  10748: 
                   10749: Inputs: 
                   10750: 
                   10751: =over 4
                   10752: 
1.957     raeburn  10753: =item B<$udom> Student's loncapa domain
1.286     matthew  10754: 
1.957     raeburn  10755: =item B<$uname> Student's loncapa login name
1.286     matthew  10756: 
1.964     bisitz   10757: =item B<$uid> Student/Employee ID
1.286     matthew  10758: 
1.957     raeburn  10759: =item B<$umode> Student's authentication mode
1.286     matthew  10760: 
1.957     raeburn  10761: =item B<$upass> Student's password
1.286     matthew  10762: 
1.957     raeburn  10763: =item B<$first> Student's first name
1.286     matthew  10764: 
1.957     raeburn  10765: =item B<$middle> Student's middle name
1.286     matthew  10766: 
1.957     raeburn  10767: =item B<$last> Student's last name
1.286     matthew  10768: 
1.957     raeburn  10769: =item B<$gene> Student's generation
1.286     matthew  10770: 
1.957     raeburn  10771: =item B<$usec> Student's section in course
1.286     matthew  10772: 
                   10773: =item B<$end> Unix time of the roles expiration
                   10774: 
                   10775: =item B<$start> Unix time of the roles start date
                   10776: 
                   10777: =item B<$forceid> If defined, allow $uid to be changed
                   10778: 
                   10779: =item B<$desiredhome> server to use as home server for student
                   10780: 
1.957     raeburn  10781: =item B<$email> Student's permanent e-mail address
                   10782: 
                   10783: =item B<$type> Type of enrollment (auto or manual)
                   10784: 
1.963     raeburn  10785: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10786: 
                   10787: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10788: 
1.963     raeburn  10789: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10790: 
1.963     raeburn  10791: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10792: 
1.963     raeburn  10793: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10794: 
1.286     matthew  10795: =back
1.297     matthew  10796: 
                   10797: =item *
                   10798: 
                   10799: modify_student_enrollment
                   10800: 
                   10801: Change a students enrollment status in a class.  The environment variable
                   10802: 'role.request.course' must be defined for this function to proceed.
                   10803: 
                   10804: Inputs:
                   10805: 
                   10806: =over 4
                   10807: 
                   10808: =item $udom, students domain
                   10809: 
                   10810: =item $uname, students name
                   10811: 
                   10812: =item $uid, students user id
                   10813: 
                   10814: =item $first, students first name
                   10815: 
                   10816: =item $middle
                   10817: 
                   10818: =item $last
                   10819: 
                   10820: =item $gene
                   10821: 
                   10822: =item $usec
                   10823: 
                   10824: =item $end
                   10825: 
                   10826: =item $start
                   10827: 
1.957     raeburn  10828: =item $type
                   10829: 
                   10830: =item $locktype
                   10831: 
                   10832: =item $cid
                   10833: 
                   10834: =item $selfenroll
                   10835: 
                   10836: =item $context
                   10837: 
1.297     matthew  10838: =back
                   10839: 
1.191     harris41 10840: 
                   10841: =item *
                   10842: 
1.243     albertel 10843: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10844: custom role; give a custom role to a user for the level given by URL.  Specify
                   10845: name and domain of role author, and role name
1.191     harris41 10846: 
                   10847: =item *
                   10848: 
1.243     albertel 10849: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10850: 
                   10851: =item *
                   10852: 
1.243     albertel 10853: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10854: 
                   10855: =back
                   10856: 
                   10857: =head2 Course Infomation
                   10858: 
                   10859: =over 4
1.191     harris41 10860: 
                   10861: =item *
                   10862: 
1.631     albertel 10863: coursedescription($courseid) : returns a hash of information about the
                   10864: specified course id, including all environment settings for the
                   10865: course, the description of the course will be in the hash under the
                   10866: key 'description'
1.191     harris41 10867: 
                   10868: =item *
                   10869: 
1.624     albertel 10870: resdata($name,$domain,$type,@which) : request for current parameter
                   10871: setting for a specific $type, where $type is either 'course' or 'user',
                   10872: @what should be a list of parameters to ask about. This routine caches
                   10873: answers for 5 minutes.
1.243     albertel 10874: 
1.877     foxr     10875: =item *
                   10876: 
                   10877: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10878: data base, returning a hash that is keyed by the resource name and has
                   10879: values that are the resource value.  I believe that the timestamps and
                   10880: versions are also returned.
                   10881: 
                   10882: 
1.243     albertel 10883: =back
                   10884: 
                   10885: =head2 Course Modification
                   10886: 
                   10887: =over 4
1.191     harris41 10888: 
                   10889: =item *
                   10890: 
1.243     albertel 10891: writecoursepref($courseid,%prefs) : write preferences (environment
                   10892: database) for a course
1.191     harris41 10893: 
                   10894: =item *
                   10895: 
1.1011    raeburn  10896: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10897: 
                   10898: =item *
                   10899: 
1.1038    raeburn  10900: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10901: 
                   10902: =back
                   10903: 
                   10904: =head2 Resource Subroutines
                   10905: 
                   10906: =over 4
1.191     harris41 10907: 
                   10908: =item *
                   10909: 
1.243     albertel 10910: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10911: 
                   10912: =item *
                   10913: 
1.243     albertel 10914: repcopy($filename) : subscribes to the requested file, and attempts to
                   10915: replicate from the owning library server, Might return
1.607     raeburn  10916: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10917: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10918: resource. Expects the local filesystem pathname
                   10919: (/home/httpd/html/res/....)
                   10920: 
                   10921: =back
                   10922: 
                   10923: =head2 Resource Information
                   10924: 
                   10925: =over 4
1.191     harris41 10926: 
                   10927: =item *
                   10928: 
1.243     albertel 10929: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10930: a vairety of different possible values, $varname should be a request
                   10931: string, and the other parameters can be used to specify who and what
                   10932: one is asking about.
                   10933: 
                   10934: Possible values for $varname are environment.lastname (or other item
                   10935: from the envirnment hash), user.name (or someother aspect about the
                   10936: user), resource.0.maxtries (or some other part and parameter of a
                   10937: resource)
1.204     albertel 10938: 
                   10939: =item *
                   10940: 
1.243     albertel 10941: directcondval($number) : get current value of a condition; reads from a state
                   10942: string
1.204     albertel 10943: 
                   10944: =item *
                   10945: 
1.243     albertel 10946: condval($condidx) : value of condition index based on state
1.204     albertel 10947: 
                   10948: =item *
                   10949: 
1.243     albertel 10950: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10951: resource's metadata, $what should be either a specific key, or either
                   10952: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10953: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10954: 
                   10955: this function automatically caches all requests
1.191     harris41 10956: 
                   10957: =item *
                   10958: 
1.243     albertel 10959: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10960: network of library servers; returns file handle of where SQL and regex results
                   10961: will be stored for query
1.191     harris41 10962: 
                   10963: =item *
                   10964: 
1.243     albertel 10965: symbread($filename) : return symbolic list entry (filename argument optional);
                   10966: returns the data handle
1.191     harris41 10967: 
                   10968: =item *
                   10969: 
1.243     albertel 10970: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10971: a possible symb for the URL in $thisfn, and if is an encryypted
                   10972: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10973: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10974: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10975: 
1.191     harris41 10976: 
                   10977: =item *
                   10978: 
1.243     albertel 10979: symbclean($symb) : removes versions numbers from a symb, returns the
                   10980: cleaned symb
1.191     harris41 10981: 
                   10982: =item *
                   10983: 
1.243     albertel 10984: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10985: course map, user must be in a course for it to work.
1.191     harris41 10986: 
                   10987: =item *
                   10988: 
1.243     albertel 10989: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10990: 
                   10991: =item *
                   10992: 
1.243     albertel 10993: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10994: a random seed, all arguments are optional, if they aren't sent it uses the
                   10995: environment to derive them. Note: if symb isn't sent and it can't get one
                   10996: from &symbread it will use the current time as its return value
1.191     harris41 10997: 
                   10998: =item *
                   10999: 
1.243     albertel 11000: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11001: unfakeable, receipt
1.191     harris41 11002: 
                   11003: =item *
                   11004: 
1.620     albertel 11005: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11006: 
                   11007: =item *
                   11008: 
1.243     albertel 11009: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11010: 
                   11011: =item *
                   11012: 
1.243     albertel 11013: 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 11014: 
                   11015: =item *
                   11016: 
1.243     albertel 11017: 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 11018: 
                   11019: =item *
                   11020: 
1.243     albertel 11021: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11022: 
                   11023: =item *
                   11024: 
1.243     albertel 11025: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11026: forcing spreadsheet to reevaluate the resource scores next time.
                   11027: 
                   11028: =back
                   11029: 
                   11030: =head2 Storing/Retreiving Data
                   11031: 
                   11032: =over 4
1.191     harris41 11033: 
                   11034: =item *
                   11035: 
1.243     albertel 11036: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11037: for this url; hashref needs to be given and should be a \%hashname; the
                   11038: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11039: be derived from the env
1.191     harris41 11040: 
                   11041: =item *
                   11042: 
1.243     albertel 11043: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11044: uses critical subroutine
1.191     harris41 11045: 
                   11046: =item *
                   11047: 
1.243     albertel 11048: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11049: all args are optional
1.191     harris41 11050: 
                   11051: =item *
                   11052: 
1.717     albertel 11053: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11054: dumps the complete (or key matching regexp) namespace into a hash
                   11055: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11056: normally &store()ed into
                   11057: 
                   11058: $range should be either an integer '100' (give me the first 100
                   11059:                                            matching records)
                   11060:               or be  two integers sperated by a - with no spaces
                   11061:                  '30-50' (give me the 30th through the 50th matching
                   11062:                           records)
                   11063: 
                   11064: 
                   11065: =item *
                   11066: 
                   11067: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11068: replaces a &store() version of data with a replacement set of data
                   11069: for a particular resource in a namespace passed in the $storehash hash 
                   11070: reference
                   11071: 
                   11072: =item *
                   11073: 
1.243     albertel 11074: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11075: works very similar to store/cstore, but all data is stored in a
                   11076: temporary location and can be reset using tmpreset, $storehash should
                   11077: be a hash reference, returns nothing on success
1.191     harris41 11078: 
                   11079: =item *
                   11080: 
1.243     albertel 11081: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11082: similar to restore, but all data is stored in a temporary location and
                   11083: can be reset using tmpreset. Returns a hash of values on success,
                   11084: error string otherwise.
1.191     harris41 11085: 
                   11086: =item *
                   11087: 
1.243     albertel 11088: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11089: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11090: 
                   11091: =item *
                   11092: 
1.243     albertel 11093: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11094: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11095: 
                   11096: =item *
                   11097: 
1.243     albertel 11098: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11099: namesp ($udom and $uname are optional)
1.191     harris41 11100: 
                   11101: =item *
                   11102: 
1.702     albertel 11103: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11104: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11105: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11106: 
1.702     albertel 11107: $range should be either an integer '100' (give me the first 100
                   11108:                                            matching records)
                   11109:               or be  two integers sperated by a - with no spaces
                   11110:                  '30-50' (give me the 30th through the 50th matching
                   11111:                           records)
1.449     matthew  11112: =item *
                   11113: 
                   11114: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11115: $store can be a scalar, an array reference, or if the amount to be 
                   11116: incremented is > 1, a hash reference.
                   11117: 
                   11118: ($udom and $uname are optional)
1.191     harris41 11119: 
                   11120: =item *
                   11121: 
1.243     albertel 11122: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11123: ($udom and $uname are optional)
1.191     harris41 11124: 
                   11125: =item *
                   11126: 
1.243     albertel 11127: cput($namespace,$storehash,$udom,$uname) : critical put
                   11128: ($udom and $uname are optional)
1.191     harris41 11129: 
                   11130: =item *
                   11131: 
1.748     albertel 11132: newput($namespace,$storehash,$udom,$uname) :
                   11133: 
                   11134: Attempts to store the items in the $storehash, but only if they don't
                   11135: currently exist, if this succeeds you can be certain that you have 
                   11136: successfully created a new key value pair in the $namespace db.
                   11137: 
                   11138: 
                   11139: Args:
                   11140:  $namespace: name of database to store values to
                   11141:  $storehash: hashref to store to the db
                   11142:  $udom: (optional) domain of user containing the db
                   11143:  $uname: (optional) name of user caontaining the db
                   11144: 
                   11145: Returns:
                   11146:  'ok' -> succeeded in storing all keys of $storehash
                   11147:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11148:                         least <key> already existed in the db (other
                   11149:                         requested keys may also already exist)
1.967     bisitz   11150:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11151:  'con_lost' -> unable to contact request server
                   11152:  'refused' -> action was not allowed by remote machine
                   11153: 
                   11154: 
                   11155: =item *
                   11156: 
1.243     albertel 11157: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11158: reference filled in from namesp (encrypts the return communication)
                   11159: ($udom and $uname are optional)
1.191     harris41 11160: 
                   11161: =item *
                   11162: 
1.243     albertel 11163: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11164: critical subroutine
                   11165: 
1.806     raeburn  11166: =item *
                   11167: 
1.860     raeburn  11168: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11169: array reference filled in from namespace found in domain level on either
                   11170: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11171: 
                   11172: =item *
                   11173: 
1.860     raeburn  11174: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11175: domain level either on specified domain server ($uhome) or primary domain 
                   11176: server ($udom and $uhome are optional)
1.806     raeburn  11177: 
1.943     raeburn  11178: =item * 
                   11179: 
                   11180: get_domain_defaults($target_domain) : returns hash with defaults for
                   11181: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11182: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11183: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11184: Values are retrieved from cache (if current), or from domain's configuration.db
                   11185: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11186: or lonTabs/domain.tab. 
                   11187: 
                   11188: %domdefaults = &get_auth_defaults($target_domain);
                   11189: 
1.243     albertel 11190: =back
                   11191: 
                   11192: =head2 Network Status Functions
                   11193: 
                   11194: =over 4
1.191     harris41 11195: 
                   11196: =item *
                   11197: 
                   11198: dirlist($uri) : return directory list based on URI
                   11199: 
                   11200: =item *
                   11201: 
1.243     albertel 11202: spareserver() : find server with least workload from spare.tab
                   11203: 
1.986     foxr     11204: 
                   11205: =item *
                   11206: 
                   11207: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11208: if there is no corresponding loncapa host.
                   11209: 
1.243     albertel 11210: =back
                   11211: 
1.986     foxr     11212: 
1.243     albertel 11213: =head2 Apache Request
                   11214: 
                   11215: =over 4
1.191     harris41 11216: 
                   11217: =item *
                   11218: 
1.243     albertel 11219: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11220: localhost, posts hash
                   11221: 
                   11222: =back
                   11223: 
                   11224: =head2 Data to String to Data
                   11225: 
                   11226: =over 4
1.191     harris41 11227: 
                   11228: =item *
                   11229: 
1.243     albertel 11230: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11231: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11232: 
                   11233: =item *
                   11234: 
1.243     albertel 11235: hashref2str($hashref) : convert a hashref into a string complete with
                   11236: escaping and '=' and '&' separators, supports elements that are
                   11237: arrayrefs and hashrefs
1.191     harris41 11238: 
                   11239: =item *
                   11240: 
1.243     albertel 11241: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11242: with escaping and '&' separators, supports elements that are arrayrefs
                   11243: and hashrefs
1.191     harris41 11244: 
                   11245: =item *
                   11246: 
1.243     albertel 11247: str2hash($string) : convert string to hash using unescaping and
                   11248: splitting on '=' and '&', supports elements that are arrayrefs and
                   11249: hashrefs
1.191     harris41 11250: 
                   11251: =item *
                   11252: 
1.243     albertel 11253: str2array($string) : convert string to hash using unescaping and
                   11254: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11255: 
                   11256: =back
                   11257: 
                   11258: =head2 Logging Routines
                   11259: 
                   11260: =over 4
                   11261: 
                   11262: These routines allow one to make log messages in the lonnet.log and
                   11263: lonnet.perm logfiles.
1.191     harris41 11264: 
                   11265: =item *
                   11266: 
1.243     albertel 11267: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11268: 
                   11269: =item *
                   11270: 
1.243     albertel 11271: logthis() : append message to the normal lonnet.log file, it gets
                   11272: preiodically rolled over and deleted.
1.191     harris41 11273: 
                   11274: =item *
                   11275: 
1.243     albertel 11276: logperm() : append a permanent message to lonnet.perm.log, this log
                   11277: file never gets deleted by any automated portion of the system, only
                   11278: messages of critical importance should go in here.
                   11279: 
                   11280: =back
                   11281: 
                   11282: =head2 General File Helper Routines
                   11283: 
                   11284: =over 4
1.191     harris41 11285: 
                   11286: =item *
                   11287: 
1.481     raeburn  11288: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11289: (a) files in /uploaded
                   11290:   (i) If a local copy of the file exists - 
                   11291:       compares modification date of local copy with last-modified date for 
                   11292:       definitive version stored on home server for course. If local copy is 
                   11293:       stale, requests a new version from the home server and stores it. 
                   11294:       If the original has been removed from the home server, then local copy 
                   11295:       is unlinked.
                   11296:   (ii) If local copy does not exist -
                   11297:       requests the file from the home server and stores it. 
                   11298:   
                   11299:   If $caller is 'uploadrep':  
                   11300:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11301:     for request for files originally uploaded via DOCS. 
                   11302:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11303:   
                   11304:   Otherwise:
                   11305:      This indicates a call from the content generation phase of the request.
                   11306:      -  returns the entire contents of the file or -1.
                   11307:      
                   11308: (b) files in /res
                   11309:    - returns the entire contents of a file or -1; 
                   11310:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11311: 
1.712     albertel 11312: 
                   11313: =item *
                   11314: 
                   11315: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11316:                   reference
                   11317: 
                   11318: returns either a stat() list of data about the file or an empty list
                   11319: if the file doesn't exist or couldn't find out about it (connection
                   11320: problems or user unknown)
                   11321: 
1.191     harris41 11322: =item *
                   11323: 
1.243     albertel 11324: filelocation($dir,$file) : returns file system location of a file
                   11325: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11326: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11327: and a file of ../bob will become /a/bob)
1.191     harris41 11328: 
                   11329: =item *
                   11330: 
                   11331: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11332: filelocation except for hrefs
                   11333: 
                   11334: =item *
                   11335: 
                   11336: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11337: 
1.243     albertel 11338: =back
                   11339: 
1.608     albertel 11340: =head2 Usererfile file routines (/uploaded*)
                   11341: 
                   11342: =over 4
                   11343: 
                   11344: =item *
                   11345: 
                   11346: userfileupload(): main rotine for putting a file in a user or course's
                   11347:                   filespace, arguments are,
                   11348: 
1.620     albertel 11349:  formname - required - this is the name of the element in $env where the
1.608     albertel 11350:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11351:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11352:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 11353:  coursedoc - if true, store the file in the course of the active role
                   11354:              of the current user
                   11355:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11356:          if undefined, it will be placed in "unknown"
                   11357: 
                   11358:  (This routine calls clean_filename() to remove any dangerous
                   11359:  characters from the filename, and then calls finuserfileupload() to
                   11360:  complete the transaction)
                   11361: 
                   11362:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11363:  and /adm/notfound.html if unsuccessful
                   11364: 
                   11365: =item *
                   11366: 
                   11367: clean_filename(): routine for cleaing a filename up for storage in
                   11368:                  userfile space, argument is:
                   11369: 
                   11370:  filename - proposed filename
                   11371: 
                   11372: returns: the new clean filename
                   11373: 
                   11374: =item *
                   11375: 
                   11376: finishuserfileupload(): routine that creaes and sends the file to
                   11377: userspace, probably shouldn't be called directly
                   11378: 
                   11379:   docuname: username or courseid of destination for the file
                   11380:   docudom: domain of user/course of destination for the file
                   11381:   formname: same as for userfileupload()
                   11382:   fname: filename (inculding subdirectories) for the file
                   11383: 
                   11384:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11385:  and /adm/notfound.html if unsuccessful
                   11386: 
                   11387: =item *
                   11388: 
                   11389: renameuserfile(): renames an existing userfile to a new name
                   11390: 
                   11391:   Args:
                   11392:    docuname: username or courseid of destination for the file
                   11393:    docudom: domain of user/course of destination for the file
                   11394:    old: current file name (including any subdirs under userfiles)
                   11395:    new: desired file name (including any subdirs under userfiles)
                   11396: 
                   11397: =item *
                   11398: 
                   11399: mkdiruserfile(): creates a directory is a userfiles dir
                   11400: 
                   11401:   Args:
                   11402:    docuname: username or courseid of destination for the file
                   11403:    docudom: domain of user/course of destination for the file
                   11404:    dir: dir to create (including any subdirs under userfiles)
                   11405: 
                   11406: =item *
                   11407: 
                   11408: removeuserfile(): removes a file that exists in userfiles
                   11409: 
                   11410:   Args:
                   11411:    docuname: username or courseid of destination for the file
                   11412:    docudom: domain of user/course of destination for the file
                   11413:    fname: filname to delete (including any subdirs under userfiles)
                   11414: 
                   11415: =item *
                   11416: 
                   11417: removeuploadedurl(): convience function for removeuserfile()
                   11418: 
                   11419:   Args:
                   11420:    url:  a full /uploaded/... url to delete
                   11421: 
1.747     albertel 11422: =item * 
                   11423: 
                   11424: get_portfile_permissions():
                   11425:   Args:
                   11426:     domain: domain of user or course contain the portfolio files
                   11427:     user: name of user or num of course contain the portfolio files
                   11428:   Returns:
                   11429:     hashref of a dump of the proper file_permissions.db
                   11430:    
                   11431: 
                   11432: =item * 
                   11433: 
                   11434: get_access_controls():
                   11435: 
                   11436: Args:
                   11437:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11438:   group: (optional) the group you want the files associated with
                   11439:   file: (optional) the file you want access info on
                   11440: 
                   11441: Returns:
1.749     raeburn  11442:     a hash (keys are file names) of hashes containing
                   11443:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11444:         values are XML containing access control settings (see below) 
1.747     albertel 11445: 
                   11446: Internal notes:
                   11447: 
1.749     raeburn  11448:  access controls are stored in file_permissions.db as key=value pairs.
                   11449:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11450:         where scope -> public,guest,course,group,domains or users.
                   11451:               end -> UNIX time for end of access (0 -> no end date)
                   11452:               start -> UNIX time for start of access
                   11453: 
                   11454:     value -> XML description of access control
                   11455:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11456:             <start></start>
                   11457:             <end></end>
                   11458: 
                   11459:             <password></password>  for scope type = guest
                   11460: 
                   11461:             <domain></domain>     for scope type = course or group
                   11462:             <number></number>
                   11463:             <roles id="">
                   11464:              <role></role>
                   11465:              <access></access>
                   11466:              <section></section>
                   11467:              <group></group>
                   11468:             </roles>
                   11469: 
                   11470:             <dom></dom>         for scope type = domains
                   11471: 
                   11472:             <users>             for scope type = users
                   11473:              <user>
                   11474:               <uname></uname>
                   11475:               <udom></udom>
                   11476:              </user>
                   11477:             </users>
                   11478:            </scope> 
                   11479:               
                   11480:  Access data is also aggregated for each file in an additional key=value pair:
                   11481:  key -> path to file/file_name\0accesscontrol 
                   11482:  value -> reference to hash
                   11483:           hash contains key = value pairs
                   11484:           where key = uniqueID:scope_end_start
                   11485:                 value = UNIX time record was last updated
                   11486: 
                   11487:           Used to improve speed of look-ups of access controls for each file.  
                   11488:  
                   11489:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11490: 
                   11491: modify_access_controls():
                   11492: 
                   11493: Modifies access controls for a portfolio file
                   11494: Args
                   11495: 1. file name
                   11496: 2. reference to hash of required changes,
                   11497: 3. domain
                   11498: 4. username
                   11499:   where domain,username are the domain of the portfolio owner 
                   11500:   (either a user or a course) 
                   11501: 
                   11502: Returns:
                   11503: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11504: 2. result of deletions ('ok' or 'error', with error message).
                   11505: 3. reference to hash of any new or updated access controls.
                   11506: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11507:    key = integer (inbound ID)
                   11508:    value = uniqueID  
1.747     albertel 11509: 
1.608     albertel 11510: =back
                   11511: 
1.243     albertel 11512: =head2 HTTP Helper Routines
                   11513: 
                   11514: =over 4
                   11515: 
1.191     harris41 11516: =item *
                   11517: 
                   11518: escape() : unpack non-word characters into CGI-compatible hex codes
                   11519: 
                   11520: =item *
                   11521: 
                   11522: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11523: 
1.243     albertel 11524: =back
                   11525: 
                   11526: =head1 PRIVATE SUBROUTINES
                   11527: 
                   11528: =head2 Underlying communication routines (Shouldn't call)
                   11529: 
                   11530: =over 4
                   11531: 
                   11532: =item *
                   11533: 
                   11534: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11535: 
                   11536: =item *
                   11537: 
                   11538: reply() : uses subreply to send a message to remote machine, logs all failures
                   11539: 
                   11540: =item *
                   11541: 
                   11542: critical() : passes a critical message to another server; if cannot
                   11543: get through then place message in connection buffer directory and
                   11544: returns con_delayed, if incapable of saving message, returns
                   11545: con_failed
                   11546: 
                   11547: =item *
                   11548: 
                   11549: reconlonc() : tries to reconnect lonc client processes.
                   11550: 
                   11551: =back
                   11552: 
                   11553: =head2 Resource Access Logging
                   11554: 
                   11555: =over 4
                   11556: 
                   11557: =item *
                   11558: 
                   11559: flushcourselogs() : flush (save) buffer logs and access logs
                   11560: 
                   11561: =item *
                   11562: 
                   11563: courselog($what) : save message for course in hash
                   11564: 
                   11565: =item *
                   11566: 
                   11567: courseacclog($what) : save message for course using &courselog().  Perform
                   11568: special processing for specific resource types (problems, exams, quizzes, etc).
                   11569: 
1.191     harris41 11570: =item *
                   11571: 
                   11572: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11573: as a PerlChildExitHandler
1.243     albertel 11574: 
                   11575: =back
                   11576: 
                   11577: =head2 Other
                   11578: 
                   11579: =over 4
                   11580: 
                   11581: =item *
                   11582: 
                   11583: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11584: 
                   11585: =back
                   11586: 
                   11587: =cut
1.877     foxr     11588: 

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