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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1085  ! raeburn     4: # $Id: lonnet.pm,v 1.1084 2010/09/24 03:15:04 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.817     raeburn  1736:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1737:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1738:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1739:         my $section=$1;
                   1740:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1741:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1742:         my $now=time;
1.548     albertel 1743:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1744:             $Expired{$end}=$section;
                   1745:             next;
                   1746:         }
1.548     albertel 1747:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1748:             $Pending{$start}=$section;
                   1749:             next;
                   1750:         }
1.599     albertel 1751:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1752:     }
                   1753:     #
                   1754:     # Presumedly there will be few matching roles from the above
                   1755:     # loop and the sorting time will be negligible.
                   1756:     if (scalar(keys(%Pending))) {
                   1757:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1758:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1759:     } 
                   1760:     if (scalar(keys(%Expired))) {
                   1761:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1762:         my $time = pop(@sorted);
1.599     albertel 1763:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1764:     }
1.599     albertel 1765:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1766: }
1.70      www      1767: 
1.599     albertel 1768: sub save_cache {
                   1769:     &purge_remembered();
1.722     albertel 1770:     #&Apache::loncommon::validate_page();
1.620     albertel 1771:     undef(%env);
1.780     albertel 1772:     undef($env_loaded);
1.599     albertel 1773: }
1.452     albertel 1774: 
1.599     albertel 1775: my $to_remember=-1;
                   1776: my %remembered;
                   1777: my %accessed;
                   1778: my $kicks=0;
                   1779: my $hits=0;
1.849     albertel 1780: sub make_key {
                   1781:     my ($name,$id) = @_;
1.872     albertel 1782:     if (length($id) > 65 
                   1783: 	&& length(&escape($id)) > 200) {
                   1784: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1785:     }
1.849     albertel 1786:     return &escape($name.':'.$id);
                   1787: }
                   1788: 
1.599     albertel 1789: sub devalidate_cache_new {
                   1790:     my ($name,$id,$debug) = @_;
                   1791:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1792:     $id=&make_key($name,$id);
1.599     albertel 1793:     $memcache->delete($id);
                   1794:     delete($remembered{$id});
                   1795:     delete($accessed{$id});
                   1796: }
                   1797: 
                   1798: sub is_cached_new {
                   1799:     my ($name,$id,$debug) = @_;
1.849     albertel 1800:     $id=&make_key($name,$id);
1.599     albertel 1801:     if (exists($remembered{$id})) {
                   1802: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1803: 	$accessed{$id}=[&gettimeofday()];
                   1804: 	$hits++;
                   1805: 	return ($remembered{$id},1);
                   1806:     }
                   1807:     my $value = $memcache->get($id);
                   1808:     if (!(defined($value))) {
                   1809: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1810: 	return (undef,undef);
1.416     albertel 1811:     }
1.599     albertel 1812:     if ($value eq '__undef__') {
                   1813: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1814: 	$value=undef;
                   1815:     }
                   1816:     &make_room($id,$value,$debug);
                   1817:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1818:     return ($value,1);
                   1819: }
                   1820: 
                   1821: sub do_cache_new {
                   1822:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1823:     $id=&make_key($name,$id);
1.599     albertel 1824:     my $setvalue=$value;
                   1825:     if (!defined($setvalue)) {
                   1826: 	$setvalue='__undef__';
                   1827:     }
1.623     albertel 1828:     if (!defined($time) ) {
                   1829: 	$time=600;
                   1830:     }
1.599     albertel 1831:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1832:     my $result = $memcache->set($id,$setvalue,$time);
                   1833:     if (! $result) {
1.872     albertel 1834: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1835: 	$memcache->disconnect_all();
1.872     albertel 1836:     }
1.600     albertel 1837:     # need to make a copy of $value
1.919     albertel 1838:     &make_room($id,$value,$debug);
1.599     albertel 1839:     return $value;
                   1840: }
                   1841: 
                   1842: sub make_room {
                   1843:     my ($id,$value,$debug)=@_;
1.919     albertel 1844: 
                   1845:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1846:                                     : $value;
1.599     albertel 1847:     if ($to_remember<0) { return; }
                   1848:     $accessed{$id}=[&gettimeofday()];
                   1849:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1850:     my $to_kick;
                   1851:     my $max_time=0;
                   1852:     foreach my $other (keys(%accessed)) {
                   1853: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1854: 	    $to_kick=$other;
                   1855: 	    $max_time=&tv_interval($accessed{$other});
                   1856: 	}
                   1857:     }
                   1858:     delete($remembered{$to_kick});
                   1859:     delete($accessed{$to_kick});
                   1860:     $kicks++;
                   1861:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1862:     return;
                   1863: }
                   1864: 
1.599     albertel 1865: sub purge_remembered {
1.604     albertel 1866:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1867:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1868:     undef(%remembered);
                   1869:     undef(%accessed);
1.428     albertel 1870: }
1.70      www      1871: # ------------------------------------- Read an entry from a user's environment
                   1872: 
                   1873: sub userenvironment {
                   1874:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1875:     my $items;
                   1876:     foreach my $item (@what) {
                   1877:         $items.=&escape($item).'&';
                   1878:     }
                   1879:     $items=~s/\&$//;
1.70      www      1880:     my %returnhash=();
1.1009    raeburn  1881:     my $uhome = &homeserver($unam,$udom);
                   1882:     unless ($uhome eq 'no_host') {
                   1883:         my @answer=split(/\&/, 
                   1884:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1885:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1886:             return %returnhash;
                   1887:         }
1.1009    raeburn  1888:         my $i;
                   1889:         for ($i=0;$i<=$#what;$i++) {
                   1890: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1891:         }
1.70      www      1892:     }
                   1893:     return %returnhash;
1.1       albertel 1894: }
                   1895: 
1.617     albertel 1896: # ---------------------------------------------------------- Get a studentphoto
                   1897: sub studentphoto {
                   1898:     my ($udom,$unam,$ext) = @_;
                   1899:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1900:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1901:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1902:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1903:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1904:             } else {
                   1905:                 my ($result,$perm_reqd)=
1.707     albertel 1906: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1907:                 if ($result eq 'ok') {
                   1908:                     if (!($perm_reqd eq 'yes')) {
                   1909:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1910:                     }
                   1911:                 }
                   1912:             }
                   1913:         }
                   1914:     } else {
                   1915:         my ($result,$perm_reqd) = 
1.707     albertel 1916: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1917:         if ($result eq 'ok') {
                   1918:             if (!($perm_reqd eq 'yes')) {
                   1919:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1920:             }
                   1921:         }
                   1922:     }
                   1923:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1924: }
                   1925: 
                   1926: sub retrievestudentphoto {
                   1927:     my ($udom,$unam,$ext,$type) = @_;
                   1928:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1929:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1930:     if ($ret eq 'ok') {
                   1931:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1932:         if ($type eq 'thumbnail') {
                   1933:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1934:         }
                   1935:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1936:         return $tokenurl;
                   1937:     } else {
                   1938:         if ($type eq 'thumbnail') {
                   1939:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1940:         } else { 
                   1941:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1942:         }
1.617     albertel 1943:     }
                   1944: }
                   1945: 
1.263     www      1946: # -------------------------------------------------------------------- New chat
                   1947: 
                   1948: sub chatsend {
1.724     raeburn  1949:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1950:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1951:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1952:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1953:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1954: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1955: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1956: }
                   1957: 
                   1958: # ------------------------------------------ Find current version of a resource
                   1959: 
                   1960: sub getversion {
                   1961:     my $fname=&clutter(shift);
                   1962:     unless ($fname=~/^\/res\//) { return -1; }
                   1963:     return &currentversion(&filelocation('',$fname));
                   1964: }
                   1965: 
                   1966: sub currentversion {
                   1967:     my $fname=shift;
1.599     albertel 1968:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1969:     if (defined($cached)) { return $result; }
1.292     www      1970:     my $author=$fname;
                   1971:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1972:     my ($udom,$uname)=split(/\//,$author);
                   1973:     my $home=homeserver($uname,$udom);
                   1974:     if ($home eq 'no_host') { 
                   1975:         return -1; 
                   1976:     }
                   1977:     my $answer=reply("currentversion:$fname",$home);
                   1978:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1979: 	return -1;
                   1980:     }
1.599     albertel 1981:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1982: }
                   1983: 
1.1       albertel 1984: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1985: 
1.1       albertel 1986: sub subscribe {
                   1987:     my $fname=shift;
1.761     raeburn  1988:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1989:     $fname=~s/[\n\r]//g;
1.1       albertel 1990:     my $author=$fname;
                   1991:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1992:     my ($udom,$uname)=split(/\//,$author);
                   1993:     my $home=homeserver($uname,$udom);
1.335     albertel 1994:     if ($home eq 'no_host') {
                   1995:         return 'not_found';
1.1       albertel 1996:     }
                   1997:     my $answer=reply("sub:$fname",$home);
1.64      www      1998:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1999: 	$answer.=' by '.$home;
                   2000:     }
1.1       albertel 2001:     return $answer;
                   2002: }
                   2003:     
1.8       www      2004: # -------------------------------------------------------------- Replicate file
                   2005: 
                   2006: sub repcopy {
                   2007:     my $filename=shift;
1.23      www      2008:     $filename=~s/\/+/\//g;
1.607     raeburn  2009:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2010:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2011:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2012: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2013: 	return &repcopy_userfile($filename);
                   2014:     }
1.532     albertel 2015:     $filename=~s/[\n\r]//g;
1.8       www      2016:     my $transname="$filename.in.transfer";
1.828     www      2017: # FIXME: this should flock
1.607     raeburn  2018:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2019:     my $remoteurl=subscribe($filename);
1.64      www      2020:     if ($remoteurl =~ /^con_lost by/) {
                   2021: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2022:            return 'unavailable';
1.8       www      2023:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2024: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2025: 	   return 'not_found';
1.64      www      2026:     } elsif ($remoteurl =~ /^rejected by/) {
                   2027: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2028:            return 'forbidden';
1.20      www      2029:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2030:            return 'ok';
1.8       www      2031:     } else {
1.290     www      2032:         my $author=$filename;
                   2033:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2034:         my ($udom,$uname)=split(/\//,$author);
                   2035:         my $home=homeserver($uname,$udom);
                   2036:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2037:            my @parts=split(/\//,$filename);
                   2038:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2039:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2040:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2041: 	       return 'bad_request';
1.8       www      2042:            }
                   2043:            my $count;
                   2044:            for ($count=5;$count<$#parts;$count++) {
                   2045:                $path.="/$parts[$count]";
                   2046:                if ((-e $path)!=1) {
                   2047: 		   mkdir($path,0777);
                   2048:                }
                   2049:            }
                   2050:            my $ua=new LWP::UserAgent;
                   2051:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2052:            my $response=$ua->request($request,$transname);
                   2053:            if ($response->is_error()) {
                   2054: 	       unlink($transname);
                   2055:                my $message=$response->status_line;
1.672     albertel 2056:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2057:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2058:                return 'unavailable';
1.8       www      2059:            } else {
1.16      www      2060: 	       if ($remoteurl!~/\.meta$/) {
                   2061:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2062:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2063:                   if ($mresponse->is_error()) {
                   2064: 		      unlink($filename.'.meta');
                   2065:                       &logthis(
1.672     albertel 2066:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2067:                   }
                   2068: 	       }
1.8       www      2069:                rename($transname,$filename);
1.607     raeburn  2070:                return 'ok';
1.8       www      2071:            }
1.290     www      2072:        }
1.8       www      2073:     }
1.330     www      2074: }
                   2075: 
                   2076: # ------------------------------------------------ Get server side include body
                   2077: sub ssi_body {
1.381     albertel 2078:     my ($filelink,%form)=@_;
1.606     matthew  2079:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2080:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2081:     }
1.953     www      2082:     my $output='';
                   2083:     my $response;
1.980     raeburn  2084:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2085:        ($output,$response)=&externalssi($filelink);
1.953     www      2086:     } else {
1.1004    droeschl 2087:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2088:        $filelink .= 'inhibitmenu=yes';
1.953     www      2089:        ($output,$response)=&ssi($filelink,%form);
                   2090:     }
1.778     albertel 2091:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2092:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2093:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2094:     if (wantarray) {
                   2095:         return ($output, $response);
                   2096:     } else {
                   2097:         return $output;
                   2098:     }
1.8       www      2099: }
                   2100: 
1.15      www      2101: # --------------------------------------------------------- Server Side Include
                   2102: 
1.782     albertel 2103: sub absolute_url {
                   2104:     my ($host_name) = @_;
                   2105:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2106:     if ($host_name eq '') {
                   2107: 	$host_name = $ENV{'SERVER_NAME'};
                   2108:     }
                   2109:     return $protocol.$host_name;
                   2110: }
                   2111: 
1.942     foxr     2112: #
                   2113: #   Server side include.
                   2114: # Parameters:
                   2115: #  fn     Possibly encrypted resource name/id.
                   2116: #  form   Hash that describes how the rendering should be done
                   2117: #         and other things.
1.944     foxr     2118: # Returns:
1.950     raeburn  2119: #   Scalar context: The content of the response.
                   2120: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2121: #     
1.15      www      2122: sub ssi {
                   2123: 
1.944     foxr     2124:     my ($fn,%form)=@_;
1.15      www      2125:     my $ua=new LWP::UserAgent;
1.23      www      2126:     my $request;
1.711     albertel 2127: 
                   2128:     $form{'no_update_last_known'}=1;
1.895     albertel 2129:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2130:     if (%form) {
1.782     albertel 2131:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2132:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2133:     } else {
1.782     albertel 2134:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2135:     }
                   2136: 
1.15      www      2137:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2138:     my $response=$ua->request($request);
                   2139: 
1.944     foxr     2140:     if (wantarray) {
                   2141: 	return ($response->content, $response);
                   2142:     } else {
                   2143: 	return $response->content;
1.942     foxr     2144:     }
1.324     www      2145: }
                   2146: 
                   2147: sub externalssi {
                   2148:     my ($url)=@_;
                   2149:     my $ua=new LWP::UserAgent;
                   2150:     my $request=new HTTP::Request('GET',$url);
                   2151:     my $response=$ua->request($request);
1.954     raeburn  2152:     if (wantarray) {
                   2153:         return ($response->content, $response);
                   2154:     } else {
                   2155:         return $response->content;
                   2156:     }
1.15      www      2157: }
1.254     www      2158: 
1.492     albertel 2159: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2160: 
                   2161: sub allowuploaded {
                   2162:     my ($srcurl,$url)=@_;
                   2163:     $url=&clutter(&declutter($url));
                   2164:     my $dir=$url;
                   2165:     $dir=~s/\/[^\/]+$//;
                   2166:     my %httpref=();
                   2167:     my $httpurl=&hreflocation('',$url);
                   2168:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2169:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2170: }
1.477     raeburn  2171: 
1.478     albertel 2172: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2173: # input: action, courseID, current domain, intended
1.637     raeburn  2174: #        path to file, source of file, instruction to parse file for objects,
                   2175: #        ref to hash for embedded objects,
                   2176: #        ref to hash for codebase of java objects.
                   2177: #
1.485     raeburn  2178: # output: url to file (if action was uploaddoc), 
                   2179: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2180: #
1.478     albertel 2181: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2182: # course.
1.477     raeburn  2183: #
1.478     albertel 2184: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2185: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2186: #          course's home server.
1.477     raeburn  2187: #
1.478     albertel 2188: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2189: #          be copied from $source (current location) to 
                   2190: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2191: #         and will then be copied to
                   2192: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2193: #         course's home server.
1.485     raeburn  2194: #
1.481     raeburn  2195: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2196: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2197: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2198: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2199: #         in course's home server.
1.637     raeburn  2200: #
1.477     raeburn  2201: 
                   2202: sub process_coursefile {
1.638     albertel 2203:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2204:     my $fetchresult;
1.638     albertel 2205:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2206:     if ($action eq 'propagate') {
1.638     albertel 2207:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2208: 			     $home);
1.481     raeburn  2209:     } else {
1.477     raeburn  2210:         my $fpath = '';
                   2211:         my $fname = $file;
1.478     albertel 2212:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2213:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2214:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2215:         if ($action eq 'copy') {
                   2216:             if ($source eq '') {
                   2217:                 $fetchresult = 'no source file';
                   2218:                 return $fetchresult;
                   2219:             } else {
                   2220:                 my $destination = $filepath.'/'.$fname;
                   2221:                 rename($source,$destination);
                   2222:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2223:                                  $home);
1.481     raeburn  2224:             }
                   2225:         } elsif ($action eq 'uploaddoc') {
                   2226:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2227:             print $fh $env{'form.'.$source};
1.481     raeburn  2228:             close($fh);
1.637     raeburn  2229:             if ($parser eq 'parse') {
1.1024    raeburn  2230:                 my $mm = new File::MMagic;
                   2231:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2232:                 if ($mime_type eq 'text/html') {
                   2233:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2234:                     unless ($parse_result eq 'ok') {
                   2235:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2236:                     }
1.637     raeburn  2237:                 }
                   2238:             }
1.477     raeburn  2239:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2240:                                  $home);
1.481     raeburn  2241:             if ($fetchresult eq 'ok') {
                   2242:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2243:             } else {
                   2244:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2245:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2246:                 return '/adm/notfound.html';
                   2247:             }
1.477     raeburn  2248:         }
                   2249:     }
1.485     raeburn  2250:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2251:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2252:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2253:     }
                   2254:     return $fetchresult;
                   2255: }
                   2256: 
1.637     raeburn  2257: sub build_filepath {
                   2258:     my ($fpath) = @_;
                   2259:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2260:     unless ($fpath eq '') {
                   2261:         my @parts=split('/',$fpath);
                   2262:         foreach my $part (@parts) {
                   2263:             $filepath.= '/'.$part;
                   2264:             if ((-e $filepath)!=1) {
                   2265:                 mkdir($filepath,0777);
                   2266:             }
                   2267:         }
                   2268:     }
                   2269:     return $filepath;
                   2270: }
                   2271: 
                   2272: sub store_edited_file {
1.638     albertel 2273:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2274:     my $file = $primary_url;
                   2275:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2276:     my $fpath = '';
                   2277:     my $fname = $file;
                   2278:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2279:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2280:     my $filepath = &build_filepath($fpath);
                   2281:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2282:     print $fh $content;
                   2283:     close($fh);
1.638     albertel 2284:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2285:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2286: 			  $home);
1.637     raeburn  2287:     if ($$fetchresult eq 'ok') {
                   2288:         return '/uploaded/'.$fpath.'/'.$fname;
                   2289:     } else {
1.638     albertel 2290:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2291: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2292:         return '/adm/notfound.html';
                   2293:     }
                   2294: }
                   2295: 
1.531     albertel 2296: sub clean_filename {
1.831     albertel 2297:     my ($fname,$args)=@_;
1.315     www      2298: # Replace Windows backslashes by forward slashes
1.257     www      2299:     $fname=~s/\\/\//g;
1.831     albertel 2300:     if (!$args->{'keep_path'}) {
                   2301:         # Get rid of everything but the actual filename
                   2302: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2303:     }
1.315     www      2304: # Replace spaces by underscores
                   2305:     $fname=~s/\s+/\_/g;
                   2306: # Replace all other weird characters by nothing
1.831     albertel 2307:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2308: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2309: # numbers
                   2310:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2311:     return $fname;
                   2312: }
1.1051    raeburn  2313: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2314: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2315: # image with the same aspect ratio as the original, but with dimensions which do 
                   2316: # not exceed $resizewidth and $resizeheight.
                   2317:  
1.984     neumanie 2318: sub resizeImage {
1.1051    raeburn  2319:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2320:     my $ima = Image::Magick->new;
                   2321:     my $resized;
                   2322:     if (-e $img_path) {
                   2323:         $ima->Read($img_path);
                   2324:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2325:             my $width = $ima->Get('width');
                   2326:             my $height = $ima->Get('height');
                   2327:             if ($width > $resizewidth) {
                   2328: 	        my $factor = $width/$resizewidth;
                   2329:                 my $newheight = $height/$factor;
                   2330:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2331:                 $resized = 1;
                   2332:             }
                   2333:         }
                   2334:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2335:             my $width = $ima->Get('width');
                   2336:             my $height = $ima->Get('height');
                   2337:             if ($height > $resizeheight) {
                   2338:                 my $factor = $height/$resizeheight;
                   2339:                 my $newwidth = $width/$factor;
                   2340:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2341:                 $resized = 1;
                   2342:             }
                   2343:         }
                   2344:         if ($resized) {
                   2345:             $ima->Write($img_path);
                   2346:         }
                   2347:     }
                   2348:     return;
1.977     amueller 2349: }
                   2350: 
1.608     albertel 2351: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2352: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2353: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2354: #        $coursedoc - if true up to the current course
                   2355: #                     if false
                   2356: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2357: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2358: #        $allfiles - reference to hash for embedded objects
                   2359: #        $codebase - reference to hash for codebase of java objects
                   2360: #        $desuname - username for permanent storage of uploaded file
                   2361: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2362: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2363: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2364: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2365: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2366: # 
1.686     albertel 2367: # output: url of file in userspace, or error: <message> 
                   2368: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2369: 
1.531     albertel 2370: sub userfileupload {
1.860     raeburn  2371:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2372:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2373:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2374:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2375:     $fname=&clean_filename($fname);
1.315     www      2376: # See if there is anything left
1.257     www      2377:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2378:     chop($env{'form.'.$formname});
1.523     raeburn  2379:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2380:         my $now = time;
                   2381:         my $filepath = 'tmp/helprequests/'.$now;
                   2382:         my @parts=split(/\//,$filepath);
                   2383:         my $fullpath = $perlvar{'lonDaemons'};
                   2384:         for (my $i=0;$i<@parts;$i++) {
                   2385:             $fullpath .= '/'.$parts[$i];
                   2386:             if ((-e $fullpath)!=1) {
                   2387:                 mkdir($fullpath,0777);
                   2388:             }
                   2389:         }
                   2390:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2391:         print $fh $env{'form.'.$formname};
1.523     raeburn  2392:         close($fh);
1.741     raeburn  2393:         return $fullpath.'/'.$fname;
                   2394:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2395:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2396:                        '_'.$env{'user.domain'}.'/pending';
                   2397:         my @parts=split(/\//,$filepath);
                   2398:         my $fullpath = $perlvar{'lonDaemons'};
                   2399:         for (my $i=0;$i<@parts;$i++) {
                   2400:             $fullpath .= '/'.$parts[$i];
                   2401:             if ((-e $fullpath)!=1) {
                   2402:                 mkdir($fullpath,0777);
                   2403:             }
                   2404:         }
                   2405:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2406:         print $fh $env{'form.'.$formname};
                   2407:         close($fh);
                   2408:         return $fullpath.'/'.$fname;
1.523     raeburn  2409:     }
1.995     raeburn  2410:     if ($subdir eq 'scantron') {
                   2411:         $fname = 'scantron_orig_'.$fname;
                   2412:     } else {   
1.258     www      2413: # Create the directory if not present
1.995     raeburn  2414:         $fname="$subdir/$fname";
                   2415:     }
1.259     www      2416:     if ($coursedoc) {
1.638     albertel 2417: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2418: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2419:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2420:             return &finishuserfileupload($docuname,$docudom,
                   2421: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2422: 					 $codebase,$thumbwidth,$thumbheight,
                   2423:                                          $resizewidth,$resizeheight);
1.481     raeburn  2424:         } else {
1.620     albertel 2425:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2426:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2427: 				       $fname,$formname,$parser,
                   2428: 				       $allfiles,$codebase);
1.481     raeburn  2429:         }
1.719     banghart 2430:     } elsif (defined($destuname)) {
                   2431:         my $docuname=$destuname;
                   2432:         my $docudom=$destudom;
1.860     raeburn  2433: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2434: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2435:                                      $thumbwidth,$thumbheight,
                   2436:                                      $resizewidth,$resizeheight);
1.719     banghart 2437:         
1.259     www      2438:     } else {
1.638     albertel 2439:         my $docuname=$env{'user.name'};
                   2440:         my $docudom=$env{'user.domain'};
1.714     raeburn  2441:         if (exists($env{'form.group'})) {
                   2442:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2443:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2444:         }
1.860     raeburn  2445: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2446: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2447:                                      $thumbwidth,$thumbheight,
                   2448:                                      $resizewidth,$resizeheight);
1.259     www      2449:     }
1.271     www      2450: }
                   2451: 
                   2452: sub finishuserfileupload {
1.860     raeburn  2453:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051    raeburn  2454:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477     raeburn  2455:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2456:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2457:   
1.860     raeburn  2458:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2459:     $file=$fname;
                   2460:     if ($fname=~m|/|) {
                   2461:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2462: 	$path.=$fnamepath.'/';
                   2463:     }
1.259     www      2464:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2465:     my $count;
                   2466:     for ($count=4;$count<=$#parts;$count++) {
                   2467:         $filepath.="/$parts[$count]";
                   2468:         if ((-e $filepath)!=1) {
                   2469: 	    mkdir($filepath,0777);
                   2470:         }
                   2471:     }
1.984     neumanie 2472: 
1.258     www      2473: # Save the file
                   2474:     {
1.701     albertel 2475: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2476: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2477: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2478: 	    return '/adm/notfound.html';
                   2479: 	}
                   2480: 	if (!print FH ($env{'form.'.$formname})) {
                   2481: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2482: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2483: 	    return '/adm/notfound.html';
                   2484: 	}
1.570     albertel 2485: 	close(FH);
1.1051    raeburn  2486:         if ($resizewidth && $resizeheight) {
                   2487:             my $mm = new File::MMagic;
                   2488:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2489:             if ($mime_type =~ m{^image/}) {
                   2490: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2491:             }  
1.977     amueller 2492: 	}
1.258     www      2493:     }
1.637     raeburn  2494:     if ($parser eq 'parse') {
1.1024    raeburn  2495:         my $mm = new File::MMagic;
                   2496:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2497:         if ($mime_type eq 'text/html') {
                   2498:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2499:                                                        $allfiles,$codebase);
                   2500:             unless ($parse_result eq 'ok') {
                   2501:                 &logthis('Failed to parse '.$filepath.$file.
                   2502: 	   	         ' for embedded media: '.$parse_result); 
                   2503:             }
1.637     raeburn  2504:         }
                   2505:     }
1.860     raeburn  2506:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2507:         my $input = $filepath.'/'.$file;
                   2508:         my $output = $filepath.'/'.'tn-'.$file;
                   2509:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2510:         system("convert -sample $thumbsize $input $output");
                   2511:         if (-e $filepath.'/'.'tn-'.$file) {
                   2512:             $fetchthumb  = 1; 
                   2513:         }
                   2514:     }
1.858     raeburn  2515:  
1.259     www      2516: # Notify homeserver to grep it
                   2517: #
1.984     neumanie 2518:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2519:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2520:     if ($fetchresult eq 'ok') {
1.860     raeburn  2521:         if ($fetchthumb) {
                   2522:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2523:             if ($thumbresult ne 'ok') {
                   2524:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2525:                          $docuhome.': '.$thumbresult);
                   2526:             }
                   2527:         }
1.259     www      2528: #
1.258     www      2529: # Return the URL to it
1.494     albertel 2530:         return '/uploaded/'.$path.$file;
1.263     www      2531:     } else {
1.494     albertel 2532:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2533: 		 ': '.$fetchresult);
1.263     www      2534:         return '/adm/notfound.html';
1.858     raeburn  2535:     }
1.493     albertel 2536: }
                   2537: 
1.637     raeburn  2538: sub extract_embedded_items {
1.961     raeburn  2539:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2540:     my @state = ();
                   2541:     my %javafiles = (
                   2542:                       codebase => '',
                   2543:                       code => '',
                   2544:                       archive => ''
                   2545:                     );
                   2546:     my %mediafiles = (
                   2547:                       src => '',
                   2548:                       movie => '',
                   2549:                      );
1.648     raeburn  2550:     my $p;
                   2551:     if ($content) {
                   2552:         $p = HTML::LCParser->new($content);
                   2553:     } else {
1.961     raeburn  2554:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2555:     }
1.641     albertel 2556:     while (my $t=$p->get_token()) {
1.640     albertel 2557: 	if ($t->[0] eq 'S') {
                   2558: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2559: 	    push(@state, $tagname);
1.648     raeburn  2560:             if (lc($tagname) eq 'allow') {
                   2561:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2562:             }
1.640     albertel 2563: 	    if (lc($tagname) eq 'img') {
                   2564: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2565: 	    }
1.886     albertel 2566: 	    if (lc($tagname) eq 'a') {
                   2567: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2568: 	    }
1.645     raeburn  2569:             if (lc($tagname) eq 'script') {
                   2570:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2571:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2572:                 } else {
                   2573:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2574:                 }
                   2575:             }
                   2576:             if (lc($tagname) eq 'link') {
                   2577:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2578:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2579:                 }
                   2580:             }
1.640     albertel 2581: 	    if (lc($tagname) eq 'object' ||
                   2582: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2583: 		foreach my $item (keys(%javafiles)) {
                   2584: 		    $javafiles{$item} = '';
                   2585: 		}
                   2586: 	    }
                   2587: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2588: 		my $name = lc($attr->{'name'});
                   2589: 		foreach my $item (keys(%javafiles)) {
                   2590: 		    if ($name eq $item) {
                   2591: 			$javafiles{$item} = $attr->{'value'};
                   2592: 			last;
                   2593: 		    }
                   2594: 		}
                   2595: 		foreach my $item (keys(%mediafiles)) {
                   2596: 		    if ($name eq $item) {
                   2597: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2598: 			last;
                   2599: 		    }
                   2600: 		}
                   2601: 	    }
                   2602: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2603: 		foreach my $item (keys(%javafiles)) {
                   2604: 		    if ($attr->{$item}) {
                   2605: 			$javafiles{$item} = $attr->{$item};
                   2606: 			last;
                   2607: 		    }
                   2608: 		}
                   2609: 		foreach my $item (keys(%mediafiles)) {
                   2610: 		    if ($attr->{$item}) {
                   2611: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2612: 			last;
                   2613: 		    }
                   2614: 		}
                   2615: 	    }
                   2616: 	} elsif ($t->[0] eq 'E') {
                   2617: 	    my ($tagname) = ($t->[1]);
                   2618: 	    if ($javafiles{'codebase'} ne '') {
                   2619: 		$javafiles{'codebase'} .= '/';
                   2620: 	    }  
                   2621: 	    if (lc($tagname) eq 'applet' ||
                   2622: 		lc($tagname) eq 'object' ||
                   2623: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2624: 		) {
                   2625: 		foreach my $item (keys(%javafiles)) {
                   2626: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2627: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2628: 			&add_filetype($allfiles,$file,$item);
                   2629: 		    }
                   2630: 		}
                   2631: 	    } 
                   2632: 	    pop @state;
                   2633: 	}
                   2634:     }
1.637     raeburn  2635:     return 'ok';
                   2636: }
                   2637: 
1.639     albertel 2638: sub add_filetype {
                   2639:     my ($allfiles,$file,$type)=@_;
                   2640:     if (exists($allfiles->{$file})) {
                   2641: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2642: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2643: 	}
                   2644:     } else {
                   2645: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2646:     }
                   2647: }
                   2648: 
1.493     albertel 2649: sub removeuploadedurl {
1.984     neumanie 2650:     my ($url)=@_;	
                   2651:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2652:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2653: }
                   2654: 
                   2655: sub removeuserfile {
                   2656:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2657:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2658:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2659:     if ($result eq 'ok') {	
1.798     raeburn  2660:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2661:             my $metafile = $fname.'.meta';
                   2662:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2663: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2664:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2665:             my $sqlresult = 
1.823     albertel 2666:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2667:                                         'portfolio_metadata',$group,
                   2668:                                         'delete');
1.798     raeburn  2669:         }
                   2670:     }
                   2671:     return $result;
1.257     www      2672: }
1.15      www      2673: 
1.530     albertel 2674: sub mkdiruserfile {
                   2675:     my ($docuname,$docudom,$dir)=@_;
                   2676:     my $home=&homeserver($docuname,$docudom);
                   2677:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2678: }
                   2679: 
1.531     albertel 2680: sub renameuserfile {
                   2681:     my ($docuname,$docudom,$old,$new)=@_;
                   2682:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2683:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2684:                         &escape("$old").':'.&escape("$new"),$home);
                   2685:     if ($result eq 'ok') {
                   2686:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2687:             my $oldmeta = $old.'.meta';
                   2688:             my $newmeta = $new.'.meta';
                   2689:             my $metaresult = 
                   2690:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2691: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2692:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2693:             my $sqlresult = 
1.823     albertel 2694:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2695:                                         'portfolio_metadata',$group,
                   2696:                                         'delete');
1.798     raeburn  2697:         }
                   2698:     }
                   2699:     return $result;
1.531     albertel 2700: }
                   2701: 
1.14      www      2702: # ------------------------------------------------------------------------- Log
                   2703: 
                   2704: sub log {
                   2705:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2706:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2707: }
                   2708: 
                   2709: # ------------------------------------------------------------------ Course Log
1.352     www      2710: #
                   2711: # This routine flushes several buffers of non-mission-critical nature
                   2712: #
1.157     www      2713: 
                   2714: sub flushcourselogs {
1.352     www      2715:     &logthis('Flushing log buffers');
                   2716: #
                   2717: # course logs
                   2718: # This is a log of all transactions in a course, which can be used
                   2719: # for data mining purposes
                   2720: #
                   2721: # It also collects the courseid database, which lists last transaction
                   2722: # times and course titles for all courseids
                   2723: #
                   2724:     my %courseidbuffer=();
1.921     raeburn  2725:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2726:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2727: 		          &escape($courselogs{$crsid}),
                   2728: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2729: 	    delete $courselogs{$crsid};
                   2730:         } else {
                   2731:             &logthis('Failed to flush log buffer for '.$crsid);
                   2732:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2733:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2734:                         " exceeded maximum size, deleting.</font>");
                   2735:                delete $courselogs{$crsid};
                   2736:             }
1.352     www      2737:         }
1.920     raeburn  2738:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2739:             'description' => $coursedescrbuf{$crsid},
                   2740:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2741:             'type'        => $coursetypebuf{$crsid},
                   2742:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2743:         };
1.191     harris41 2744:     }
1.352     www      2745: #
                   2746: # Write course id database (reverse lookup) to homeserver of courses 
                   2747: # Is used in pickcourse
                   2748: #
1.840     albertel 2749:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2750:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2751:                                     $courseidbuffer{$crs_home},
                   2752:                                     $crs_home,'timeonly');
1.352     www      2753:     }
                   2754: #
                   2755: # File accesses
                   2756: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2757: #
1.449     matthew  2758:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2759:         if ($entry =~ /___count$/) {
                   2760:             my ($dom,$name);
1.807     albertel 2761:             ($dom,$name,undef)=
1.811     albertel 2762: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2763:             if (! defined($dom) || $dom eq '' || 
                   2764:                 ! defined($name) || $name eq '') {
1.620     albertel 2765:                 my $cid = $env{'request.course.id'};
                   2766:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2767:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2768:             }
1.450     matthew  2769:             my $value = $accesshash{$entry};
                   2770:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2771:             my %temphash=($url => $value);
1.449     matthew  2772:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2773:             if ($result eq 'ok') {
                   2774:                 delete $accesshash{$entry};
                   2775:             } elsif ($result eq 'unknown_cmd') {
                   2776:                 # Target server has old code running on it.
1.450     matthew  2777:                 my %temphash=($entry => $value);
1.449     matthew  2778:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2779:                     delete $accesshash{$entry};
                   2780:                 }
                   2781:             }
                   2782:         } else {
1.811     albertel 2783:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2784:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2785:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2786:                 delete $accesshash{$entry};
                   2787:             }
1.185     www      2788:         }
1.191     harris41 2789:     }
1.352     www      2790: #
                   2791: # Roles
                   2792: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2793: #
1.800     albertel 2794:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2795:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2796: 	    split(/\:/,$entry);
                   2797:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2798:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2799:                 $rudom,$runame) eq 'ok') {
                   2800: 	    delete $userrolehash{$entry};
                   2801:         }
                   2802:     }
1.662     raeburn  2803: #
                   2804: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2805: #
                   2806:     my %domrolebuffer = ();
1.1000    raeburn  2807:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2808:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2809:         if ($domrolebuffer{$rudom}) {
                   2810:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2811:                       '='.&escape($domainrolehash{$entry});
                   2812:         } else {
                   2813:             $domrolebuffer{$rudom}.=&escape($entry).
                   2814:                       '='.&escape($domainrolehash{$entry});
                   2815:         }
                   2816:         delete $domainrolehash{$entry};
                   2817:     }
                   2818:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2819: 	my %servers = &get_servers($dom,'library');
                   2820: 	foreach my $tryserver (keys(%servers)) {
                   2821: 	    unless (&reply('domroleput:'.$dom.':'.
                   2822: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2823: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2824: 	    }
1.662     raeburn  2825:         }
                   2826:     }
1.186     www      2827:     $dumpcount++;
1.157     www      2828: }
                   2829: 
                   2830: sub courselog {
                   2831:     my $what=shift;
1.158     www      2832:     $what=time.':'.$what;
1.620     albertel 2833:     unless ($env{'request.course.id'}) { return ''; }
                   2834:     $coursedombuf{$env{'request.course.id'}}=
                   2835:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2836:     $coursenumbuf{$env{'request.course.id'}}=
                   2837:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2838:     $coursehombuf{$env{'request.course.id'}}=
                   2839:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2840:     $coursedescrbuf{$env{'request.course.id'}}=
                   2841:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2842:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2843:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2844:     $courseownerbuf{$env{'request.course.id'}}=
                   2845:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2846:     $coursetypebuf{$env{'request.course.id'}}=
                   2847:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2848:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2849: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2850:     } else {
1.620     albertel 2851: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2852:     }
1.620     albertel 2853:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2854: 	&flushcourselogs();
                   2855:     }
1.158     www      2856: }
                   2857: 
                   2858: sub courseacclog {
                   2859:     my $fnsymb=shift;
1.620     albertel 2860:     unless ($env{'request.course.id'}) { return ''; }
                   2861:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2862:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2863:         $what.=':POST';
1.583     matthew  2864:         # FIXME: Probably ought to escape things....
1.800     albertel 2865: 	foreach my $key (keys(%env)) {
                   2866:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2867:                 my $formitem = $1;
                   2868:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2869:                     $what.=':'.$formitem.'='.$env{$key};
                   2870:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2871:                     $what.=':'.$formitem.'='.$env{$key};
                   2872:                 }
1.158     www      2873:             }
1.191     harris41 2874:         }
1.583     matthew  2875:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2876:         # FIXME: We should not be depending on a form parameter that someone
                   2877:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2878:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2879:             $what.= ':POST';
                   2880:             # FIXME: Probably ought to escape things....
                   2881:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2882:                                  'crsdiscuss') {
1.620     albertel 2883:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2884:             }
                   2885:         }
1.158     www      2886:     }
                   2887:     &courselog($what);
1.149     www      2888: }
                   2889: 
1.185     www      2890: sub countacc {
                   2891:     my $url=&declutter(shift);
1.458     matthew  2892:     return if (! defined($url) || $url eq '');
1.620     albertel 2893:     unless ($env{'request.course.id'}) { return ''; }
                   2894:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2895:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2896:     $accesshash{$key}++;
1.185     www      2897: }
1.349     www      2898: 
1.361     www      2899: sub linklog {
                   2900:     my ($from,$to)=@_;
                   2901:     $from=&declutter($from);
                   2902:     $to=&declutter($to);
                   2903:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2904:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2905: }
                   2906:   
1.349     www      2907: sub userrolelog {
                   2908:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2909:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2910:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2911:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2912:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2913:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2914:        $userrolehash
                   2915:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2916:                     =$tend.':'.$tstart;
1.662     raeburn  2917:     }
1.898     albertel 2918:     if (($env{'request.role'} =~ /dc\./) &&
                   2919: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2920: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2921: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2922:          ($trole=~/^co/))) {
1.898     albertel 2923:        $userrolehash
                   2924:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2925:                     =$tend.':'.$tstart;
                   2926:     }
1.662     raeburn  2927:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2928:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2929:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2930:         ($trole=~/^sc/)) {
                   2931:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2932:        $domainrolehash
                   2933:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2934:                     = $tend.':'.$tstart;
                   2935:     }
1.351     www      2936: }
                   2937: 
1.957     raeburn  2938: sub courserolelog {
                   2939:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2940:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2941:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2942:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2943:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2944:         ($trole eq 'co')) {
1.957     raeburn  2945:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2946:             my $cdom = $1;
                   2947:             my $cnum = $2;
                   2948:             my $sec = $3;
                   2949:             my $namespace = 'rolelog';
                   2950:             my %storehash = (
                   2951:                                role    => $trole,
                   2952:                                start   => $tstart,
                   2953:                                end     => $tend,
                   2954:                                selfenroll => $selfenroll,
                   2955:                                context    => $context,
                   2956:                             );
                   2957:             if ($trole eq 'gr') {
                   2958:                 $namespace = 'groupslog';
                   2959:                 $storehash{'group'} = $sec;
                   2960:             } else {
                   2961:                 $storehash{'section'} = $sec;
                   2962:             }
                   2963:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2964:             if (($trole ne 'st') || ($sec ne '')) {
                   2965:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2966:             }
1.957     raeburn  2967:         }
                   2968:     }
                   2969:     return;
                   2970: }
                   2971: 
1.351     www      2972: sub get_course_adv_roles {
1.948     raeburn  2973:     my ($cid,$codes) = @_;
1.620     albertel 2974:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2975:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2976:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2977:     my %nothide=();
1.800     albertel 2978:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2979:         if ($user !~ /:/) {
                   2980: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2981:         } else {
                   2982:             $nothide{$user}=1;
                   2983:         }
1.470     www      2984:     }
1.351     www      2985:     my %returnhash=();
                   2986:     my %dumphash=
                   2987:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2988:     my $now=time;
1.997     raeburn  2989:     my %privileged;
1.1000    raeburn  2990:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2991: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2992:         if (($tstart) && ($tstart<0)) { next; }
                   2993:         if (($tend) && ($tend<$now)) { next; }
                   2994:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2995:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2996: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2997:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2998:             my %dompersonnel =
1.998     raeburn  2999:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3000:             $privileged{$domain} = {};
                   3001:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3002:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3003:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3004:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3005:                         $privileged{$udom}{$uname} = 1;
                   3006:                     }
                   3007:                 }
                   3008:             }
                   3009:         }
                   3010:         if ((exists($privileged{$domain}{$username})) && 
                   3011:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3012: 	if ($role eq 'cr') { next; }
1.948     raeburn  3013:         if ($codes) {
                   3014:             if ($section) { $role .= ':'.$section; }
                   3015:             if ($returnhash{$role}) {
                   3016:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3017:             } else {
                   3018:                 $returnhash{$role}=$username.':'.$domain;
                   3019:             }
1.351     www      3020:         } else {
1.988     raeburn  3021:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3022:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3023:             if ($returnhash{$key}) {
                   3024: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3025:             } else {
                   3026:                 $returnhash{$key}=$username.':'.$domain;
                   3027:             }
1.351     www      3028:         }
1.948     raeburn  3029:     }
1.400     www      3030:     return %returnhash;
                   3031: }
                   3032: 
                   3033: sub get_my_roles {
1.937     raeburn  3034:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3035:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3036:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3037:     my (%dumphash,%nothide);
1.858     raeburn  3038:     if ($context eq 'userroles') { 
                   3039:         %dumphash = &dump('roles',$udom,$uname);
                   3040:     } else {
                   3041:         %dumphash=
1.400     www      3042:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3043:         if ($hidepriv) {
                   3044:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3045:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3046:                 if ($user !~ /:/) {
                   3047:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3048:                 } else {
                   3049:                     $nothide{$user} = 1;
                   3050:                 }
                   3051:             }
                   3052:         }
1.858     raeburn  3053:     }
1.400     www      3054:     my %returnhash=();
                   3055:     my $now=time;
1.999     raeburn  3056:     my %privileged;
1.800     albertel 3057:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3058:         my ($role,$tend,$tstart);
                   3059:         if ($context eq 'userroles') {
                   3060: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3061:         } else {
                   3062:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3063:         }
1.400     www      3064:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3065:         my $status = 'active';
1.939     raeburn  3066:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3067:             $status = 'previous';
                   3068:         } 
                   3069:         if (($tstart) && ($now<$tstart)) {
                   3070:             $status = 'future';
                   3071:         }
                   3072:         if (ref($types) eq 'ARRAY') {
                   3073:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3074:                 next;
                   3075:             } 
                   3076:         } else {
                   3077:             if ($status ne 'active') {
                   3078:                 next;
                   3079:             }
                   3080:         }
1.867     raeburn  3081:         my ($rolecode,$username,$domain,$section,$area);
                   3082:         if ($context eq 'userroles') {
                   3083:             ($area,$rolecode) = split(/_/,$entry);
                   3084:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3085:         } else {
                   3086:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3087:         }
1.832     raeburn  3088:         if (ref($roledoms) eq 'ARRAY') {
                   3089:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3090:                 next;
                   3091:             }
                   3092:         }
                   3093:         if (ref($roles) eq 'ARRAY') {
                   3094:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3095:                 if ($role =~ /^cr\//) {
                   3096:                     if (!grep(/^cr$/,@{$roles})) {
                   3097:                         next;
                   3098:                     }
                   3099:                 } else {
                   3100:                     next;
                   3101:                 }
1.832     raeburn  3102:             }
1.867     raeburn  3103:         }
1.937     raeburn  3104:         if ($hidepriv) {
1.999     raeburn  3105:             if ($context eq 'userroles') {
                   3106:                 if ((&privileged($username,$domain)) &&
                   3107:                     (!$nothide{$username.':'.$domain})) {
                   3108:                     next;
                   3109:                 }
                   3110:             } else {
                   3111:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3112:                     my %dompersonnel =
                   3113:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3114:                     $privileged{$domain} = {};
                   3115:                     if (keys(%dompersonnel)) {
                   3116:                         foreach my $server (keys(%dompersonnel)) {
                   3117:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3118:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3119:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3120:                                     $privileged{$udom}{$uname} = $trole;
                   3121:                                 }
                   3122:                             }
                   3123:                         }
                   3124:                     }
                   3125:                 }
                   3126:                 if (exists($privileged{$domain}{$username})) {
                   3127:                     if (!$nothide{$username.':'.$domain}) {
                   3128:                         next;
                   3129:                     }
                   3130:                 }
1.937     raeburn  3131:             }
                   3132:         }
1.933     raeburn  3133:         if ($withsec) {
                   3134:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3135:                 $tstart.':'.$tend;
                   3136:         } else {
                   3137:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3138:         }
1.832     raeburn  3139:     }
1.373     www      3140:     return %returnhash;
1.399     www      3141: }
                   3142: 
                   3143: # ----------------------------------------------------- Frontpage Announcements
                   3144: #
                   3145: #
                   3146: 
                   3147: sub postannounce {
                   3148:     my ($server,$text)=@_;
1.844     albertel 3149:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3150:     unless ($text=~/\w/) { $text=''; }
                   3151:     return &reply('setannounce:'.&escape($text),$server);
                   3152: }
                   3153: 
                   3154: sub getannounce {
1.448     albertel 3155: 
                   3156:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3157: 	my $announcement='';
1.800     albertel 3158: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3159: 	close($fh);
1.399     www      3160: 	if ($announcement=~/\w/) { 
                   3161: 	    return 
                   3162:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3163:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3164: 	} else {
                   3165: 	    return '';
                   3166: 	}
                   3167:     } else {
                   3168: 	return '';
                   3169:     }
1.351     www      3170: }
1.353     www      3171: 
                   3172: # ---------------------------------------------------------- Course ID routines
                   3173: # Deal with domain's nohist_courseid.db files
                   3174: #
                   3175: 
                   3176: sub courseidput {
1.921     raeburn  3177:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3178:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3179:     my $outcome;
                   3180:     if ($caller eq 'timeonly') {
                   3181:         my $cids = '';
                   3182:         foreach my $item (keys(%$storehash)) {
                   3183:             $cids.=&escape($item).'&';
                   3184:         }
                   3185:         $cids=~s/\&$//;
                   3186:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3187:                           $coursehome);       
                   3188:     } else {
                   3189:         my $items = '';
                   3190:         foreach my $item (keys(%$storehash)) {
                   3191:             $items.= &escape($item).'='.
                   3192:                      &freeze_escape($$storehash{$item}).'&';
                   3193:         }
                   3194:         $items=~s/\&$//;
                   3195:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3196:                           $coursehome);
1.918     raeburn  3197:     }
                   3198:     if ($outcome eq 'unknown_cmd') {
                   3199:         my $what;
                   3200:         foreach my $cid (keys(%$storehash)) {
                   3201:             $what .= &escape($cid).'=';
1.921     raeburn  3202:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3203:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3204:             }
                   3205:             $what =~ s/\:$/&/;
                   3206:         }
                   3207:         $what =~ s/\&$//;  
                   3208:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3209:     } else {
                   3210:         return $outcome;
                   3211:     }
1.353     www      3212: }
                   3213: 
                   3214: sub courseiddump {
1.921     raeburn  3215:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3216:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3217:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3218:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3219:     my $as_hash = 1;
                   3220:     my %returnhash;
                   3221:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3222:     my %libserv = &all_library();
                   3223:     foreach my $tryserver (keys(%libserv)) {
                   3224:         if ( (  $hostidflag == 1 
                   3225: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3226: 	     || (!defined($hostidflag)) ) {
                   3227: 
1.918     raeburn  3228: 	    if (($domfilter eq '') ||
                   3229: 		(&host_domain($tryserver) eq $domfilter)) {
                   3230:                 my $rep = 
                   3231:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3232:                          $sincefilter.':'.&escape($descfilter).':'.
                   3233:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3234:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3235:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3236:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3237:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3238:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3239:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3240:                          &escape($creationcontext).':'.$domcloner,
                   3241:                          $tryserver);
1.918     raeburn  3242:                 my @pairs=split(/\&/,$rep);
                   3243:                 foreach my $item (@pairs) {
                   3244:                     my ($key,$value)=split(/\=/,$item,2);
                   3245:                     $key = &unescape($key);
                   3246:                     next if ($key =~ /^error: 2 /);
                   3247:                     my $result = &thaw_unescape($value);
                   3248:                     if (ref($result) eq 'HASH') {
                   3249:                         $returnhash{$key}=$result;
                   3250:                     } else {
1.921     raeburn  3251:                         my @responses = split(/:/,$value);
                   3252:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3253:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3254:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3255:                         }
1.1008    raeburn  3256:                     }
1.353     www      3257:                 }
                   3258:             }
                   3259:         }
                   3260:     }
                   3261:     return %returnhash;
                   3262: }
                   3263: 
1.1055    raeburn  3264: sub courselastaccess {
                   3265:     my ($cdom,$cnum,$hostidref) = @_;
                   3266:     my %returnhash;
                   3267:     if ($cdom && $cnum) {
                   3268:         my $chome = &homeserver($cnum,$cdom);
                   3269:         if ($chome ne 'no_host') {
                   3270:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3271:             &extract_lastaccess(\%returnhash,$rep);
                   3272:         }
                   3273:     } else {
                   3274:         if (!$cdom) { $cdom=''; }
                   3275:         my %libserv = &all_library();
                   3276:         foreach my $tryserver (keys(%libserv)) {
                   3277:             if (ref($hostidref) eq 'ARRAY') {
                   3278:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3279:             } 
                   3280:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3281:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3282:                 &extract_lastaccess(\%returnhash,$rep);
                   3283:             }
                   3284:         }
                   3285:     }
                   3286:     return %returnhash;
                   3287: }
                   3288: 
                   3289: sub extract_lastaccess {
                   3290:     my ($returnhash,$rep) = @_;
                   3291:     if (ref($returnhash) eq 'HASH') {
                   3292:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3293:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3294:                  $rep eq '') {
                   3295:             my @pairs=split(/\&/,$rep);
                   3296:             foreach my $item (@pairs) {
                   3297:                 my ($key,$value)=split(/\=/,$item,2);
                   3298:                 $key = &unescape($key);
                   3299:                 next if ($key =~ /^error: 2 /);
                   3300:                 $returnhash->{$key} = &thaw_unescape($value);
                   3301:             }
                   3302:         }
                   3303:     }
                   3304:     return;
                   3305: }
                   3306: 
1.658     raeburn  3307: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3308: 
                   3309: sub dcmailput {
1.685     raeburn  3310:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3311:     my $status = &Apache::lonnet::critical(
1.740     www      3312:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3313:        &escape($message),$server);
1.662     raeburn  3314:     return $status;
                   3315: }
                   3316: 
1.658     raeburn  3317: sub dcmaildump {
                   3318:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3319:     my %returnhash=();
1.846     albertel 3320: 
                   3321:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3322:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3323:                                                          &escape($enddate).':';
                   3324: 	my @esc_senders=map { &escape($_)} @$senders;
                   3325: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3326: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3327:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3328:             if (($key) && ($value)) {
                   3329:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3330:             }
                   3331:         }
                   3332:     }
                   3333:     return %returnhash;
                   3334: }
1.662     raeburn  3335: # ---------------------------------------------------------- Domain roles
                   3336: 
                   3337: sub get_domain_roles {
                   3338:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3339:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3340:         $startdate = '.';
                   3341:     }
1.1018    raeburn  3342:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3343:         $enddate = '.';
                   3344:     }
1.922     raeburn  3345:     my $rolelist;
                   3346:     if (ref($roles) eq 'ARRAY') {
                   3347:         $rolelist = join(':',@{$roles});
                   3348:     }
1.662     raeburn  3349:     my %personnel = ();
1.841     albertel 3350: 
                   3351:     my %servers = &get_servers($dom,'library');
                   3352:     foreach my $tryserver (keys(%servers)) {
                   3353: 	%{$personnel{$tryserver}}=();
                   3354: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3355: 					    &escape($startdate).':'.
                   3356: 					    &escape($enddate).':'.
                   3357: 					    &escape($rolelist), $tryserver))) {
                   3358: 	    my ($key,$value) = split(/\=/,$line,2);
                   3359: 	    if (($key) && ($value)) {
                   3360: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3361: 	    }
                   3362: 	}
1.662     raeburn  3363:     }
                   3364:     return %personnel;
                   3365: }
1.658     raeburn  3366: 
1.1057    www      3367: # ----------------------------------------------------------- Interval timing 
1.149     www      3368: 
1.504     albertel 3369: sub get_first_access {
                   3370:     my ($type,$argsymb)=@_;
1.790     albertel 3371:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3372:     if ($argsymb) { $symb=$argsymb; }
                   3373:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3374:     if ($type eq 'course') {
                   3375: 	$res='course';
                   3376:     } elsif ($type eq 'map') {
1.588     albertel 3377: 	$res=&symbread($map);
                   3378:     } else {
                   3379: 	$res=$symb;
                   3380:     }
                   3381:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3382:     return $times{"$courseid\0$res"};
1.504     albertel 3383: }
                   3384: 
                   3385: sub set_first_access {
                   3386:     my ($type)=@_;
1.790     albertel 3387:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3388:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3389:     if ($type eq 'course') {
                   3390: 	$res='course';
                   3391:     } elsif ($type eq 'map') {
1.588     albertel 3392: 	$res=&symbread($map);
                   3393:     } else {
                   3394: 	$res=$symb;
                   3395:     }
                   3396:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3397:     if (!$firstaccess) {
1.588     albertel 3398: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3399:     }
                   3400:     return 'already_set';
1.504     albertel 3401: }
                   3402: 
1.110     www      3403: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3404: 
                   3405: sub expirespread {
                   3406:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3407:     my $cid=$env{'request.course.id'}; 
1.110     www      3408:     if ($cid) {
                   3409:        my $now=time;
                   3410:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3411:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3412:                             $env{'course.'.$cid.'.num'}.
1.110     www      3413: 	        	    ':nohist_expirationdates:'.
                   3414:                             &escape($key).'='.$now,
1.620     albertel 3415:                             $env{'course.'.$cid.'.home'})
1.110     www      3416:     }
                   3417:     return 'ok';
1.14      www      3418: }
                   3419: 
1.109     www      3420: # ----------------------------------------------------- Devalidate Spreadsheets
                   3421: 
                   3422: sub devalidate {
1.325     www      3423:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3424:     my $cid=$env{'request.course.id'}; 
1.109     www      3425:     if ($cid) {
1.391     matthew  3426:         # delete the stored spreadsheets for
                   3427:         # - the student level sheet of this user in course's homespace
                   3428:         # - the assessment level sheet for this resource 
                   3429:         #   for this user in user's homespace
1.553     albertel 3430: 	# - current conditional state info
1.325     www      3431: 	my $key=$uname.':'.$udom.':';
1.109     www      3432:         my $status=
1.299     matthew  3433: 	    &del('nohist_calculatedsheets',
1.391     matthew  3434: 		 [$key.'studentcalc:'],
1.620     albertel 3435: 		 $env{'course.'.$cid.'.domain'},
                   3436: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3437: 		.' '.
                   3438: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3439: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3440:         unless ($status eq 'ok ok') {
                   3441:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3442:                     $uname.' at '.$udom.' for '.
1.109     www      3443: 		    $symb.': '.$status);
1.133     albertel 3444:         }
1.553     albertel 3445: 	&delenv('user.state.'.$cid);
1.109     www      3446:     }
                   3447: }
                   3448: 
1.265     albertel 3449: sub get_scalar {
                   3450:     my ($string,$end) = @_;
                   3451:     my $value;
                   3452:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3453: 	$value = $1;
                   3454:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3455: 	$value = $1;
                   3456:     }
                   3457:     return &unescape($value);
                   3458: }
                   3459: 
                   3460: sub array2str {
                   3461:   my (@array) = @_;
                   3462:   my $result=&arrayref2str(\@array);
                   3463:   $result=~s/^__ARRAY_REF__//;
                   3464:   $result=~s/__END_ARRAY_REF__$//;
                   3465:   return $result;
                   3466: }
                   3467: 
1.204     albertel 3468: sub arrayref2str {
                   3469:   my ($arrayref) = @_;
1.265     albertel 3470:   my $result='__ARRAY_REF__';
1.204     albertel 3471:   foreach my $elem (@$arrayref) {
1.265     albertel 3472:     if(ref($elem) eq 'ARRAY') {
                   3473:       $result.=&arrayref2str($elem).'&';
                   3474:     } elsif(ref($elem) eq 'HASH') {
                   3475:       $result.=&hashref2str($elem).'&';
                   3476:     } elsif(ref($elem)) {
                   3477:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3478:     } else {
                   3479:       $result.=&escape($elem).'&';
                   3480:     }
                   3481:   }
                   3482:   $result=~s/\&$//;
1.265     albertel 3483:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3484:   return $result;
                   3485: }
                   3486: 
1.168     albertel 3487: sub hash2str {
1.204     albertel 3488:   my (%hash) = @_;
                   3489:   my $result=&hashref2str(\%hash);
1.265     albertel 3490:   $result=~s/^__HASH_REF__//;
                   3491:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3492:   return $result;
                   3493: }
                   3494: 
                   3495: sub hashref2str {
                   3496:   my ($hashref)=@_;
1.265     albertel 3497:   my $result='__HASH_REF__';
1.800     albertel 3498:   foreach my $key (sort(keys(%$hashref))) {
                   3499:     if (ref($key) eq 'ARRAY') {
                   3500:       $result.=&arrayref2str($key).'=';
                   3501:     } elsif (ref($key) eq 'HASH') {
                   3502:       $result.=&hashref2str($key).'=';
                   3503:     } elsif (ref($key)) {
1.265     albertel 3504:       $result.='=';
1.800     albertel 3505:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3506:     } else {
1.800     albertel 3507: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3508:     }
                   3509: 
1.800     albertel 3510:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3511:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3512:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3513:       $result.=&hashref2str($hashref->{$key}).'&';
                   3514:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3515:        $result.='&';
1.800     albertel 3516:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3517:     } else {
1.800     albertel 3518:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3519:     }
                   3520:   }
1.168     albertel 3521:   $result=~s/\&$//;
1.265     albertel 3522:   $result .= '__END_HASH_REF__';
1.168     albertel 3523:   return $result;
                   3524: }
                   3525: 
                   3526: sub str2hash {
1.265     albertel 3527:     my ($string)=@_;
                   3528:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3529:     return %$hash;
                   3530: }
                   3531: 
                   3532: sub str2hashref {
1.168     albertel 3533:   my ($string) = @_;
1.265     albertel 3534: 
                   3535:   my %hash;
                   3536: 
                   3537:   if($string !~ /^__HASH_REF__/) {
                   3538:       if (! ($string eq '' || !defined($string))) {
                   3539: 	  $hash{'error'}='Not hash reference';
                   3540:       }
                   3541:       return (\%hash, $string);
                   3542:   }
                   3543: 
                   3544:   $string =~ s/^__HASH_REF__//;
                   3545: 
                   3546:   while($string !~ /^__END_HASH_REF__/) {
                   3547:       #key
                   3548:       my $key='';
                   3549:       if($string =~ /^__HASH_REF__/) {
                   3550:           ($key, $string)=&str2hashref($string);
                   3551:           if(defined($key->{'error'})) {
                   3552:               $hash{'error'}='Bad data';
                   3553:               return (\%hash, $string);
                   3554:           }
                   3555:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3556:           ($key, $string)=&str2arrayref($string);
                   3557:           if($key->[0] eq 'Array reference error') {
                   3558:               $hash{'error'}='Bad data';
                   3559:               return (\%hash, $string);
                   3560:           }
                   3561:       } else {
                   3562:           $string =~ s/^(.*?)=//;
1.267     albertel 3563: 	  $key=&unescape($1);
1.265     albertel 3564:       }
                   3565:       $string =~ s/^=//;
                   3566: 
                   3567:       #value
                   3568:       my $value='';
                   3569:       if($string =~ /^__HASH_REF__/) {
                   3570:           ($value, $string)=&str2hashref($string);
                   3571:           if(defined($value->{'error'})) {
                   3572:               $hash{'error'}='Bad data';
                   3573:               return (\%hash, $string);
                   3574:           }
                   3575:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3576:           ($value, $string)=&str2arrayref($string);
                   3577:           if($value->[0] eq 'Array reference error') {
                   3578:               $hash{'error'}='Bad data';
                   3579:               return (\%hash, $string);
                   3580:           }
                   3581:       } else {
                   3582: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3583:       }
                   3584:       $string =~ s/^&//;
                   3585: 
                   3586:       $hash{$key}=$value;
1.204     albertel 3587:   }
1.265     albertel 3588: 
                   3589:   $string =~ s/^__END_HASH_REF__//;
                   3590: 
                   3591:   return (\%hash, $string);
1.204     albertel 3592: }
                   3593: 
                   3594: sub str2array {
1.265     albertel 3595:     my ($string)=@_;
                   3596:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3597:     return @$array;
                   3598: }
                   3599: 
                   3600: sub str2arrayref {
1.204     albertel 3601:   my ($string) = @_;
1.265     albertel 3602:   my @array;
                   3603: 
                   3604:   if($string !~ /^__ARRAY_REF__/) {
                   3605:       if (! ($string eq '' || !defined($string))) {
                   3606: 	  $array[0]='Array reference error';
                   3607:       }
                   3608:       return (\@array, $string);
                   3609:   }
                   3610: 
                   3611:   $string =~ s/^__ARRAY_REF__//;
                   3612: 
                   3613:   while($string !~ /^__END_ARRAY_REF__/) {
                   3614:       my $value='';
                   3615:       if($string =~ /^__HASH_REF__/) {
                   3616:           ($value, $string)=&str2hashref($string);
                   3617:           if(defined($value->{'error'})) {
                   3618:               $array[0] ='Array reference error';
                   3619:               return (\@array, $string);
                   3620:           }
                   3621:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3622:           ($value, $string)=&str2arrayref($string);
                   3623:           if($value->[0] eq 'Array reference error') {
                   3624:               $array[0] ='Array reference error';
                   3625:               return (\@array, $string);
                   3626:           }
                   3627:       } else {
                   3628: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3629:       }
                   3630:       $string =~ s/^&//;
                   3631: 
                   3632:       push(@array, $value);
1.191     harris41 3633:   }
1.265     albertel 3634: 
                   3635:   $string =~ s/^__END_ARRAY_REF__//;
                   3636: 
                   3637:   return (\@array, $string);
1.168     albertel 3638: }
                   3639: 
1.167     albertel 3640: # -------------------------------------------------------------------Temp Store
                   3641: 
1.168     albertel 3642: sub tmpreset {
                   3643:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3644:   if (!$symb) {
                   3645:     $symb=&symbread();
1.620     albertel 3646:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3647:   }
                   3648:   $symb=escape($symb);
                   3649: 
1.620     albertel 3650:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3651:   $namespace=~s/\//\_/g;
                   3652:   $namespace=~s/\W//g;
                   3653: 
1.620     albertel 3654:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3655:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3656:   if ($domain eq 'public' && $stuname eq 'public') {
                   3657:       $stuname=$ENV{'REMOTE_ADDR'};
                   3658:   }
1.168     albertel 3659:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3660:   my %hash;
                   3661:   if (tie(%hash,'GDBM_File',
                   3662: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3663: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3664:     foreach my $key (keys(%hash)) {
1.180     albertel 3665:       if ($key=~ /:$symb/) {
1.168     albertel 3666: 	delete($hash{$key});
                   3667:       }
                   3668:     }
                   3669:   }
                   3670: }
                   3671: 
1.167     albertel 3672: sub tmpstore {
1.168     albertel 3673:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3674: 
                   3675:   if (!$symb) {
                   3676:     $symb=&symbread();
1.620     albertel 3677:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3678:   }
                   3679:   $symb=escape($symb);
                   3680: 
                   3681:   if (!$namespace) {
                   3682:     # I don't think we would ever want to store this for a course.
                   3683:     # it seems this will only be used if we don't have a course.
1.620     albertel 3684:     #$namespace=$env{'request.course.id'};
1.168     albertel 3685:     #if (!$namespace) {
1.620     albertel 3686:       $namespace=$env{'request.state'};
1.168     albertel 3687:     #}
                   3688:   }
                   3689:   $namespace=~s/\//\_/g;
                   3690:   $namespace=~s/\W//g;
1.620     albertel 3691:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3692:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3693:   if ($domain eq 'public' && $stuname eq 'public') {
                   3694:       $stuname=$ENV{'REMOTE_ADDR'};
                   3695:   }
1.168     albertel 3696:   my $now=time;
                   3697:   my %hash;
                   3698:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3699:   if (tie(%hash,'GDBM_File',
                   3700: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3701: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3702:     $hash{"version:$symb"}++;
                   3703:     my $version=$hash{"version:$symb"};
                   3704:     my $allkeys=''; 
                   3705:     foreach my $key (keys(%$storehash)) {
                   3706:       $allkeys.=$key.':';
1.591     albertel 3707:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3708:     }
                   3709:     $hash{"$version:$symb:timestamp"}=$now;
                   3710:     $allkeys.='timestamp';
                   3711:     $hash{"$version:keys:$symb"}=$allkeys;
                   3712:     if (untie(%hash)) {
                   3713:       return 'ok';
                   3714:     } else {
                   3715:       return "error:$!";
                   3716:     }
                   3717:   } else {
                   3718:     return "error:$!";
                   3719:   }
                   3720: }
1.167     albertel 3721: 
1.168     albertel 3722: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3723: 
1.168     albertel 3724: sub tmprestore {
                   3725:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3726: 
1.168     albertel 3727:   if (!$symb) {
                   3728:     $symb=&symbread();
1.620     albertel 3729:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3730:   }
                   3731:   $symb=escape($symb);
                   3732: 
1.620     albertel 3733:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3734: 
1.620     albertel 3735:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3736:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3737:   if ($domain eq 'public' && $stuname eq 'public') {
                   3738:       $stuname=$ENV{'REMOTE_ADDR'};
                   3739:   }
1.168     albertel 3740:   my %returnhash;
                   3741:   $namespace=~s/\//\_/g;
                   3742:   $namespace=~s/\W//g;
                   3743:   my %hash;
                   3744:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3745:   if (tie(%hash,'GDBM_File',
                   3746: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3747: 	  &GDBM_READER(),0640)) {
1.168     albertel 3748:     my $version=$hash{"version:$symb"};
                   3749:     $returnhash{'version'}=$version;
                   3750:     my $scope;
                   3751:     for ($scope=1;$scope<=$version;$scope++) {
                   3752:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3753:       my @keys=split(/:/,$vkeys);
                   3754:       my $key;
                   3755:       $returnhash{"$scope:keys"}=$vkeys;
                   3756:       foreach $key (@keys) {
1.591     albertel 3757: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3758: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3759:       }
                   3760:     }
1.168     albertel 3761:     if (!(untie(%hash))) {
                   3762:       return "error:$!";
                   3763:     }
                   3764:   } else {
                   3765:     return "error:$!";
                   3766:   }
                   3767:   return %returnhash;
1.167     albertel 3768: }
                   3769: 
1.9       www      3770: # ----------------------------------------------------------------------- Store
                   3771: 
                   3772: sub store {
1.124     www      3773:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3774:     my $home='';
                   3775: 
1.168     albertel 3776:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3777: 
1.213     www      3778:     $symb=&symbclean($symb);
1.122     albertel 3779:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3780: 
1.620     albertel 3781:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3782:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3783: 
                   3784:     &devalidate($symb,$stuname,$domain);
1.109     www      3785: 
                   3786:     $symb=escape($symb);
1.187     www      3787:     if (!$namespace) { 
1.620     albertel 3788:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3789:           return ''; 
                   3790:        } 
                   3791:     }
1.620     albertel 3792:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3793: 
                   3794:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3795:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3796: 
1.12      www      3797:     my $namevalue='';
1.800     albertel 3798:     foreach my $key (keys(%$storehash)) {
                   3799:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3800:     }
1.12      www      3801:     $namevalue=~s/\&$//;
1.187     www      3802:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3803:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3804: }
                   3805: 
1.47      www      3806: # -------------------------------------------------------------- Critical Store
                   3807: 
                   3808: sub cstore {
1.124     www      3809:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3810:     my $home='';
                   3811: 
1.168     albertel 3812:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3813: 
1.213     www      3814:     $symb=&symbclean($symb);
1.122     albertel 3815:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3816: 
1.620     albertel 3817:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3818:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3819: 
                   3820:     &devalidate($symb,$stuname,$domain);
1.109     www      3821: 
                   3822:     $symb=escape($symb);
1.187     www      3823:     if (!$namespace) { 
1.620     albertel 3824:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3825:           return ''; 
                   3826:        } 
                   3827:     }
1.620     albertel 3828:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3829: 
                   3830:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3831:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3832: 
1.47      www      3833:     my $namevalue='';
1.800     albertel 3834:     foreach my $key (keys(%$storehash)) {
                   3835:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3836:     }
1.47      www      3837:     $namevalue=~s/\&$//;
1.187     www      3838:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3839:     return critical
                   3840:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3841: }
                   3842: 
1.9       www      3843: # --------------------------------------------------------------------- Restore
                   3844: 
                   3845: sub restore {
1.124     www      3846:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3847:     my $home='';
                   3848: 
1.168     albertel 3849:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3850: 
1.122     albertel 3851:     if (!$symb) {
                   3852:       unless ($symb=escape(&symbread())) { return ''; }
                   3853:     } else {
1.213     www      3854:       $symb=&escape(&symbclean($symb));
1.122     albertel 3855:     }
1.188     www      3856:     if (!$namespace) { 
1.620     albertel 3857:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3858:           return ''; 
                   3859:        } 
                   3860:     }
1.620     albertel 3861:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3862:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3863:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3864:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3865: 
1.12      www      3866:     my %returnhash=();
1.800     albertel 3867:     foreach my $line (split(/\&/,$answer)) {
                   3868: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3869:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3870:     }
1.75      www      3871:     my $version;
                   3872:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3873:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3874:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3875:        }
1.75      www      3876:     }
1.13      www      3877:     return %returnhash;
1.34      www      3878: }
                   3879: 
                   3880: # ---------------------------------------------------------- Course Description
                   3881: 
                   3882: sub coursedescription {
1.731     albertel 3883:     my ($courseid,$args)=@_;
1.34      www      3884:     $courseid=~s/^\///;
1.49      www      3885:     $courseid=~s/\_/\//g;
1.34      www      3886:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3887:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3888:     my $normalid=$cdomain.'_'.$cnum;
                   3889:     # need to always cache even if we get errors otherwise we keep 
                   3890:     # trying and trying and trying to get the course description.
                   3891:     my %envhash=();
                   3892:     my %returnhash=();
1.731     albertel 3893:     
                   3894:     my $expiretime=600;
                   3895:     if ($env{'request.course.id'} eq $normalid) {
                   3896: 	$expiretime=120;
                   3897:     }
                   3898: 
                   3899:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3900:     if (!$args->{'freshen_cache'}
                   3901: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3902: 	foreach my $key (keys(%env)) {
                   3903: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3904: 	    my ($setting) = $1;
                   3905: 	    $returnhash{$setting} = $env{$key};
                   3906: 	}
                   3907: 	return %returnhash;
                   3908:     }
                   3909: 
                   3910:     # get the data agin
                   3911:     if (!$args->{'one_time'}) {
                   3912: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3913:     }
1.811     albertel 3914: 
1.34      www      3915:     if ($chome ne 'no_host') {
1.302     albertel 3916:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3917:        if (!exists($returnhash{'con_lost'})) {
                   3918:            $returnhash{'home'}= $chome;
                   3919: 	   $returnhash{'domain'} = $cdomain;
                   3920: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3921:            if (!defined($returnhash{'type'})) {
                   3922:                $returnhash{'type'} = 'Course';
                   3923:            }
1.130     albertel 3924:            while (my ($name,$value) = each %returnhash) {
1.53      www      3925:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3926:            }
1.270     www      3927:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3928:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3929: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3930:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3931:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3932:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3933:        }
                   3934:     }
1.731     albertel 3935:     if (!$args->{'one_time'}) {
1.949     raeburn  3936: 	&appenv(\%envhash);
1.731     albertel 3937:     }
1.302     albertel 3938:     return %returnhash;
1.461     www      3939: }
                   3940: 
1.1080    raeburn  3941: sub update_released_required {
                   3942:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   3943:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   3944:         $cid = $env{'request.course.id'};
                   3945:         $cdom = $env{'course.'.$cid.'.domain'};
                   3946:         $cnum = $env{'course.'.$cid.'.num'};
                   3947:         $chome = $env{'course.'.$cid.'.home'};
                   3948:     }
                   3949:     if ($needsrelease) {
                   3950:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   3951:         my $needsupdate;
                   3952:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   3953:             $needsupdate = 1;
                   3954:         } else {
                   3955:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   3956:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   3957:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   3958:                 $needsupdate = 1;
                   3959:             }
                   3960:         }
                   3961:         if ($needsupdate) {
                   3962:             my %needshash = (
                   3963:                              'internal.releaserequired' => $needsrelease,
                   3964:                             );
                   3965:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   3966:             if ($putresult eq 'ok') {
                   3967:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   3968:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   3969:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   3970:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   3971:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   3972:                 }
                   3973:             }
                   3974:         }
                   3975:     }
                   3976:     return;
                   3977: }
                   3978: 
1.461     www      3979: # -------------------------------------------------See if a user is privileged
                   3980: 
                   3981: sub privileged {
                   3982:     my ($username,$domain)=@_;
                   3983:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3984: 			&homeserver($username,$domain));
1.1033    raeburn  3985:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3986:         ($rolesdump =~ /^error:/)) {
                   3987:         return 0;
                   3988:     }
1.461     www      3989:     my $now=time;
                   3990:     if ($rolesdump ne '') {
1.800     albertel 3991:         foreach my $entry (split(/&/,$rolesdump)) {
                   3992: 	    if ($entry!~/^rolesdef_/) {
                   3993: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3994: 		$area=~s/\_\w\w$//;
                   3995: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3996: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3997: 		    my $active=1;
                   3998: 		    if ($tend) {
                   3999: 			if ($tend<$now) { $active=0; }
                   4000: 		    }
                   4001: 		    if ($tstart) {
                   4002: 			if ($tstart>$now) { $active=0; }
                   4003: 		    }
                   4004: 		    if ($active) { return 1; }
                   4005: 		}
                   4006: 	    }
                   4007: 	}
                   4008:     }
                   4009:     return 0;
1.9       www      4010: }
1.1       albertel 4011: 
1.103     harris41 4012: # -------------------------------------------------------- Get user privileges
1.11      www      4013: 
                   4014: sub rolesinit {
                   4015:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4016:     my $now=time;
                   4017:     my %userroles = ('user.login.time' => $now);
1.1078    raeburn  4018:     my $extra = &freeze_escape({'clientcheckrole' => 1});
                   4019:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4020:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4021:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4022:         return \%userroles;
                   4023:     }
1.11      www      4024:     my %allroles=();
1.678     raeburn  4025:     my %allgroups=();   
                   4026:     my $group_privs;
1.11      www      4027: 
                   4028:     if ($rolesdump ne '') {
1.800     albertel 4029:         foreach my $entry (split(/&/,$rolesdump)) {
                   4030: 	  if ($entry!~/^rolesdef_/) {
                   4031:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4032: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4033:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4034: 	    if ($role=~/^cr/) { 
1.807     albertel 4035: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4036: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4037: 		    ($tend,$tstart)=split('_',$trest);
                   4038: 		} else {
                   4039: 		    $trole=$role;
                   4040: 		}
1.678     raeburn  4041:             } elsif ($role =~ m|^gr/|) {
                   4042:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4043:                 ($trole,$group_privs) = split(/\//,$trole);
                   4044:                 $group_privs = &unescape($group_privs);
1.587     albertel 4045: 	    } else {
                   4046: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4047: 	    }
1.743     albertel 4048: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4049: 					 $username);
                   4050: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4051:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4052:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4053:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4054: 		my $spec=$trole.'.'.$area;
                   4055: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4056: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4057:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4058:                 } elsif ($trole eq 'gr') {
                   4059:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4060: 		} else {
1.567     raeburn  4061:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4062: 		}
1.12      www      4063:             }
1.662     raeburn  4064:           }
1.191     harris41 4065:         }
1.743     albertel 4066:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4067:         $userroles{'user.adv'}    = $adv;
                   4068: 	$userroles{'user.author'} = $author;
1.620     albertel 4069:         $env{'user.adv'}=$adv;
1.11      www      4070:     }
1.743     albertel 4071:     return \%userroles;  
1.11      www      4072: }
                   4073: 
1.567     raeburn  4074: sub set_arearole {
                   4075:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4076: # log the associated role with the area
                   4077:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4078:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4079: }
                   4080: 
                   4081: sub custom_roleprivs {
                   4082:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4083:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4084:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4085:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4086:         my ($rdummy,$roledef)=
                   4087:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4088:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4089:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4090:             if (defined($syspriv)) {
1.1043    raeburn  4091:                 if ($trest =~ /^$match_community$/) {
                   4092:                     $syspriv =~ s/bre\&S//; 
                   4093:                 }
1.567     raeburn  4094:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4095:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4096:             }
                   4097:             if ($tdomain ne '') {
                   4098:                 if (defined($dompriv)) {
                   4099:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4100:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4101:                 }
                   4102:                 if (($trest ne '') && (defined($coursepriv))) {
                   4103:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4104:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4105:                 }
                   4106:             }
                   4107:         }
                   4108:     }
                   4109: }
                   4110: 
1.678     raeburn  4111: sub group_roleprivs {
                   4112:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4113:     my $access = 1;
                   4114:     my $now = time;
                   4115:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4116:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4117:     if ($access) {
1.811     albertel 4118:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4119:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4120:     }
                   4121: }
1.567     raeburn  4122: 
                   4123: sub standard_roleprivs {
                   4124:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4125:     if (defined($pr{$trole.':s'})) {
                   4126:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4127:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4128:     }
                   4129:     if ($tdomain ne '') {
                   4130:         if (defined($pr{$trole.':d'})) {
                   4131:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4132:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4133:         }
                   4134:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4135:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4136:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4137:         }
                   4138:     }
                   4139: }
                   4140: 
                   4141: sub set_userprivs {
1.1064    raeburn  4142:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4143:     my $author=0;
                   4144:     my $adv=0;
1.678     raeburn  4145:     my %grouproles = ();
                   4146:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4147:         my @groupkeys; 
1.1000    raeburn  4148:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4149:             push(@groupkeys,$role);
                   4150:         }
                   4151:         if (ref($groups_roles) eq 'HASH') {
                   4152:             foreach my $key (keys(%{$groups_roles})) {
                   4153:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4154:                     push(@groupkeys,$key);
                   4155:                 }
                   4156:             }
                   4157:         }
                   4158:         if (@groupkeys > 0) {
                   4159:             foreach my $role (@groupkeys) {
                   4160:                 my ($trole,$area,$sec,$extendedarea);
                   4161:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4162:                     $trole = $1;
                   4163:                     $area = $2;
                   4164:                     $sec = $3;
                   4165:                     $extendedarea = $area.$sec;
                   4166:                     if (exists($$allgroups{$area})) {
                   4167:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4168:                             my $spec = $trole.'.'.$extendedarea;
                   4169:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4170:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4171:                         }
1.678     raeburn  4172:                     }
                   4173:                 }
                   4174:             }
                   4175:         }
                   4176:     }
1.800     albertel 4177:     foreach my $group (keys(%grouproles)) {
                   4178:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4179:     }
1.800     albertel 4180:     foreach my $role (keys(%{$allroles})) {
                   4181:         my %thesepriv;
1.941     raeburn  4182:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4183:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4184:             if ($item ne '') {
                   4185:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4186:                 if ($restrictions eq '') {
                   4187:                     $thesepriv{$privilege}='F';
                   4188:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4189:                     $thesepriv{$privilege}.=$restrictions;
                   4190:                 }
                   4191:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4192:             }
                   4193:         }
                   4194:         my $thesestr='';
1.800     albertel 4195:         foreach my $priv (keys(%thesepriv)) {
                   4196: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4197: 	}
                   4198:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4199:     }
                   4200:     return ($author,$adv);
                   4201: }
                   4202: 
1.994     raeburn  4203: sub role_status {
1.1002    raeburn  4204:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4205:     my @pwhere = ();
                   4206:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4207:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4208:         unless (!defined($$role) || $$role eq '') {
                   4209:             $$where=join('.',@pwhere);
                   4210:             $$trolecode=$$role.'.'.$$where;
                   4211:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4212:             $$tstatus='is';
                   4213:             if ($$tstart && $$tstart>$then) {
                   4214:                 $$tstatus='future';
1.1034    raeburn  4215:                 if ($$tstart<$now) {
                   4216:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4217:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4218:                             my (%allroles,%allgroups,$group_privs,
                   4219:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4220:                             my %userroles = (
                   4221:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4222:                             );
1.1064    raeburn  4223:                             @rolecodes = ('cm'); 
1.1002    raeburn  4224:                             my $spec=$$role.'.'.$$where;
                   4225:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4226:                             if ($$role =~ /^cr\//) {
                   4227:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4228:                                 push(@rolecodes,'cr');
1.1002    raeburn  4229:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4230:                                 push(@rolecodes,$$role);
1.1002    raeburn  4231:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4232:                                                     $env{'user.name'});
1.1064    raeburn  4233:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4234:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4235:                                 $group_privs = &unescape($group_privs);
                   4236:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4237:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4238:                                 if (keys(%course_roles) > 0) {
                   4239:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4240:                                     if ($tdomain ne '' && $tnum ne '') { 
                   4241:                                         foreach my $key (keys(%course_roles)) {
                   4242:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4243:                                                 my $crsrole = $1;
                   4244:                                                 my $crssec = $2;
                   4245:                                                 if ($crsrole =~ /^cr/) {
                   4246:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4247:                                                         push(@rolecodes,'cr');
                   4248:                                                     }
                   4249:                                                 } else {
                   4250:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4251:                                                         push(@rolecodes,$crsrole);
                   4252:                                                     }
                   4253:                                                 }
                   4254:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4255:                                                 if ($crssec ne '') {
                   4256:                                                     $rolekey .= '/'.$crssec;
                   4257:                                                 }
                   4258:                                                 $rolekey .= './';
                   4259:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4260:                                             }
                   4261:                                         }
                   4262:                                     }
                   4263:                                 }
1.1002    raeburn  4264:                             } else {
1.1064    raeburn  4265:                                 push(@rolecodes,$$role);
1.1002    raeburn  4266:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4267:                             }
1.1064    raeburn  4268:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4269:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4270:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4271:                         }
                   4272:                     }
1.1034    raeburn  4273:                     $$tstatus = 'is';
1.1002    raeburn  4274:                 }
1.994     raeburn  4275:             }
                   4276:             if ($$tend) {
                   4277:                 if ($$tend<$then) {
                   4278:                     $$tstatus='expired';
                   4279:                 } elsif ($$tend<$now) {
                   4280:                     $$tstatus='will_not';
                   4281:                 }
                   4282:             }
                   4283:         }
                   4284:     }
                   4285: }
                   4286: 
                   4287: sub check_adhoc_privs {
1.1002    raeburn  4288:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4289:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4290:     if ($env{$cckey}) {
                   4291:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4292:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4293:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4294:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4295:         }
                   4296:     } else {
                   4297:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4298:     }
                   4299: }
                   4300: 
                   4301: sub set_adhoc_privileges {
                   4302: # role can be cc or ca
                   4303:     my ($dcdom,$pickedcourse,$role) = @_;
                   4304:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4305:     my $spec = $role.'.'.$area;
                   4306:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4307:                                   $env{'user.name'});
                   4308:     my %ccrole = ();
                   4309:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4310:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4311:     &appenv(\%userroles,[$role,'cm']);
                   4312:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4313:     &appenv( {'request.role'        => $spec,
                   4314:               'request.role.domain' => $dcdom,
                   4315:               'request.course.sec'  => ''
                   4316:              }
                   4317:            );
                   4318:     my $tadv=0;
                   4319:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4320:     &appenv({'request.role.adv'    => $tadv});
                   4321: }
                   4322: 
1.12      www      4323: # --------------------------------------------------------------- get interface
                   4324: 
                   4325: sub get {
1.131     albertel 4326:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4327:    my $items='';
1.800     albertel 4328:    foreach my $item (@$storearr) {
                   4329:        $items.=&escape($item).'&';
1.191     harris41 4330:    }
1.12      www      4331:    $items=~s/\&$//;
1.620     albertel 4332:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4333:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4334:    my $uhome=&homeserver($uname,$udomain);
                   4335: 
1.133     albertel 4336:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4337:    my @pairs=split(/\&/,$rep);
1.273     albertel 4338:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4339:      return @pairs;
                   4340:    }
1.15      www      4341:    my %returnhash=();
1.42      www      4342:    my $i=0;
1.800     albertel 4343:    foreach my $item (@$storearr) {
                   4344:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4345:       $i++;
1.191     harris41 4346:    }
1.15      www      4347:    return %returnhash;
1.27      www      4348: }
                   4349: 
                   4350: # --------------------------------------------------------------- del interface
                   4351: 
                   4352: sub del {
1.133     albertel 4353:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4354:    my $items='';
1.800     albertel 4355:    foreach my $item (@$storearr) {
                   4356:        $items.=&escape($item).'&';
1.191     harris41 4357:    }
1.984     neumanie 4358: 
1.27      www      4359:    $items=~s/\&$//;
1.620     albertel 4360:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4361:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4362:    my $uhome=&homeserver($uname,$udomain);
                   4363:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4364: }
                   4365: 
                   4366: # -------------------------------------------------------------- dump interface
                   4367: 
                   4368: sub dump {
1.755     albertel 4369:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4370:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4371:     if (!$uname) { $uname=$env{'user.name'}; }
                   4372:     my $uhome=&homeserver($uname,$udomain);
                   4373:     if ($regexp) {
                   4374: 	$regexp=&escape($regexp);
                   4375:     } else {
                   4376: 	$regexp='.';
                   4377:     }
                   4378:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4379:     my @pairs=split(/\&/,$rep);
                   4380:     my %returnhash=();
                   4381:     foreach my $item (@pairs) {
                   4382: 	my ($key,$value)=split(/=/,$item,2);
                   4383: 	$key = &unescape($key);
                   4384: 	next if ($key =~ /^error: 2 /);
                   4385: 	$returnhash{$key}=&thaw_unescape($value);
                   4386:     }
                   4387:     return %returnhash;
1.407     www      4388: }
                   4389: 
1.717     albertel 4390: # --------------------------------------------------------- dumpstore interface
                   4391: 
                   4392: sub dumpstore {
                   4393:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4394:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4395:    if (!$uname) { $uname=$env{'user.name'}; }
                   4396:    my $uhome=&homeserver($uname,$udomain);
                   4397:    if ($regexp) {
                   4398:        $regexp=&escape($regexp);
                   4399:    } else {
                   4400:        $regexp='.';
                   4401:    }
                   4402:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4403:    my @pairs=split(/\&/,$rep);
                   4404:    my %returnhash=();
                   4405:    foreach my $item (@pairs) {
                   4406:        my ($key,$value)=split(/=/,$item,2);
                   4407:        next if ($key =~ /^error: 2 /);
                   4408:        $returnhash{$key}=&thaw_unescape($value);
                   4409:    }
                   4410:    return %returnhash;
1.717     albertel 4411: }
                   4412: 
1.407     www      4413: # -------------------------------------------------------------- keys interface
                   4414: 
                   4415: sub getkeys {
                   4416:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4417:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4418:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4419:    my $uhome=&homeserver($uname,$udomain);
                   4420:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4421:    my @keyarray=();
1.800     albertel 4422:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4423:       next if ($key =~ /^error: 2 /);
1.800     albertel 4424:       push(@keyarray,&unescape($key));
1.407     www      4425:    }
                   4426:    return @keyarray;
1.318     matthew  4427: }
                   4428: 
1.319     matthew  4429: # --------------------------------------------------------------- currentdump
                   4430: sub currentdump {
1.328     matthew  4431:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4432:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4433:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4434:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4435:    my $uhome = &homeserver($sname,$sdom);
                   4436:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4437:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4438:    #
1.318     matthew  4439:    my %returnhash=();
1.319     matthew  4440:    #
                   4441:    if ($rep eq "unknown_cmd") { 
                   4442:        # an old lond will not know currentdump
                   4443:        # Do a dump and make it look like a currentdump
1.822     albertel 4444:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4445:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4446:        my %hash = @tmp;
                   4447:        @tmp=();
1.424     matthew  4448:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4449:    } else {
                   4450:        my @pairs=split(/\&/,$rep);
1.800     albertel 4451:        foreach my $pair (@pairs) {
                   4452:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4453:            my ($symb,$param) = split(/:/,$key);
                   4454:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4455:                                                         &thaw_unescape($value);
1.319     matthew  4456:        }
1.191     harris41 4457:    }
1.12      www      4458:    return %returnhash;
1.424     matthew  4459: }
                   4460: 
                   4461: sub convert_dump_to_currentdump{
                   4462:     my %hash = %{shift()};
                   4463:     my %returnhash;
                   4464:     # Code ripped from lond, essentially.  The only difference
                   4465:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4466:     # we might run in to problems with parameter names =~ /^v\./
                   4467:     while (my ($key,$value) = each(%hash)) {
                   4468:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4469: 	$symb  = &unescape($symb);
                   4470: 	$param = &unescape($param);
1.424     matthew  4471:         next if ($v eq 'version' || $symb eq 'keys');
                   4472:         next if (exists($returnhash{$symb}) &&
                   4473:                  exists($returnhash{$symb}->{$param}) &&
                   4474:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4475:         $returnhash{$symb}->{$param}=$value;
                   4476:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4477:     }
                   4478:     #
                   4479:     # Remove all of the keys in the hashes which keep track of
                   4480:     # the version of the parameter.
                   4481:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4482:         # use a foreach because we are going to delete from the hash.
                   4483:         foreach my $key (keys(%$param_hash)) {
                   4484:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4485:         }
                   4486:     }
                   4487:     return \%returnhash;
1.12      www      4488: }
                   4489: 
1.627     albertel 4490: # ------------------------------------------------------ critical inc interface
                   4491: 
                   4492: sub cinc {
                   4493:     return &inc(@_,'critical');
                   4494: }
                   4495: 
1.449     matthew  4496: # --------------------------------------------------------------- inc interface
                   4497: 
                   4498: sub inc {
1.627     albertel 4499:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4500:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4501:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4502:     my $uhome=&homeserver($uname,$udomain);
                   4503:     my $items='';
                   4504:     if (! ref($store)) {
                   4505:         # got a single value, so use that instead
                   4506:         $items = &escape($store).'=&';
                   4507:     } elsif (ref($store) eq 'SCALAR') {
                   4508:         $items = &escape($$store).'=&';        
                   4509:     } elsif (ref($store) eq 'ARRAY') {
                   4510:         $items = join('=&',map {&escape($_);} @{$store});
                   4511:     } elsif (ref($store) eq 'HASH') {
                   4512:         while (my($key,$value) = each(%{$store})) {
                   4513:             $items.= &escape($key).'='.&escape($value).'&';
                   4514:         }
                   4515:     }
                   4516:     $items=~s/\&$//;
1.627     albertel 4517:     if ($critical) {
                   4518: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4519:     } else {
                   4520: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4521:     }
1.449     matthew  4522: }
                   4523: 
1.12      www      4524: # --------------------------------------------------------------- put interface
                   4525: 
                   4526: sub put {
1.134     albertel 4527:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4528:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4529:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4530:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4531:    my $items='';
1.800     albertel 4532:    foreach my $item (keys(%$storehash)) {
                   4533:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4534:    }
1.12      www      4535:    $items=~s/\&$//;
1.134     albertel 4536:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4537: }
                   4538: 
1.631     albertel 4539: # ------------------------------------------------------------ newput interface
                   4540: 
                   4541: sub newput {
                   4542:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4543:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4544:    if (!$uname) { $uname=$env{'user.name'}; }
                   4545:    my $uhome=&homeserver($uname,$udomain);
                   4546:    my $items='';
                   4547:    foreach my $key (keys(%$storehash)) {
                   4548:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4549:    }
                   4550:    $items=~s/\&$//;
                   4551:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4552: }
                   4553: 
                   4554: # ---------------------------------------------------------  putstore interface
                   4555: 
1.524     raeburn  4556: sub putstore {
1.715     albertel 4557:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4558:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4559:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4560:    my $uhome=&homeserver($uname,$udomain);
                   4561:    my $items='';
1.715     albertel 4562:    foreach my $key (keys(%$storehash)) {
                   4563:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4564:    }
1.715     albertel 4565:    $items=~s/\&$//;
1.716     albertel 4566:    my $esc_symb=&escape($symb);
                   4567:    my $esc_v=&escape($version);
1.715     albertel 4568:    my $reply =
1.716     albertel 4569:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4570: 	      $uhome);
                   4571:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4572:        # gfall back to way things use to be done
1.715     albertel 4573:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4574: 			    $uname);
1.524     raeburn  4575:    }
1.715     albertel 4576:    return $reply;
                   4577: }
                   4578: 
                   4579: sub old_putstore {
1.716     albertel 4580:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4581:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4582:     if (!$uname) { $uname=$env{'user.name'}; }
                   4583:     my $uhome=&homeserver($uname,$udomain);
                   4584:     my %newstorehash;
1.800     albertel 4585:     foreach my $item (keys(%$storehash)) {
                   4586: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4587: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4588:     }
                   4589:     my $items='';
                   4590:     my %allitems = ();
1.800     albertel 4591:     foreach my $item (keys(%newstorehash)) {
                   4592: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4593: 	    my $key = $1.':keys:'.$2;
                   4594: 	    $allitems{$key} .= $3.':';
                   4595: 	}
1.800     albertel 4596: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4597:     }
1.800     albertel 4598:     foreach my $item (keys(%allitems)) {
                   4599: 	$allitems{$item} =~ s/\:$//;
                   4600: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4601:     }
                   4602:     $items=~s/\&$//;
                   4603:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4604: }
                   4605: 
1.47      www      4606: # ------------------------------------------------------ critical put interface
                   4607: 
                   4608: sub cput {
1.134     albertel 4609:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4610:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4611:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4612:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4613:    my $items='';
1.800     albertel 4614:    foreach my $item (keys(%$storehash)) {
                   4615:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4616:    }
1.47      www      4617:    $items=~s/\&$//;
1.134     albertel 4618:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4619: }
                   4620: 
                   4621: # -------------------------------------------------------------- eget interface
                   4622: 
                   4623: sub eget {
1.133     albertel 4624:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4625:    my $items='';
1.800     albertel 4626:    foreach my $item (@$storearr) {
                   4627:        $items.=&escape($item).'&';
1.191     harris41 4628:    }
1.12      www      4629:    $items=~s/\&$//;
1.620     albertel 4630:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4631:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4632:    my $uhome=&homeserver($uname,$udomain);
                   4633:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4634:    my @pairs=split(/\&/,$rep);
                   4635:    my %returnhash=();
1.42      www      4636:    my $i=0;
1.800     albertel 4637:    foreach my $item (@$storearr) {
                   4638:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4639:       $i++;
1.191     harris41 4640:    }
1.12      www      4641:    return %returnhash;
                   4642: }
                   4643: 
1.667     albertel 4644: # ------------------------------------------------------------ tmpput interface
                   4645: sub tmpput {
1.802     raeburn  4646:     my ($storehash,$server,$context)=@_;
1.667     albertel 4647:     my $items='';
1.800     albertel 4648:     foreach my $item (keys(%$storehash)) {
                   4649: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4650:     }
                   4651:     $items=~s/\&$//;
1.802     raeburn  4652:     if (defined($context)) {
                   4653:         $items .= ':'.&escape($context);
                   4654:     }
1.667     albertel 4655:     return &reply("tmpput:$items",$server);
                   4656: }
                   4657: 
                   4658: # ------------------------------------------------------------ tmpget interface
                   4659: sub tmpget {
1.688     albertel 4660:     my ($token,$server)=@_;
                   4661:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4662:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4663:     my %returnhash;
                   4664:     foreach my $item (split(/\&/,$rep)) {
                   4665: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4666:         next if ($key =~ /^error: 2 /);
1.667     albertel 4667: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4668:     }
                   4669:     return %returnhash;
                   4670: }
                   4671: 
1.688     albertel 4672: # ------------------------------------------------------------ tmpget interface
                   4673: sub tmpdel {
                   4674:     my ($token,$server)=@_;
                   4675:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4676:     return &reply("tmpdel:$token",$server);
                   4677: }
                   4678: 
1.765     albertel 4679: # -------------------------------------------------- portfolio access checking
                   4680: 
                   4681: sub portfolio_access {
1.766     albertel 4682:     my ($requrl) = @_;
1.765     albertel 4683:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4684:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4685:     if ($result) {
                   4686:         my %setters;
                   4687:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4688:             my ($startblock,$endblock) =
                   4689:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4690:             if ($startblock && $endblock) {
                   4691:                 return 'B';
                   4692:             }
                   4693:         } else {
                   4694:             my ($startblock,$endblock) =
                   4695:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4696:             if ($startblock && $endblock) {
                   4697:                 return 'B';
                   4698:             }
                   4699:         }
                   4700:     }
1.765     albertel 4701:     if ($result eq 'ok') {
1.766     albertel 4702:        return 'F';
1.765     albertel 4703:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4704:        return 'A';
1.765     albertel 4705:     }
1.766     albertel 4706:     return '';
1.765     albertel 4707: }
                   4708: 
                   4709: sub get_portfolio_access {
1.767     albertel 4710:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4711: 
                   4712:     if (!ref($access_hash)) {
                   4713: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4714: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4715: 						   $file_name);
                   4716: 	$access_hash = $access_controls{$file_name};
                   4717:     }
                   4718: 
1.765     albertel 4719:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4720:     my $now = time;
                   4721:     if (ref($access_hash) eq 'HASH') {
                   4722:         foreach my $key (keys(%{$access_hash})) {
                   4723:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4724:             if ($start > $now) {
                   4725:                 next;
                   4726:             }
                   4727:             if ($end && $end<$now) {
                   4728:                 next;
                   4729:             }
                   4730:             if ($scope eq 'public') {
                   4731:                 $public = $key;
                   4732:                 last;
                   4733:             } elsif ($scope eq 'guest') {
                   4734:                 $guest = $key;
                   4735:             } elsif ($scope eq 'domains') {
                   4736:                 push(@domains,$key);
                   4737:             } elsif ($scope eq 'users') {
                   4738:                 push(@users,$key);
                   4739:             } elsif ($scope eq 'course') {
                   4740:                 push(@courses,$key);
                   4741:             } elsif ($scope eq 'group') {
                   4742:                 push(@groups,$key);
                   4743:             }
                   4744:         }
                   4745:         if ($public) {
                   4746:             return 'ok';
                   4747:         }
                   4748:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4749:             if ($guest) {
                   4750:                 return $guest;
                   4751:             }
                   4752:         } else {
                   4753:             if (@domains > 0) {
                   4754:                 foreach my $domkey (@domains) {
                   4755:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4756:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4757:                             return 'ok';
                   4758:                         }
                   4759:                     }
                   4760:                 }
                   4761:             }
                   4762:             if (@users > 0) {
                   4763:                 foreach my $userkey (@users) {
1.865     raeburn  4764:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4765:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4766:                             if (ref($item) eq 'HASH') {
                   4767:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4768:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4769:                                     return 'ok';
                   4770:                                 }
                   4771:                             }
                   4772:                         }
                   4773:                     } 
1.765     albertel 4774:                 }
                   4775:             }
                   4776:             my %roleshash;
                   4777:             my @courses_and_groups = @courses;
                   4778:             push(@courses_and_groups,@groups); 
                   4779:             if (@courses_and_groups > 0) {
                   4780:                 my (%allgroups,%allroles); 
                   4781:                 my ($start,$end,$role,$sec,$group);
                   4782:                 foreach my $envkey (%env) {
1.1060    raeburn  4783:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4784:                         my $cid = $2.'_'.$3; 
                   4785:                         if ($1 eq 'gr') {
                   4786:                             $group = $4;
                   4787:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4788:                         } else {
                   4789:                             if ($4 eq '') {
                   4790:                                 $sec = 'none';
                   4791:                             } else {
                   4792:                                 $sec = $4;
                   4793:                             }
                   4794:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4795:                         }
1.811     albertel 4796:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4797:                         my $cid = $2.'_'.$3;
                   4798:                         if ($4 eq '') {
                   4799:                             $sec = 'none';
                   4800:                         } else {
                   4801:                             $sec = $4;
                   4802:                         }
                   4803:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4804:                     }
                   4805:                 }
                   4806:                 if (keys(%allroles) == 0) {
                   4807:                     return;
                   4808:                 }
                   4809:                 foreach my $key (@courses_and_groups) {
                   4810:                     my %content = %{$$access_hash{$key}};
                   4811:                     my $cnum = $content{'number'};
                   4812:                     my $cdom = $content{'domain'};
                   4813:                     my $cid = $cdom.'_'.$cnum;
                   4814:                     if (!exists($allroles{$cid})) {
                   4815:                         next;
                   4816:                     }    
                   4817:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4818:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4819:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4820:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4821:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4822:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4823:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4824:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4825:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4826:                                         if (grep/^all$/,@sections) {
                   4827:                                             return 'ok';
                   4828:                                         } else {
                   4829:                                             if (grep/^$sec$/,@sections) {
                   4830:                                                 return 'ok';
                   4831:                                             }
                   4832:                                         }
                   4833:                                     }
                   4834:                                 }
                   4835:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4836:                                     if (grep/^none$/,@groups) {
                   4837:                                         return 'ok';
                   4838:                                     }
                   4839:                                 } else {
                   4840:                                     if (grep/^all$/,@groups) {
                   4841:                                         return 'ok';
                   4842:                                     } 
                   4843:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4844:                                         if (grep/^$group$/,@groups) {
                   4845:                                             return 'ok';
                   4846:                                         }
                   4847:                                     }
                   4848:                                 } 
                   4849:                             }
                   4850:                         }
                   4851:                     }
                   4852:                 }
                   4853:             }
                   4854:             if ($guest) {
                   4855:                 return $guest;
                   4856:             }
                   4857:         }
                   4858:     }
                   4859:     return;
                   4860: }
                   4861: 
                   4862: sub course_group_datechecker {
                   4863:     my ($dates,$now,$status) = @_;
                   4864:     my ($start,$end) = split(/\./,$dates);
                   4865:     if (!$start && !$end) {
                   4866:         return 'ok';
                   4867:     }
                   4868:     if (grep/^active$/,@{$status}) {
                   4869:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4870:             return 'ok';
                   4871:         }
                   4872:     }
                   4873:     if (grep/^previous$/,@{$status}) {
                   4874:         if ($end > $now ) {
                   4875:             return 'ok';
                   4876:         }
                   4877:     }
                   4878:     if (grep/^future$/,@{$status}) {
                   4879:         if ($start > $now) {
                   4880:             return 'ok';
                   4881:         }
                   4882:     }
                   4883:     return; 
                   4884: }
                   4885: 
                   4886: sub parse_portfolio_url {
                   4887:     my ($url) = @_;
                   4888: 
                   4889:     my ($type,$udom,$unum,$group,$file_name);
                   4890:     
1.823     albertel 4891:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4892: 	$type = 1;
                   4893:         $udom = $1;
                   4894:         $unum = $2;
                   4895:         $file_name = $3;
1.823     albertel 4896:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4897: 	$type = 2;
                   4898:         $udom = $1;
                   4899:         $unum = $2;
                   4900:         $group = $3;
                   4901:         $file_name = $3.'/'.$4;
                   4902:     }
                   4903:     if (wantarray) {
                   4904: 	return ($type,$udom,$unum,$file_name,$group);
                   4905:     }
                   4906:     return $type;
                   4907: }
                   4908: 
                   4909: sub is_portfolio_url {
                   4910:     my ($url) = @_;
                   4911:     return scalar(&parse_portfolio_url($url));
                   4912: }
                   4913: 
1.798     raeburn  4914: sub is_portfolio_file {
                   4915:     my ($file) = @_;
1.820     raeburn  4916:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4917:         return 1;
                   4918:     }
                   4919:     return;
                   4920: }
                   4921: 
1.976     raeburn  4922: sub usertools_access {
1.1084    raeburn  4923:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  4924:     my ($access,%tools);
                   4925:     if ($context eq '') {
                   4926:         $context = 'tools';
                   4927:     }
                   4928:     if ($context eq 'requestcourses') {
                   4929:         %tools = (
                   4930:                       official   => 1,
                   4931:                       unofficial => 1,
1.1006    raeburn  4932:                       community  => 1,
1.985     raeburn  4933:                  );
                   4934:     } else {
                   4935:         %tools = (
                   4936:                       aboutme   => 1,
                   4937:                       blog      => 1,
                   4938:                       portfolio => 1,
                   4939:                  );
                   4940:     }
1.976     raeburn  4941:     return if (!defined($tools{$tool}));
                   4942: 
                   4943:     if ((!defined($udom)) || (!defined($uname))) {
                   4944:         $udom = $env{'user.domain'};
                   4945:         $uname = $env{'user.name'};
                   4946:     }
                   4947: 
1.978     raeburn  4948:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4949:         if ($action ne 'reload') {
1.985     raeburn  4950:             if ($context eq 'requestcourses') {
                   4951:                 return $env{'environment.canrequest.'.$tool};
                   4952:             } else {
                   4953:                 return $env{'environment.availabletools.'.$tool};
                   4954:             }
                   4955:         }
1.976     raeburn  4956:     }
                   4957: 
                   4958:     my ($toolstatus,$inststatus);
                   4959: 
1.985     raeburn  4960:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4961:          ($action ne 'reload')) {
                   4962:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4963:         $inststatus = $env{'environment.inststatus'};
                   4964:     } else {
1.1084    raeburn  4965:         if (ref($userenvref) eq 'HASH') {
                   4966:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   4967:             $inststatus = $userenvref->{'inststatus'};
                   4968:         } else {
                   4969:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   4970:             $toolstatus = $userenv{$context.'.'.$tool};
                   4971:             $inststatus = $userenv{'inststatus'};
                   4972:         }
1.976     raeburn  4973:     }
                   4974: 
                   4975:     if ($toolstatus ne '') {
                   4976:         if ($toolstatus) {
                   4977:             $access = 1;
                   4978:         } else {
                   4979:             $access = 0;
                   4980:         }
                   4981:         return $access;
                   4982:     }
                   4983: 
1.1084    raeburn  4984:     my ($is_adv,%domdef);
                   4985:     if (ref($is_advref) eq 'HASH') {
                   4986:         $is_adv = $is_advref->{'is_adv'};
                   4987:     } else {
                   4988:         $is_adv = &is_advanced_user($udom,$uname);
                   4989:     }
                   4990:     if (ref($domdefref) eq 'HASH') {
                   4991:         %domdef = %{$domdefref};
                   4992:     } else {
                   4993:         %domdef = &get_domain_defaults($udom);
                   4994:     }
1.976     raeburn  4995:     if (ref($domdef{$tool}) eq 'HASH') {
                   4996:         if ($is_adv) {
                   4997:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4998:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4999:                     $access = 1;
                   5000:                 } else {
                   5001:                     $access = 0;
                   5002:                 }
                   5003:                 return $access;
                   5004:             }
                   5005:         }
                   5006:         if ($inststatus ne '') {
                   5007:             my ($hasaccess,$hasnoaccess);
                   5008:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5009:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5010:                     if ($domdef{$tool}{$affiliation}) {
                   5011:                         $hasaccess = 1;
                   5012:                     } else {
                   5013:                         $hasnoaccess = 1;
                   5014:                     }
                   5015:                 }
                   5016:             }
                   5017:             if ($hasaccess || $hasnoaccess) {
                   5018:                 if ($hasaccess) {
                   5019:                     $access = 1;
                   5020:                 } elsif ($hasnoaccess) {
                   5021:                     $access = 0; 
                   5022:                 }
                   5023:                 return $access;
                   5024:             }
                   5025:         } else {
                   5026:             if ($domdef{$tool}{'default'} ne '') {
                   5027:                 if ($domdef{$tool}{'default'}) {
                   5028:                     $access = 1;
                   5029:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5030:                     $access = 0;
                   5031:                 }
                   5032:                 return $access;
                   5033:             }
                   5034:         }
                   5035:     } else {
1.985     raeburn  5036:         if ($context eq 'tools') {
                   5037:             $access = 1;
                   5038:         } else {
                   5039:             $access = 0;
                   5040:         }
1.976     raeburn  5041:         return $access;
                   5042:     }
                   5043: }
                   5044: 
1.1050    raeburn  5045: sub is_course_owner {
                   5046:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5047:     if (($udom eq '') || ($uname eq '')) {
                   5048:         $udom = $env{'user.domain'};
                   5049:         $uname = $env{'user.name'};
                   5050:     }
                   5051:     unless (($udom eq '') || ($uname eq '')) {
                   5052:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5053:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5054:                 return 1;
                   5055:             } else {
                   5056:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5057:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5058:                     return 1;
                   5059:                 }
                   5060:             }
                   5061:         }
                   5062:     }
                   5063:     return;
                   5064: }
                   5065: 
1.976     raeburn  5066: sub is_advanced_user {
                   5067:     my ($udom,$uname) = @_;
1.1085  ! raeburn  5068:     if ($udom ne '' && $uname ne '') {
        !          5069:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
        !          5070:             return $env{'user.adv'};  
        !          5071:         }
        !          5072:     }
1.976     raeburn  5073:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5074:     my %allroles;
                   5075:     my $is_adv;
                   5076:     foreach my $role (keys(%roleshash)) {
                   5077:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5078:         my $area = '/'.$tdomain.'/'.$trest;
                   5079:         if ($sec ne '') {
                   5080:             $area .= '/'.$sec;
                   5081:         }
                   5082:         if (($area ne '') && ($trole ne '')) {
                   5083:             my $spec=$trole.'.'.$area;
                   5084:             if ($trole =~ /^cr\//) {
                   5085:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5086:             } elsif ($trole ne 'gr') {
                   5087:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5088:             }
                   5089:         }
                   5090:     }
                   5091:     foreach my $role (keys(%allroles)) {
                   5092:         last if ($is_adv);
                   5093:         foreach my $item (split(/:/,$allroles{$role})) {
                   5094:             if ($item ne '') {
                   5095:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5096:                 if ($privilege eq 'adv') {
                   5097:                     $is_adv = 1;
                   5098:                     last;
                   5099:                 }
                   5100:             }
                   5101:         }
                   5102:     }
                   5103:     return $is_adv;
                   5104: }
1.798     raeburn  5105: 
1.1035    raeburn  5106: sub check_can_request {
1.1036    raeburn  5107:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5108:     my $canreq = 0;
                   5109:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5110:     my @options = ('approval','validate','autolimit');
                   5111:     my $optregex = join('|',@options);
                   5112:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5113:         foreach my $type (@{$types}) {
                   5114:             if (&usertools_access($env{'user.name'},
                   5115:                                   $env{'user.domain'},
                   5116:                                   $type,undef,'requestcourses')) {
                   5117:                 $canreq ++;
1.1036    raeburn  5118:                 if (ref($request_domains) eq 'HASH') {
                   5119:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5120:                 }
1.1035    raeburn  5121:                 if ($dom eq $env{'user.domain'}) {
                   5122:                     $can_request->{$type} = 1;
                   5123:                 }
                   5124:             }
                   5125:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5126:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5127:                 if (@curr > 0) {
1.1036    raeburn  5128:                     foreach my $item (@curr) {
                   5129:                         if (ref($request_domains) eq 'HASH') {
                   5130:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5131:                             if ($otherdom ne '') {
                   5132:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5133:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5134:                                         push(@{$request_domains->{$type}},$otherdom);
                   5135:                                     }
                   5136:                                 } else {
                   5137:                                     push(@{$request_domains->{$type}},$otherdom);
                   5138:                                 }
                   5139:                             }
                   5140:                         }
                   5141:                     }
                   5142:                     unless($dom eq $env{'user.domain'}) {
                   5143:                         $canreq ++;
1.1035    raeburn  5144:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5145:                             $can_request->{$type} = 1;
                   5146:                         }
                   5147:                     }
                   5148:                 }
                   5149:             }
                   5150:         }
                   5151:     }
                   5152:     return $canreq;
                   5153: }
                   5154: 
1.341     www      5155: # ---------------------------------------------- Custom access rule evaluation
                   5156: 
                   5157: sub customaccess {
                   5158:     my ($priv,$uri)=@_;
1.807     albertel 5159:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5160:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5161:     $udom = &LONCAPA::clean_domain($udom);
                   5162:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5163:     my $access=0;
1.800     albertel 5164:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5165: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5166: 	if ($type eq 'user') {
                   5167: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5168: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5169: 		if ($tdom) {
                   5170: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5171: 		}
1.896     albertel 5172: 		if ($tuname) {
                   5173: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5174: 		}
                   5175: 		$access=($effect eq 'allow');
                   5176: 		last;
                   5177: 	    }
                   5178: 	} else {
                   5179: 	    if ($role) {
                   5180: 		if ($role ne $urole) { next; }
                   5181: 	    }
                   5182: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5183: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5184: 		if ($tdom) {
                   5185: 		    if ($tdom ne $udom) { next; }
                   5186: 		}
                   5187: 		if ($tcrs) {
                   5188: 		    if ($tcrs ne $ucrs) { next; }
                   5189: 		}
                   5190: 		if ($tsec) {
                   5191: 		    if ($tsec ne $usec) { next; }
                   5192: 		}
                   5193: 		$access=($effect eq 'allow');
                   5194: 		last;
                   5195: 	    }
                   5196: 	    if ($realm eq '' && $role eq '') {
                   5197: 		$access=($effect eq 'allow');
                   5198: 	    }
1.402     bowersj2 5199: 	}
1.341     www      5200:     }
                   5201:     return $access;
                   5202: }
                   5203: 
1.103     harris41 5204: # ------------------------------------------------- Check for a user privilege
1.12      www      5205: 
                   5206: sub allowed {
1.810     raeburn  5207:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5208:     my $ver_orguri=$uri;
1.439     www      5209:     $uri=&deversion($uri);
1.152     www      5210:     my $orguri=$uri;
1.52      www      5211:     $uri=&declutter($uri);
1.809     raeburn  5212: 
1.810     raeburn  5213:     if ($priv eq 'evb') {
                   5214: # Evade communication block restrictions for specified role in a course
                   5215:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5216:             return $1;
                   5217:         } else {
                   5218:             return;
                   5219:         }
                   5220:     }
                   5221: 
1.620     albertel 5222:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5223: # Free bre access to adm and meta resources
1.775     albertel 5224:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5225: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5226: 	&& ($priv eq 'bre')) {
1.14      www      5227: 	return 'F';
1.159     www      5228:     }
                   5229: 
1.545     banghart 5230: # Free bre access to user's own portfolio contents
1.714     raeburn  5231:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5232:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5233: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5234:         my %setters;
                   5235:         my ($startblock,$endblock) = 
                   5236:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5237:         if ($startblock && $endblock) {
                   5238:             return 'B';
                   5239:         } else {
                   5240:             return 'F';
                   5241:         }
1.545     banghart 5242:     }
                   5243: 
1.762     raeburn  5244: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5245:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5246:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5247:         if (exists($env{'request.course.id'})) {
                   5248:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5249:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5250:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5251:                 my $courseprivid=$env{'request.course.id'};
                   5252:                 $courseprivid=~s/\_/\//;
                   5253:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5254:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5255:                     return $1; 
1.762     raeburn  5256:                 } else {
                   5257:                     if ($env{'request.course.sec'}) {
                   5258:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5259:                     }
                   5260:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5261:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5262:                         return $2;
                   5263:                     }
1.714     raeburn  5264:                 }
                   5265:             }
                   5266:         }
                   5267:     }
                   5268: 
1.159     www      5269: # Free bre to public access
                   5270: 
                   5271:     if ($priv eq 'bre') {
1.238     www      5272:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5273: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5274:            return 'F'; 
                   5275:         }
1.238     www      5276:         if ($copyright eq 'priv') {
                   5277:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5278: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5279: 		return '';
                   5280:             }
                   5281:         }
                   5282:         if ($copyright eq 'domain') {
                   5283:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5284: 	    unless (($env{'user.domain'} eq $1) ||
                   5285:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5286: 		return '';
                   5287:             }
1.262     matthew  5288:         }
1.620     albertel 5289:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5290:             # Library role, so allow browsing of resources in this domain.
                   5291:             return 'F';
1.238     www      5292:         }
1.341     www      5293:         if ($copyright eq 'custom') {
                   5294: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5295:         }
1.14      www      5296:     }
1.264     matthew  5297:     # Domain coordinator is trying to create a course
1.620     albertel 5298:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5299:         # uri is the requested domain in this case.
                   5300:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5301:         # a role of dc for the domain in question.
1.620     albertel 5302:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5303:     }
1.29      www      5304: 
1.52      www      5305:     my $thisallowed='';
                   5306:     my $statecond=0;
                   5307:     my $courseprivid='';
                   5308: 
1.1039    raeburn  5309:     my $ownaccess;
1.1043    raeburn  5310:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5311:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5312:         if ($uri eq '') {
                   5313:             $ownaccess = 1;
                   5314:         } else {
                   5315:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5316:                 my $udom = $env{'user.domain'};
                   5317:                 my $uname = $env{'user.name'};
                   5318:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5319:                     $ownaccess = 1;
1.1040    raeburn  5320:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5321:                     unless ($uri =~ m{\.\./}) {
                   5322:                         $ownaccess = 1;
                   5323:                     }
                   5324:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5325:                     my $now = time;
                   5326:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5327:                         my $adom = $1;
                   5328:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5329:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5330:                                 my ($start,$end) = split('.',$env{$key});
                   5331:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5332:                                     $ownaccess = 1;
                   5333:                                     last;
                   5334:                                 }
                   5335:                             }
                   5336:                         }
                   5337:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5338:                         my $adom = $1;
                   5339:                         my $aname = $2;
1.1042    raeburn  5340:                         foreach my $role ('ca','aa') { 
                   5341:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5342:                                 my ($start,$end) =
                   5343:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5344:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5345:                                     $ownaccess = 1;
                   5346:                                     last;
                   5347:                                 }
1.1039    raeburn  5348:                             }
                   5349:                         }
                   5350:                     }
                   5351:                 }
                   5352:             }
                   5353:         }
                   5354:     }
                   5355: 
1.52      www      5356: # Course
                   5357: 
1.620     albertel 5358:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5359:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5360:             $thisallowed.=$1;
                   5361:         }
1.52      www      5362:     }
1.29      www      5363: 
1.52      www      5364: # Domain
                   5365: 
1.620     albertel 5366:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5367:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5368:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5369:             $thisallowed.=$1;
                   5370:         }
1.12      www      5371:     }
1.52      www      5372: 
                   5373: # Course: uri itself is a course
1.66      www      5374:     my $courseuri=$uri;
                   5375:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5376:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5377: 
1.620     albertel 5378:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5379:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5380:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5381:             $thisallowed.=$1;
                   5382:         }
1.12      www      5383:     }
1.29      www      5384: 
1.665     albertel 5385: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5386: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5387:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5388: 	$thisallowed='';
1.671     raeburn  5389:         my ($match)=&is_on_map($uri);
                   5390:         if ($match) {
                   5391:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5392:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5393:                 $thisallowed.=$1;
                   5394:             }
                   5395:         } else {
1.705     albertel 5396:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5397:             if ($refuri) {
                   5398:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5399:                     $thisallowed='F';
1.671     raeburn  5400:                 } else {
                   5401:                     $refuri=&declutter($refuri);
                   5402:                     my ($match) = &is_on_map($refuri);
                   5403:                     if ($match) {
                   5404:                         $thisallowed='F';
                   5405:                     }
1.669     raeburn  5406:                 }
1.671     raeburn  5407:             }
                   5408:         }
1.314     www      5409:     }
1.492     albertel 5410: 
1.766     albertel 5411:     if ($priv eq 'bre'
                   5412: 	&& $thisallowed ne 'F' 
                   5413: 	&& $thisallowed ne '2'
                   5414: 	&& &is_portfolio_url($uri)) {
                   5415: 	$thisallowed = &portfolio_access($uri);
                   5416:     }
                   5417:     
1.52      www      5418: # Full access at system, domain or course-wide level? Exit.
1.29      www      5419:     if ($thisallowed=~/F/) {
                   5420: 	return 'F';
                   5421:     }
                   5422: 
1.52      www      5423: # If this is generating or modifying users, exit with special codes
1.29      www      5424: 
1.643     www      5425:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5426: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5427: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5428: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5429: 	    unless ($auname) { return $thisallowed; }
                   5430: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5431: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5432: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5433: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5434: 	}
1.52      www      5435: 	return $thisallowed;
                   5436:     }
                   5437: #
1.103     harris41 5438: # Gathered so far: system, domain and course wide privileges
1.52      www      5439: #
                   5440: # Course: See if uri or referer is an individual resource that is part of 
                   5441: # the course
                   5442: 
1.620     albertel 5443:     if ($env{'request.course.id'}) {
1.232     www      5444: 
1.620     albertel 5445:        $courseprivid=$env{'request.course.id'};
                   5446:        if ($env{'request.course.sec'}) {
                   5447:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5448:        }
                   5449:        $courseprivid=~s/\_/\//;
                   5450:        my $checkreferer=1;
1.232     www      5451:        my ($match,$cond)=&is_on_map($uri);
                   5452:        if ($match) {
                   5453:            $statecond=$cond;
1.620     albertel 5454:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5455:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5456:                $thisallowed.=$1;
                   5457:                $checkreferer=0;
                   5458:            }
1.29      www      5459:        }
1.83      www      5460:        
1.148     www      5461:        if ($checkreferer) {
1.620     albertel 5462: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5463:             unless ($refuri) {
1.800     albertel 5464:                 foreach my $key (keys(%env)) {
                   5465: 		    if ($key=~/^httpref\..*\*/) {
                   5466: 			my $pattern=$key;
1.156     www      5467:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5468:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5469:                         $pattern=~s/\//\\\//g;
1.152     www      5470:                         if ($orguri=~/$pattern/) {
1.800     albertel 5471: 			    $refuri=$env{$key};
1.148     www      5472:                         }
                   5473:                     }
1.191     harris41 5474:                 }
1.148     www      5475:             }
1.232     www      5476: 
1.148     www      5477:          if ($refuri) { 
1.152     www      5478: 	  $refuri=&declutter($refuri);
1.232     www      5479:           my ($match,$cond)=&is_on_map($refuri);
                   5480:             if ($match) {
                   5481:               my $refstatecond=$cond;
1.620     albertel 5482:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5483:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5484:                   $thisallowed.=$1;
1.53      www      5485:                   $uri=$refuri;
                   5486:                   $statecond=$refstatecond;
1.52      www      5487:               }
                   5488:           }
1.148     www      5489:         }
1.29      www      5490:        }
1.52      www      5491:    }
1.29      www      5492: 
1.52      www      5493: #
1.103     harris41 5494: # Gathered now: all privileges that could apply, and condition number
1.52      www      5495: # 
                   5496: #
                   5497: # Full or no access?
                   5498: #
1.29      www      5499: 
1.52      www      5500:     if ($thisallowed=~/F/) {
                   5501: 	return 'F';
                   5502:     }
1.29      www      5503: 
1.52      www      5504:     unless ($thisallowed) {
                   5505:         return '';
                   5506:     }
1.29      www      5507: 
1.52      www      5508: # Restrictions exist, deal with them
                   5509: #
                   5510: #   C:according to course preferences
                   5511: #   R:according to resource settings
                   5512: #   L:unless locked
                   5513: #   X:according to user session state
                   5514: #
                   5515: 
                   5516: # Possibly locked functionality, check all courses
1.54      www      5517: # Locks might take effect only after 10 minutes cache expiration for other
                   5518: # courses, and 2 minutes for current course
1.52      www      5519: 
                   5520:     my $envkey;
                   5521:     if ($thisallowed=~/L/) {
1.1000    raeburn  5522:         foreach $envkey (keys(%env)) {
1.54      www      5523:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5524:                my $courseid=$2;
                   5525:                my $roleid=$1.'.'.$2;
1.92      www      5526:                $courseid=~s/^\///;
1.54      www      5527:                my $expiretime=600;
1.620     albertel 5528:                if ($env{'request.role'} eq $roleid) {
1.54      www      5529: 		  $expiretime=120;
                   5530:                }
                   5531: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5532:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5533:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5534: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5535:                }
1.620     albertel 5536:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5537:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5538: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5539:                        &log($env{'user.domain'},$env{'user.name'},
                   5540:                             $env{'user.home'},
1.57      www      5541:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5542:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5543:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5544: 		       return '';
                   5545:                    }
                   5546:                }
1.620     albertel 5547:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5548:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5549: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5550:                        &log($env{'user.domain'},$env{'user.name'},
                   5551:                             $env{'user.home'},
1.57      www      5552:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5553:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5554:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5555: 		       return '';
                   5556:                    }
                   5557:                }
                   5558: 	   }
1.29      www      5559:        }
1.52      www      5560:     }
                   5561:    
                   5562: #
                   5563: # Rest of the restrictions depend on selected course
                   5564: #
                   5565: 
1.620     albertel 5566:     unless ($env{'request.course.id'}) {
1.766     albertel 5567: 	if ($thisallowed eq 'A') {
                   5568: 	    return 'A';
1.814     raeburn  5569:         } elsif ($thisallowed eq 'B') {
                   5570:             return 'B';
1.766     albertel 5571: 	} else {
                   5572: 	    return '1';
                   5573: 	}
1.52      www      5574:     }
1.29      www      5575: 
1.52      www      5576: #
                   5577: # Now user is definitely in a course
                   5578: #
1.53      www      5579: 
                   5580: 
                   5581: # Course preferences
                   5582: 
                   5583:    if ($thisallowed=~/C/) {
1.620     albertel 5584:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5585:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5586:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5587: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5588: 	   if ($priv ne 'pch') { 
                   5589: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5590: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5591: 			$env{'request.course.id'});
                   5592: 	   }
1.237     www      5593:            return '';
                   5594:        }
                   5595: 
1.620     albertel 5596:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5597: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5598: 	   if ($priv ne 'pch') { 
                   5599: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5600: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5601: 			$env{'request.course.id'});
                   5602: 	   }
1.54      www      5603:            return '';
                   5604:        }
1.53      www      5605:    }
                   5606: 
                   5607: # Resource preferences
                   5608: 
                   5609:    if ($thisallowed=~/R/) {
1.620     albertel 5610:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5611:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5612: 	   if ($priv ne 'pch') { 
                   5613: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5614: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5615: 	   }
                   5616: 	   return '';
1.54      www      5617:        }
1.53      www      5618:    }
1.30      www      5619: 
1.246     www      5620: # Restricted by state or randomout?
1.30      www      5621: 
1.52      www      5622:    if ($thisallowed=~/X/) {
1.620     albertel 5623:       if ($env{'acc.randomout'}) {
1.579     albertel 5624: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5625:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5626:             return ''; 
                   5627:          }
1.247     www      5628:       }
                   5629:       if (&condval($statecond)) {
1.52      www      5630: 	 return '2';
                   5631:       } else {
                   5632:          return '';
                   5633:       }
                   5634:    }
1.30      www      5635: 
1.766     albertel 5636:     if ($thisallowed eq 'A') {
                   5637: 	return 'A';
1.814     raeburn  5638:     } elsif ($thisallowed eq 'B') {
                   5639:         return 'B';
1.766     albertel 5640:     }
1.52      www      5641:    return 'F';
1.232     www      5642: }
                   5643: 
1.710     albertel 5644: sub split_uri_for_cond {
                   5645:     my $uri=&deversion(&declutter(shift));
                   5646:     my @uriparts=split(/\//,$uri);
                   5647:     my $filename=pop(@uriparts);
                   5648:     my $pathname=join('/',@uriparts);
                   5649:     return ($pathname,$filename);
                   5650: }
1.232     www      5651: # --------------------------------------------------- Is a resource on the map?
                   5652: 
                   5653: sub is_on_map {
1.710     albertel 5654:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5655:     #Trying to find the conditional for the file
1.620     albertel 5656:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5657: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5658:     if ($match) {
1.289     bowersj2 5659: 	return (1,$1);
                   5660:     } else {
1.434     www      5661: 	return (0,0);
1.289     bowersj2 5662:     }
1.12      www      5663: }
                   5664: 
1.427     www      5665: # --------------------------------------------------------- Get symb from alias
                   5666: 
                   5667: sub get_symb_from_alias {
                   5668:     my $symb=shift;
                   5669:     my ($map,$resid,$url)=&decode_symb($symb);
                   5670: # Already is a symb
                   5671:     if ($url) { return $symb; }
                   5672: # Must be an alias
                   5673:     my $aliassymb='';
                   5674:     my %bighash;
1.620     albertel 5675:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5676:                             &GDBM_READER(),0640)) {
                   5677:         my $rid=$bighash{'mapalias_'.$symb};
                   5678: 	if ($rid) {
                   5679: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5680: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5681: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5682: 	}
                   5683:         untie %bighash;
                   5684:     }
                   5685:     return $aliassymb;
                   5686: }
                   5687: 
1.12      www      5688: # ----------------------------------------------------------------- Define Role
                   5689: 
                   5690: sub definerole {
                   5691:   if (allowed('mcr','/')) {
                   5692:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5693:     foreach my $role (split(':',$sysrole)) {
                   5694: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5695:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5696:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5697: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5698:                return "refused:s:$crole&$cqual"; 
                   5699:             }
                   5700:         }
1.191     harris41 5701:     }
1.800     albertel 5702:     foreach my $role (split(':',$domrole)) {
                   5703: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5704:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5705:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5706: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5707:                return "refused:d:$crole&$cqual"; 
                   5708:             }
                   5709:         }
1.191     harris41 5710:     }
1.800     albertel 5711:     foreach my $role (split(':',$courole)) {
                   5712: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5713:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5714:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5715: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5716:                return "refused:c:$crole&$cqual"; 
                   5717:             }
                   5718:         }
1.191     harris41 5719:     }
1.620     albertel 5720:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5721:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5722: 	        "rolesdef_$rolename=".
                   5723:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5724:     return reply($command,$env{'user.home'});
1.12      www      5725:   } else {
                   5726:     return 'refused';
                   5727:   }
1.105     harris41 5728: }
                   5729: 
                   5730: # ---------------- Make a metadata query against the network of library servers
                   5731: 
                   5732: sub metadata_query {
1.244     matthew  5733:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5734:     my %rhash;
1.845     albertel 5735:     my %libserv = &all_library();
1.244     matthew  5736:     my @server_list = (defined($server_array) ? @$server_array
                   5737:                                               : keys(%libserv) );
                   5738:     for my $server (@server_list) {
1.118     harris41 5739: 	unless ($custom or $customshow) {
                   5740: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5741: 	    $rhash{$server}=$reply;
                   5742: 	}
                   5743: 	else {
                   5744: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5745: 			     &escape($custom).':'.&escape($customshow),
                   5746: 			     $server);
                   5747: 	    $rhash{$server}=$reply;
                   5748: 	}
1.112     harris41 5749:     }
1.118     harris41 5750:     return \%rhash;
1.240     www      5751: }
                   5752: 
                   5753: # ----------------------------------------- Send log queries and wait for reply
                   5754: 
                   5755: sub log_query {
                   5756:     my ($uname,$udom,$query,%filters)=@_;
                   5757:     my $uhome=&homeserver($uname,$udom);
                   5758:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5759:     my $uhost=&hostname($uhome);
1.800     albertel 5760:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5761:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5762:                        $uhome);
1.479     albertel 5763:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5764:     return get_query_reply($queryid);
                   5765: }
                   5766: 
1.818     raeburn  5767: # -------------------------- Update MySQL table for portfolio file
                   5768: 
                   5769: sub update_portfolio_table {
1.821     raeburn  5770:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5771:     if ($group ne '') {
                   5772:         $file_name =~s /^\Q$group\E//;
                   5773:     }
1.818     raeburn  5774:     my $homeserver = &homeserver($uname,$udom);
                   5775:     my $queryid=
1.821     raeburn  5776:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5777:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5778:     my $reply = &get_query_reply($queryid);
                   5779:     return $reply;
                   5780: }
                   5781: 
1.899     raeburn  5782: # -------------------------- Update MySQL allusers table
                   5783: 
                   5784: sub update_allusers_table {
                   5785:     my ($uname,$udom,$names) = @_;
                   5786:     my $homeserver = &homeserver($uname,$udom);
                   5787:     my $queryid=
                   5788:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5789:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5790:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5791:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5792:                'generation='.&escape($names->{'generation'}).'%%'.
                   5793:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5794:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  5795:     return;
1.899     raeburn  5796: }
                   5797: 
1.508     raeburn  5798: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5799: 
                   5800: sub fetch_enrollment_query {
1.511     raeburn  5801:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5802:     my $homeserver;
1.547     raeburn  5803:     my $maxtries = 1;
1.508     raeburn  5804:     if ($context eq 'automated') {
                   5805:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5806:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5807:     } else {
                   5808:         $homeserver = &homeserver($cnum,$dom);
                   5809:     }
1.838     albertel 5810:     my $host=&hostname($homeserver);
1.506     raeburn  5811:     my $cmd = '';
1.1000    raeburn  5812:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5813:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5814:     }
                   5815:     $cmd =~ s/%%$//;
                   5816:     $cmd = &escape($cmd);
                   5817:     my $query = 'fetchenrollment';
1.620     albertel 5818:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5819:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5820:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5821:         return 'error: '.$queryid;
                   5822:     }
1.506     raeburn  5823:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5824:     my $tries = 1;
                   5825:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5826:         $reply = &get_query_reply($queryid);
                   5827:         $tries ++;
                   5828:     }
1.526     raeburn  5829:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5830:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5831:     } else {
1.901     albertel 5832:         my @responses = split(/:/,$reply);
1.515     raeburn  5833:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5834:             foreach my $line (@responses) {
                   5835:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5836:                 $$replyref{$key} = $value;
                   5837:             }
                   5838:         } else {
1.506     raeburn  5839:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5840:             foreach my $line (@responses) {
                   5841:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5842:                 $$replyref{$key} = $value;
                   5843:                 if ($value > 0) {
1.800     albertel 5844:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5845:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5846:                         my $destname = $pathname.'/'.$filename;
                   5847:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5848:                         if ($xml_classlist =~ /^error/) {
                   5849:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5850:                         } else {
1.506     raeburn  5851:                             if ( open(FILE,">$destname") ) {
                   5852:                                 print FILE &unescape($xml_classlist);
                   5853:                                 close(FILE);
1.526     raeburn  5854:                             } else {
                   5855:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5856:                             }
                   5857:                         }
                   5858:                     }
                   5859:                 }
                   5860:             }
                   5861:         }
                   5862:         return 'ok';
                   5863:     }
                   5864:     return 'error';
                   5865: }
                   5866: 
1.242     www      5867: sub get_query_reply {
                   5868:     my $queryid=shift;
1.240     www      5869:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5870:     my $reply='';
                   5871:     for (1..100) {
                   5872: 	sleep 2;
                   5873:         if (-e $replyfile.'.end') {
1.448     albertel 5874: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5875: 		$reply = join('',<$fh>);
                   5876: 		close($fh);
1.240     www      5877: 	   } else { return 'error: reply_file_error'; }
1.242     www      5878:            return &unescape($reply);
                   5879: 	}
1.240     www      5880:     }
1.242     www      5881:     return 'timeout:'.$queryid;
1.240     www      5882: }
                   5883: 
                   5884: sub courselog_query {
1.241     www      5885: #
                   5886: # possible filters:
                   5887: # url: url or symb
                   5888: # username
                   5889: # domain
                   5890: # action: view, submit, grade
                   5891: # start: timestamp
                   5892: # end: timestamp
                   5893: #
1.240     www      5894:     my (%filters)=@_;
1.620     albertel 5895:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5896:     if ($filters{'url'}) {
                   5897: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5898:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5899:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5900:     }
1.620     albertel 5901:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5902:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5903:     return &log_query($cname,$cdom,'courselog',%filters);
                   5904: }
                   5905: 
                   5906: sub userlog_query {
1.858     raeburn  5907: #
                   5908: # possible filters:
                   5909: # action: log check role
                   5910: # start: timestamp
                   5911: # end: timestamp
                   5912: #
1.240     www      5913:     my ($uname,$udom,%filters)=@_;
                   5914:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5915: }
                   5916: 
1.506     raeburn  5917: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5918: 
                   5919: sub auto_run {
1.508     raeburn  5920:     my ($cnum,$cdom) = @_;
1.876     raeburn  5921:     my $response = 0;
                   5922:     my $settings;
                   5923:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5924:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5925:         $settings = $domconfig{'autoenroll'};
                   5926:         if ($settings->{'run'} eq '1') {
                   5927:             $response = 1;
                   5928:         }
                   5929:     } else {
1.934     raeburn  5930:         my $homeserver;
                   5931:         if (&is_course($cdom,$cnum)) {
                   5932:             $homeserver = &homeserver($cnum,$cdom);
                   5933:         } else {
                   5934:             $homeserver = &domain($cdom,'primary');
                   5935:         }
                   5936:         if ($homeserver ne 'no_host') {
                   5937:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5938:         }
1.876     raeburn  5939:     }
1.506     raeburn  5940:     return $response;
                   5941: }
1.776     albertel 5942: 
1.506     raeburn  5943: sub auto_get_sections {
1.508     raeburn  5944:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5945:     my $homeserver;
                   5946:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5947:         $homeserver = &homeserver($cnum,$cdom);
                   5948:     }
                   5949:     if (!defined($homeserver)) { 
                   5950:         if ($cdom =~ /^$match_domain$/) {
                   5951:             $homeserver = &domain($cdom,'primary');
                   5952:         }
                   5953:     }
                   5954:     my @secs;
                   5955:     if (defined($homeserver)) {
                   5956:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5957:         unless ($response eq 'refused') {
                   5958:             @secs = split(/:/,$response);
                   5959:         }
1.506     raeburn  5960:     }
                   5961:     return @secs;
                   5962: }
1.776     albertel 5963: 
1.506     raeburn  5964: sub auto_new_course {
1.508     raeburn  5965:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5966:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5967:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5968:     return $response;
                   5969: }
1.776     albertel 5970: 
1.506     raeburn  5971: sub auto_validate_courseID {
1.508     raeburn  5972:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5973:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5974:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5975:     return $response;
                   5976: }
1.776     albertel 5977: 
1.1007    raeburn  5978: sub auto_validate_instcode {
1.1020    raeburn  5979:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  5980:     my ($homeserver,$response);
                   5981:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5982:         $homeserver = &homeserver($cnum,$cdom);
                   5983:     }
                   5984:     if (!defined($homeserver)) {
                   5985:         if ($cdom =~ /^$match_domain$/) {
                   5986:             $homeserver = &domain($cdom,'primary');
                   5987:         }
                   5988:     }
1.1065    raeburn  5989:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   5990:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  5991:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   5992:     return ($outcome,$description);
1.1007    raeburn  5993: }
                   5994: 
1.506     raeburn  5995: sub auto_create_password {
1.873     raeburn  5996:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5997:     my ($homeserver,$response);
1.506     raeburn  5998:     my $create_passwd = 0;
                   5999:     my $authchk = '';
1.873     raeburn  6000:     if ($udom =~ /^$match_domain$/) {
                   6001:         $homeserver = &domain($udom,'primary');
                   6002:     }
                   6003:     if ($homeserver eq '') {
                   6004:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6005:             $homeserver = &homeserver($cnum,$cdom);
                   6006:         }
                   6007:     }
                   6008:     if ($homeserver eq '') {
                   6009:         $authchk = 'nodomain';
1.506     raeburn  6010:     } else {
1.873     raeburn  6011:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6012:         if ($response eq 'refused') {
                   6013:             $authchk = 'refused';
                   6014:         } else {
1.901     albertel 6015:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6016:         }
1.506     raeburn  6017:     }
                   6018:     return ($authparam,$create_passwd,$authchk);
                   6019: }
                   6020: 
1.706     raeburn  6021: sub auto_photo_permission {
                   6022:     my ($cnum,$cdom,$students) = @_;
                   6023:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6024:     my ($outcome,$perm_reqd,$conditions) = 
                   6025: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6026:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6027: 	return (undef,undef);
                   6028:     }
1.706     raeburn  6029:     return ($outcome,$perm_reqd,$conditions);
                   6030: }
                   6031: 
                   6032: sub auto_checkphotos {
                   6033:     my ($uname,$udom,$pid) = @_;
                   6034:     my $homeserver = &homeserver($uname,$udom);
                   6035:     my ($result,$resulttype);
                   6036:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6037: 				   &escape($uname).':'.&escape($pid),
                   6038: 				   $homeserver));
1.709     albertel 6039:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6040: 	return (undef,undef);
                   6041:     }
1.706     raeburn  6042:     if ($outcome) {
                   6043:         ($result,$resulttype) = split(/:/,$outcome);
                   6044:     } 
                   6045:     return ($result,$resulttype);
                   6046: }
                   6047: 
                   6048: sub auto_photochoice {
                   6049:     my ($cnum,$cdom) = @_;
                   6050:     my $homeserver = &homeserver($cnum,$cdom);
                   6051:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6052: 						       &escape($cdom),
                   6053: 						       $homeserver)));
1.709     albertel 6054:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6055: 	return (undef,undef);
                   6056:     }
1.706     raeburn  6057:     return ($update,$comment);
                   6058: }
                   6059: 
                   6060: sub auto_photoupdate {
                   6061:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6062:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6063:     my $host=&hostname($homeserver);
1.706     raeburn  6064:     my $cmd = '';
                   6065:     my $maxtries = 1;
1.800     albertel 6066:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6067:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6068:     }
                   6069:     $cmd =~ s/%%$//;
                   6070:     $cmd = &escape($cmd);
                   6071:     my $query = 'institutionalphotos';
                   6072:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6073:     unless ($queryid=~/^\Q$host\E\_/) {
                   6074:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6075:         return 'error: '.$queryid;
                   6076:     }
                   6077:     my $reply = &get_query_reply($queryid);
                   6078:     my $tries = 1;
                   6079:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6080:         $reply = &get_query_reply($queryid);
                   6081:         $tries ++;
                   6082:     }
                   6083:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6084:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6085:     } else {
                   6086:         my @responses = split(/:/,$reply);
                   6087:         my $outcome = shift(@responses); 
                   6088:         foreach my $item (@responses) {
                   6089:             my ($key,$value) = split(/=/,$item);
                   6090:             $$photo{$key} = $value;
                   6091:         }
                   6092:         return $outcome;
                   6093:     }
                   6094:     return 'error';
                   6095: }
                   6096: 
1.521     raeburn  6097: sub auto_instcode_format {
1.793     albertel 6098:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6099: 	$cat_order) = @_;
1.521     raeburn  6100:     my $courses = '';
1.772     raeburn  6101:     my @homeservers;
1.521     raeburn  6102:     if ($caller eq 'global') {
1.841     albertel 6103: 	my %servers = &get_servers($codedom,'library');
                   6104: 	foreach my $tryserver (keys(%servers)) {
                   6105: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6106: 		push(@homeservers,$tryserver);
                   6107: 	    }
1.584     raeburn  6108:         }
1.1022    raeburn  6109:     } elsif ($caller eq 'requests') {
                   6110:         if ($codedom =~ /^$match_domain$/) {
                   6111:             my $chome = &domain($codedom,'primary');
                   6112:             unless ($chome eq 'no_host') {
                   6113:                 push(@homeservers,$chome);
                   6114:             }
                   6115:         }
1.521     raeburn  6116:     } else {
1.772     raeburn  6117:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6118:     }
1.793     albertel 6119:     foreach my $code (keys(%{$instcodes})) {
                   6120:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6121:     }
                   6122:     chop($courses);
1.772     raeburn  6123:     my $ok_response = 0;
                   6124:     my $response;
                   6125:     while (@homeservers > 0 && $ok_response == 0) {
                   6126:         my $server = shift(@homeservers); 
                   6127:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6128:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6129:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6130: 		split(/:/,$response);
1.772     raeburn  6131:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6132:             push(@{$codetitles},&str2array($codetitles_str));
                   6133:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6134:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6135:             $ok_response = 1;
                   6136:         }
                   6137:     }
                   6138:     if ($ok_response) {
1.521     raeburn  6139:         return 'ok';
1.772     raeburn  6140:     } else {
                   6141:         return $response;
1.521     raeburn  6142:     }
                   6143: }
                   6144: 
1.792     raeburn  6145: sub auto_instcode_defaults {
                   6146:     my ($domain,$returnhash,$code_order) = @_;
                   6147:     my @homeservers;
1.841     albertel 6148: 
                   6149:     my %servers = &get_servers($domain,'library');
                   6150:     foreach my $tryserver (keys(%servers)) {
                   6151: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6152: 	    push(@homeservers,$tryserver);
                   6153: 	}
1.792     raeburn  6154:     }
1.841     albertel 6155: 
1.792     raeburn  6156:     my $response;
1.841     albertel 6157:     foreach my $server (@homeservers) {
1.792     raeburn  6158:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6159:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6160: 	
                   6161: 	foreach my $pair (split(/\&/,$response)) {
                   6162: 	    my ($name,$value)=split(/\=/,$pair);
                   6163: 	    if ($name eq 'code_order') {
                   6164: 		@{$code_order} = split(/\&/,&unescape($value));
                   6165: 	    } else {
                   6166: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6167: 	    }
                   6168: 	}
                   6169: 	return 'ok';
1.792     raeburn  6170:     }
1.841     albertel 6171: 
                   6172:     return $response;
1.1003    raeburn  6173: }
                   6174: 
                   6175: sub auto_possible_instcodes {
1.1007    raeburn  6176:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6177:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6178:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6179:         return;
                   6180:     }
1.1003    raeburn  6181:     my (@homeservers,$uhome);
                   6182:     if (defined(&domain($domain,'primary'))) {
                   6183:         $uhome=&domain($domain,'primary');
                   6184:         push(@homeservers,&domain($domain,'primary'));
                   6185:     } else {
                   6186:         my %servers = &get_servers($domain,'library');
                   6187:         foreach my $tryserver (keys(%servers)) {
                   6188:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6189:                 push(@homeservers,$tryserver);
                   6190:             }
                   6191:         }
                   6192:     }
                   6193:     my $response;
                   6194:     foreach my $server (@homeservers) {
                   6195:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6196:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6197:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6198:             split(':',$response);
                   6199:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6200:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6201:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6202:             my ($name,$value)=split('=',$item);
                   6203:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6204:         }
                   6205:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6206:             my ($name,$value)=split('=',$item);
                   6207:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6208:         }
                   6209:         return 'ok';
                   6210:     }
                   6211:     return $response;
                   6212: }
1.792     raeburn  6213: 
1.1010    raeburn  6214: sub auto_courserequest_checks {
                   6215:     my ($dom) = @_;
1.1020    raeburn  6216:     my ($homeserver,%validations);
                   6217:     if ($dom =~ /^$match_domain$/) {
                   6218:         $homeserver = &domain($dom,'primary');
                   6219:     }
                   6220:     unless ($homeserver eq 'no_host') {
                   6221:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6222:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6223:             my @items = split(/&/,$response);
                   6224:             foreach my $item (@items) {
                   6225:                 my ($key,$value) = split('=',$item);
                   6226:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6227:             }
                   6228:         }
                   6229:     }
1.1010    raeburn  6230:     return %validations; 
                   6231: }
                   6232: 
1.1020    raeburn  6233: sub auto_courserequest_validation {
                   6234:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6235:     my ($homeserver,$response);
                   6236:     if ($dom =~ /^$match_domain$/) {
                   6237:         $homeserver = &domain($dom,'primary');
                   6238:     }
                   6239:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6240:           
1.1020    raeburn  6241:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6242:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6243:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6244:                                     $homeserver));
                   6245:     }
                   6246:     return $response;
                   6247: }
                   6248: 
1.777     albertel 6249: sub auto_validate_class_sec {
1.918     raeburn  6250:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6251:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6252:     my $ownerlist;
                   6253:     if (ref($owners) eq 'ARRAY') {
                   6254:         $ownerlist = join(',',@{$owners});
                   6255:     } else {
                   6256:         $ownerlist = $owners;
                   6257:     }
1.773     raeburn  6258:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6259:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6260:     return $response;
                   6261: }
                   6262: 
1.679     raeburn  6263: # ------------------------------------------------------- Course Group routines
                   6264: 
                   6265: sub get_coursegroups {
1.809     raeburn  6266:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6267:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6268: }
                   6269: 
1.679     raeburn  6270: sub modify_coursegroup {
                   6271:     my ($cdom,$cnum,$groupsettings) = @_;
                   6272:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6273: }
                   6274: 
1.809     raeburn  6275: sub toggle_coursegroup_status {
                   6276:     my ($cdom,$cnum,$group,$action) = @_;
                   6277:     my ($from_namespace,$to_namespace);
                   6278:     if ($action eq 'delete') {
                   6279:         $from_namespace = 'coursegroups';
                   6280:         $to_namespace = 'deleted_groups';
                   6281:     } else {
                   6282:         $from_namespace = 'deleted_groups';
                   6283:         $to_namespace = 'coursegroups';
                   6284:     }
                   6285:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6286:     if (my $tmp = &error(%curr_group)) {
                   6287:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6288:         return ('read error',$tmp);
                   6289:     } else {
                   6290:         my %savedsettings = %curr_group; 
1.809     raeburn  6291:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6292:         my $deloutcome;
                   6293:         if ($result eq 'ok') {
1.809     raeburn  6294:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6295:         } else {
                   6296:             return ('write error',$result);
                   6297:         }
                   6298:         if ($deloutcome eq 'ok') {
                   6299:             return 'ok';
                   6300:         } else {
                   6301:             return ('delete error',$deloutcome);
                   6302:         }
                   6303:     }
                   6304: }
                   6305: 
1.679     raeburn  6306: sub modify_group_roles {
1.957     raeburn  6307:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6308:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6309:     my $role = 'gr/'.&escape($userprivs);
                   6310:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6311:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6312:     if ($result eq 'ok') {
                   6313:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6314:     }
1.679     raeburn  6315:     return $result;
                   6316: }
                   6317: 
                   6318: sub modify_coursegroup_membership {
                   6319:     my ($cdom,$cnum,$membership) = @_;
                   6320:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6321:     return $result;
                   6322: }
                   6323: 
1.682     raeburn  6324: sub get_active_groups {
                   6325:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6326:     my $now = time;
                   6327:     my %groups = ();
                   6328:     foreach my $key (keys(%env)) {
1.811     albertel 6329:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6330:             my ($start,$end) = split(/\./,$env{$key});
                   6331:             if (($end!=0) && ($end<$now)) { next; }
                   6332:             if (($start!=0) && ($start>$now)) { next; }
                   6333:             if ($1 eq $cdom && $2 eq $cnum) {
                   6334:                 $groups{$3} = $env{$key} ;
                   6335:             }
                   6336:         }
                   6337:     }
                   6338:     return %groups;
                   6339: }
                   6340: 
1.683     raeburn  6341: sub get_group_membership {
                   6342:     my ($cdom,$cnum,$group) = @_;
                   6343:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6344: }
                   6345: 
                   6346: sub get_users_groups {
                   6347:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6348:     my @usersgroups;
1.683     raeburn  6349:     my $cachetime=1800;
                   6350: 
                   6351:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6352:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6353:     if (defined($cached)) {
1.734     albertel 6354:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6355:     } else {  
                   6356:         $grouplist = '';
1.816     raeburn  6357:         my $courseurl = &courseid_to_courseurl($courseid);
                   6358:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  6359:         my $access_end = $env{'course.'.$courseid.
                   6360:                               '.default_enrollment_end_date'};
                   6361:         my $now = time;
                   6362:         foreach my $key (keys(%roleshash)) {
                   6363:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6364:                 my $group = $1;
                   6365:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6366:                     my $start = $2;
                   6367:                     my $end = $1;
                   6368:                     if ($start == -1) { next; } # deleted from group
                   6369:                     if (($start!=0) && ($start>$now)) { next; }
                   6370:                     if (($end!=0) && ($end<$now)) {
                   6371:                         if ($access_end && $access_end < $now) {
                   6372:                             if ($access_end - $end < 86400) {
                   6373:                                 push(@usersgroups,$group);
1.733     raeburn  6374:                             }
                   6375:                         }
1.817     raeburn  6376:                         next;
1.733     raeburn  6377:                     }
1.817     raeburn  6378:                     push(@usersgroups,$group);
1.683     raeburn  6379:                 }
                   6380:             }
                   6381:         }
1.817     raeburn  6382:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6383:         $grouplist = join(':',@usersgroups);
                   6384:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6385:     }
1.733     raeburn  6386:     return @usersgroups;
1.683     raeburn  6387: }
                   6388: 
                   6389: sub devalidate_getgroups_cache {
                   6390:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6391:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6392: 
1.683     raeburn  6393:     my $hashid="$udom:$uname:$courseid";
                   6394:     &devalidate_cache_new('getgroups',$hashid);
                   6395: }
                   6396: 
1.12      www      6397: # ------------------------------------------------------------------ Plain Text
                   6398: 
                   6399: sub plaintext {
1.988     raeburn  6400:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6401:     if ($short =~ m{^cr/}) {
1.758     albertel 6402: 	return (split('/',$short))[-1];
                   6403:     }
1.742     raeburn  6404:     if (!defined($cid)) {
                   6405:         $cid = $env{'request.course.id'};
                   6406:     }
                   6407:     my %rolenames = (
1.1008    raeburn  6408:                       Course    => 'std',
                   6409:                       Community => 'alt1',
1.742     raeburn  6410:                     );
1.1037    raeburn  6411:     if ($cid ne '') {
                   6412:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6413:             unless ($forcedefault) {
                   6414:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6415:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6416:                 return &Apache::lonlocal::mt($roletext);
                   6417:             }
                   6418:         }
                   6419:     }
                   6420:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6421:         (defined($rolenames{$type})) && 
                   6422:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6423:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6424:     } elsif ($cid ne '') {
                   6425:         my $crstype = $env{'course.'.$cid.'.type'};
                   6426:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6427:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6428:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6429:         }
1.742     raeburn  6430:     }
1.1037    raeburn  6431:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6432: }
                   6433: 
                   6434: # ----------------------------------------------------------------- Assign Role
                   6435: 
                   6436: sub assignrole {
1.957     raeburn  6437:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6438:         $context)=@_;
1.21      www      6439:     my $mrole;
                   6440:     if ($role =~ /^cr\//) {
1.393     www      6441:         my $cwosec=$url;
1.811     albertel 6442:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6443: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6444:            my $refused = 1;
                   6445:            if ($context eq 'requestcourses') {
                   6446:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6447:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6448:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6449:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6450:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6451:                            if ($crsenv{'internal.courseowner'} eq
                   6452:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6453:                                $refused = '';
                   6454:                            }
                   6455:                        }
                   6456:                    }
                   6457:                }
                   6458:            }
                   6459:            if ($refused) {
                   6460:                &logthis('Refused custom assignrole: '.
                   6461:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6462:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6463:                return 'refused';
                   6464:            }
1.104     www      6465:         }
1.21      www      6466:         $mrole='cr';
1.678     raeburn  6467:     } elsif ($role =~ /^gr\//) {
                   6468:         my $cwogrp=$url;
1.811     albertel 6469:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6470:         unless (&allowed('mdg',$cwogrp)) {
                   6471:             &logthis('Refused group assignrole: '.
                   6472:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6473:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6474:             return 'refused';
                   6475:         }
                   6476:         $mrole='gr';
1.21      www      6477:     } else {
1.82      www      6478:         my $cwosec=$url;
1.811     albertel 6479:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6480:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6481:             my $refused;
                   6482:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6483:                 if (!(&allowed('c'.$role,$url))) {
                   6484:                     $refused = 1;
                   6485:                 }
                   6486:             } else {
                   6487:                 $refused = 1;
                   6488:             }
1.947     raeburn  6489:             if ($refused) {
1.1045    raeburn  6490:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6491:                 if (!$selfenroll && $context eq 'course') {
                   6492:                     my %crsenv;
                   6493:                     if ($role eq 'cc' || $role eq 'co') {
                   6494:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6495:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6496:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6497:                                 if ($crsenv{'internal.courseowner'} eq 
                   6498:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6499:                                     $refused = '';
                   6500:                                 }
                   6501:                             }
                   6502:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6503:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6504:                                 if ($crsenv{'internal.courseowner'} eq 
                   6505:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6506:                                     $refused = '';
                   6507:                                 }
                   6508:                             }
                   6509:                         }
                   6510:                     }
                   6511:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6512:                     $refused = '';
1.1017    raeburn  6513:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6514:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6515:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6516:                         my $wrongcc;
                   6517:                         if ($cnum =~ /^$match_community$/) {
                   6518:                             $wrongcc = 1 if ($role eq 'cc');
                   6519:                         } else {
                   6520:                             $wrongcc = 1 if ($role eq 'co');
                   6521:                         }
                   6522:                         unless ($wrongcc) {
                   6523:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6524:                             if ($crsenv{'internal.courseowner'} eq 
                   6525:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6526:                                 $refused = '';
                   6527:                             }
1.1017    raeburn  6528:                         }
                   6529:                     }
                   6530:                 }
                   6531:                 if ($refused) {
1.947     raeburn  6532:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6533:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6534: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6535:                     return 'refused';
                   6536:                 }
1.932     raeburn  6537:             }
1.104     www      6538:         }
1.21      www      6539:         $mrole=$role;
                   6540:     }
1.620     albertel 6541:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6542:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6543:     if ($end) { $command.='_'.$end; }
1.21      www      6544:     if ($start) {
                   6545: 	if ($end) { 
1.81      www      6546:            $command.='_'.$start; 
1.21      www      6547:         } else {
1.81      www      6548:            $command.='_0_'.$start;
1.21      www      6549:         }
                   6550:     }
1.739     raeburn  6551:     my $origstart = $start;
                   6552:     my $origend = $end;
1.957     raeburn  6553:     my $delflag;
1.357     www      6554: # actually delete
                   6555:     if ($deleteflag) {
1.373     www      6556: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6557: # modify command to delete the role
1.620     albertel 6558:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6559:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6560: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6561: # set start and finish to negative values for userrolelog
                   6562:            $start=-1;
                   6563:            $end=-1;
1.957     raeburn  6564:            $delflag = 1;
1.357     www      6565:         }
                   6566:     }
                   6567: # send command
1.349     www      6568:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6569: # log new user role if status is ok
1.349     www      6570:     if ($answer eq 'ok') {
1.663     raeburn  6571: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6572: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6573:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6574:         unless ($role =~ /^gr/) {
                   6575:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6576:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6577:         }
1.1053    raeburn  6578:         if ($role eq 'cc') {
                   6579:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6580:         }
1.349     www      6581:     }
                   6582:     return $answer;
1.169     harris41 6583: }
                   6584: 
1.1053    raeburn  6585: sub autoupdate_coowners {
                   6586:     my ($url,$end,$start,$uname,$udom) = @_;
                   6587:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6588:     if (($cdom ne '') && ($cnum ne '')) {
                   6589:         my $now = time;
                   6590:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6591:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6592:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6593:             my $instcode = $coursehash{'internal.coursecode'};
                   6594:             if ($instcode ne '') {
1.1056    raeburn  6595:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6596:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6597:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6598:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6599:                         if ($result eq 'valid') {
                   6600:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6601:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6602:                                     push(@newcoowners,$coowner);
                   6603:                                 }
                   6604:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6605:                                     push(@newcoowners,$uname.':'.$udom);
                   6606:                                 }
                   6607:                                 @newcoowners = sort(@newcoowners);
                   6608:                             } else {
                   6609:                                 push(@newcoowners,$uname.':'.$udom);
                   6610:                             }
                   6611:                         } else {
                   6612:                             if ($coursehash{'internal.co-owners'}) {
                   6613:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6614:                                     unless ($coowner eq $uname.':'.$udom) {
                   6615:                                         push(@newcoowners,$coowner);
                   6616:                                     }
                   6617:                                 }
                   6618:                                 unless (@newcoowners > 0) {
                   6619:                                     $delcoowners = 1;
                   6620:                                     $coowners = '';
                   6621:                                 }
                   6622:                             }
                   6623:                         }
                   6624:                         if (@newcoowners || $delcoowners) {
                   6625:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6626:                                             $delcoowners,@newcoowners);
                   6627:                         }
                   6628:                     }
                   6629:                 }
                   6630:             }
                   6631:         }
                   6632:     }
                   6633: }
                   6634: 
                   6635: sub store_coowners {
                   6636:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6637:     my $cid = $cdom.'_'.$cnum;
                   6638:     my ($coowners,$delresult,$putresult);
                   6639:     if (@newcoowners) {
                   6640:         $coowners = join(',',@newcoowners);
                   6641:         my %coownershash = (
                   6642:                             'internal.co-owners' => $coowners,
                   6643:                            );
                   6644:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6645:         if ($putresult eq 'ok') {
                   6646:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6647:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6648:             }
                   6649:         }
                   6650:     }
                   6651:     if ($delcoowners) {
                   6652:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6653:         if ($delresult eq 'ok') {
                   6654:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6655:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6656:             }
                   6657:         }
                   6658:     }
                   6659:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6660:         my %crsinfo =
                   6661:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6662:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6663:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6664:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6665:         }
                   6666:     }
                   6667: }
                   6668: 
1.169     harris41 6669: # -------------------------------------------------- Modify user authentication
1.197     www      6670: # Overrides without validation
                   6671: 
1.169     harris41 6672: sub modifyuserauth {
                   6673:     my ($udom,$uname,$umode,$upass)=@_;
                   6674:     my $uhome=&homeserver($uname,$udom);
1.197     www      6675:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6676:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6677:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6678:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6679:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6680: 		     &escape($upass),$uhome);
1.620     albertel 6681:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6682:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6683:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6684:     &log($udom,,$uname,$uhome,
1.620     albertel 6685:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6686:                                      $env{'user.name'}.', '.$umode.
1.197     www      6687:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6688:     unless ($reply eq 'ok') {
1.197     www      6689:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6690: 	return 'error: '.$reply;
                   6691:     }   
1.170     harris41 6692:     return 'ok';
1.80      www      6693: }
                   6694: 
1.81      www      6695: # --------------------------------------------------------------- Modify a user
1.80      www      6696: 
1.81      www      6697: sub modifyuser {
1.206     matthew  6698:     my ($udom,    $uname, $uid,
                   6699:         $umode,   $upass, $first,
                   6700:         $middle,  $last,  $gene,
1.1058    raeburn  6701:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6702:     $udom= &LONCAPA::clean_domain($udom);
                   6703:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6704:     my $showcandelete = 'none';
                   6705:     if (ref($candelete) eq 'ARRAY') {
                   6706:         if (@{$candelete} > 0) {
                   6707:             $showcandelete = join(', ',@{$candelete});
                   6708:         }
                   6709:     }
1.81      www      6710:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6711:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6712: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6713:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6714:                                      ' desiredhome not specified'). 
1.620     albertel 6715:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6716:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6717:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6718:     my $newuser;
                   6719:     if ($uhome eq 'no_host') {
                   6720:         $newuser = 1;
                   6721:     }
1.80      www      6722: # ----------------------------------------------------------------- Create User
1.406     albertel 6723:     if (($uhome eq 'no_host') && 
                   6724: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6725:         my $unhome='';
1.844     albertel 6726:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6727:             $unhome = $desiredhome;
1.620     albertel 6728: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6729: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6730:         } else { # load balancing routine for determining $unhome
1.81      www      6731:             my $loadm=10000000;
1.841     albertel 6732: 	    my %servers = &get_servers($udom,'library');
                   6733: 	    foreach my $tryserver (keys(%servers)) {
                   6734: 		my $answer=reply('load',$tryserver);
                   6735: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6736: 		    $loadm=$answer;
                   6737: 		    $unhome=$tryserver;
                   6738: 		}
1.80      www      6739: 	    }
                   6740:         }
                   6741:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6742: 	    return 'error: unable to find a home server for '.$uname.
                   6743:                    ' in domain '.$udom;
1.80      www      6744:         }
                   6745:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6746:                          &escape($upass),$unhome);
                   6747: 	unless ($reply eq 'ok') {
                   6748:             return 'error: '.$reply;
                   6749:         }   
1.230     stredwic 6750:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6751:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6752: 	    return 'error: unable verify users home machine.';
1.80      www      6753:         }
1.209     matthew  6754:     }   # End of creation of new user
1.80      www      6755: # ---------------------------------------------------------------------- Add ID
                   6756:     if ($uid) {
                   6757:        $uid=~tr/A-Z/a-z/;
                   6758:        my %uidhash=&idrget($udom,$uname);
1.196     www      6759:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6760:          && (!$forceid)) {
1.80      www      6761: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6762: 	      return 'error: user id "'.$uid.'" does not match '.
                   6763:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6764:           }
                   6765:        } else {
                   6766: 	  &idput($udom,($uname => $uid));
                   6767:        }
                   6768:     }
                   6769: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6770:     my @tmp=&get('environment',
1.899     raeburn  6771: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6772:                     'permanentemail','inststatus'],
1.134     albertel 6773: 		   $udom,$uname);
1.1075    raeburn  6774:     my (%names,%oldnames);
1.313     matthew  6775:     if ($tmp[0] =~ m/^error:.*/) { 
                   6776:         %names=(); 
                   6777:     } else {
                   6778:         %names = @tmp;
1.1075    raeburn  6779:         %oldnames = %names;
1.313     matthew  6780:     }
1.388     www      6781: #
1.1058    raeburn  6782: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6783: # of users did not contain them), do not overwrite existing values
                   6784: # unless field is in $candelete array ref.  
                   6785: #
                   6786: 
                   6787:     my @fields = ('firstname','middlename','lastname','generation',
                   6788:                   'permanentemail','id');
                   6789:     my %newvalues;
                   6790:     if (ref($candelete) eq 'ARRAY') {
                   6791:         foreach my $field (@fields) {
                   6792:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6793:                 if ($field eq 'firstname') {
                   6794:                     $names{$field} = $first;
                   6795:                 } elsif ($field eq 'middlename') {
                   6796:                     $names{$field} = $middle;
                   6797:                 } elsif ($field eq 'lastname') {
                   6798:                     $names{$field} = $last;
                   6799:                 } elsif ($field eq 'generation') { 
                   6800:                     $names{$field} = $gene;
                   6801:                 } elsif ($field eq 'permanentemail') {
                   6802:                     $names{$field} = $email;
                   6803:                 } elsif ($field eq 'id') {
                   6804:                     $names{$field}  = $uid;
                   6805:                 }
                   6806:             }
                   6807:         }
                   6808:     }
1.388     www      6809:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6810:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6811:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6812:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6813:     if ($email) {
                   6814:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6815:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6816:     }
1.899     raeburn  6817:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6818:     if (defined($inststatus)) {
                   6819:         $names{'inststatus'} = '';
                   6820:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6821:         if (ref($usertypes) eq 'HASH') {
                   6822:             my @okstatuses; 
                   6823:             foreach my $item (split(/:/,$inststatus)) {
                   6824:                 if (defined($usertypes->{$item})) {
                   6825:                     push(@okstatuses,$item);  
                   6826:                 }
                   6827:             }
                   6828:             if (@okstatuses) {
                   6829:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6830:             }
                   6831:         }
                   6832:     }
1.1075    raeburn  6833:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6834:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  6835:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6836:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6837:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6838:     } else {
                   6839:         $logmsg .= ' during self creation';
                   6840:     }
1.1075    raeburn  6841:     my $changed;
                   6842:     if ($newuser) {
                   6843:         $changed = 1;
                   6844:     } else {
                   6845:         foreach my $field (@fields) {
                   6846:             if ($names{$field} ne $oldnames{$field}) {
                   6847:                 $changed = 1;
                   6848:                 last;
                   6849:             }
                   6850:         }
                   6851:     }
                   6852:     unless ($changed) {
                   6853:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6854:         &logthis($logmsg);
                   6855:         return 'ok';
                   6856:     }
                   6857:     my $reply = &put('environment', \%names, $udom,$uname);
                   6858:     if ($reply ne 'ok') { 
                   6859:         return 'error: '.$reply;
                   6860:     }
                   6861:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6862:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6863:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6864:     &logthis($logmsg);
1.134     albertel 6865:     return 'ok';
1.80      www      6866: }
                   6867: 
1.81      www      6868: # -------------------------------------------------------------- Modify student
1.80      www      6869: 
1.81      www      6870: sub modifystudent {
                   6871:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6872:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6873:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6874:     if (!$cid) {
1.620     albertel 6875: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6876: 	    return 'not_in_class';
                   6877: 	}
1.80      www      6878:     }
                   6879: # --------------------------------------------------------------- Make the user
1.81      www      6880:     my $reply=&modifyuser
1.209     matthew  6881: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6882:          $desiredhome,$email,$inststatus);
1.80      www      6883:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6884:     # This will cause &modify_student_enrollment to get the uid from the
                   6885:     # students environment
                   6886:     $uid = undef if (!$forceid);
1.455     albertel 6887:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6888: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6889:     return $reply;
                   6890: }
                   6891: 
                   6892: sub modify_student_enrollment {
1.957     raeburn  6893:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6894:     my ($cdom,$cnum,$chome);
                   6895:     if (!$cid) {
1.620     albertel 6896: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6897: 	    return 'not_in_class';
                   6898: 	}
1.620     albertel 6899: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6900: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6901:     } else {
                   6902: 	($cdom,$cnum)=split(/_/,$cid);
                   6903:     }
1.620     albertel 6904:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6905:     if (!$chome) {
1.457     raeburn  6906: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6907:     }
1.455     albertel 6908:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6909:     # Make sure the user exists
1.81      www      6910:     my $uhome=&homeserver($uname,$udom);
                   6911:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6912: 	return 'error: no such user';
                   6913:     }
1.297     matthew  6914:     # Get student data if we were not given enough information
                   6915:     if (!defined($first)  || $first  eq '' || 
                   6916:         !defined($last)   || $last   eq '' || 
                   6917:         !defined($uid)    || $uid    eq '' || 
                   6918:         !defined($middle) || $middle eq '' || 
                   6919:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6920:         # They did not supply us with enough data to enroll the student, so
                   6921:         # we need to pick up more information.
1.297     matthew  6922:         my %tmp = &get('environment',
1.294     matthew  6923:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6924:                        ,$udom,$uname);
                   6925: 
1.800     albertel 6926:         #foreach my $key (keys(%tmp)) {
                   6927:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6928:         #}
1.294     matthew  6929:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6930:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6931:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6932:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6933:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6934:     }
1.556     albertel 6935:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6936:     my $reply=cput('classlist',
                   6937: 		   {"$uname:$udom" => 
1.515     raeburn  6938: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6939: 		   $cdom,$cnum);
1.81      www      6940:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6941: 	return 'error: '.$reply;
1.652     albertel 6942:     } else {
                   6943: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6944:     }
1.297     matthew  6945:     # Add student role to user
1.83      www      6946:     my $uurl='/'.$cid;
1.81      www      6947:     $uurl=~s/\_/\//g;
                   6948:     if ($usec) {
                   6949: 	$uurl.='/'.$usec;
                   6950:     }
1.957     raeburn  6951:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6952: }
                   6953: 
1.556     albertel 6954: sub format_name {
                   6955:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6956:     my $name;
                   6957:     if ($first ne 'lastname') {
                   6958: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6959:     } else {
                   6960: 	if ($lastname=~/\S/) {
                   6961: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6962: 	    $name=~s/\s+,/,/;
                   6963: 	} else {
                   6964: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6965: 	}
                   6966:     }
                   6967:     $name=~s/^\s+//;
                   6968:     $name=~s/\s+$//;
                   6969:     $name=~s/\s+/ /g;
                   6970:     return $name;
                   6971: }
                   6972: 
1.84      www      6973: # ------------------------------------------------- Write to course preferences
                   6974: 
                   6975: sub writecoursepref {
                   6976:     my ($courseid,%prefs)=@_;
                   6977:     $courseid=~s/^\///;
                   6978:     $courseid=~s/\_/\//g;
                   6979:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6980:     my $chome=homeserver($cnum,$cdomain);
                   6981:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6982: 	return 'error: no such course';
                   6983:     }
                   6984:     my $cstring='';
1.800     albertel 6985:     foreach my $pref (keys(%prefs)) {
                   6986: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6987:     }
1.84      www      6988:     $cstring=~s/\&$//;
                   6989:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6990: }
                   6991: 
                   6992: # ---------------------------------------------------------- Make/modify course
                   6993: 
                   6994: sub createcourse {
1.741     raeburn  6995:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  6996:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      6997:     $url=&declutter($url);
                   6998:     my $cid='';
1.1028    raeburn  6999:     if ($context eq 'requestcourses') {
                   7000:         my $can_create = 0;
                   7001:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7002:         if ($udom eq $ownerdom) {
                   7003:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7004:                                   $context)) {
                   7005:                 $can_create = 1;
                   7006:             }
                   7007:         } else {
                   7008:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7009:                                            $category);
                   7010:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7011:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7012:                 if (@curr > 0) {
                   7013:                     my @options = qw(approval validate autolimit);
                   7014:                     my $optregex = join('|',@options);
                   7015:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7016:                         $can_create = 1;
                   7017:                     }
                   7018:                 }
                   7019:             }
                   7020:         }
                   7021:         if ($can_create) {
                   7022:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7023:                 unless (&allowed('ccc',$udom)) {
                   7024:                     return 'refused'; 
                   7025:                 }
1.1017    raeburn  7026:             }
                   7027:         } else {
                   7028:             return 'refused';
                   7029:         }
1.1028    raeburn  7030:     } elsif (!&allowed('ccc',$udom)) {
                   7031:         return 'refused';
1.84      www      7032:     }
1.1011    raeburn  7033: # --------------------------------------------------------------- Get Unique ID
                   7034:     my $uname;
                   7035:     if ($cnum =~ /^$match_courseid$/) {
                   7036:         my $chome=&homeserver($cnum,$udom,'true');
                   7037:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7038:             $uname = $cnum;
                   7039:         } else {
1.1038    raeburn  7040:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7041:         }
                   7042:     } else {
1.1038    raeburn  7043:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7044:     }
                   7045:     return $uname if ($uname =~ /^error/);
                   7046: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7047:     if (!defined($course_server)) {
                   7048:         if (defined(&domain($udom,'primary'))) {
                   7049:             $course_server = &domain($udom,'primary');
                   7050:         } else {
                   7051:             $course_server = $env{'user.home'}; 
                   7052:         }
                   7053:     }
                   7054:     my %host_servers =
                   7055:         &Apache::lonnet::get_servers($udom,'library');
                   7056:     unless ($host_servers{$course_server}) {
                   7057:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7058:     }
1.84      www      7059: # ------------------------------------------------------------- Make the course
                   7060:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7061:                       $course_server);
1.84      www      7062:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7063:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7064:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7065: 	return 'error: no such course';
                   7066:     }
1.271     www      7067: # ----------------------------------------------------------------- Course made
1.516     raeburn  7068: # log existence
1.1029    raeburn  7069:     my $now = time;
1.918     raeburn  7070:     my $newcourse = {
                   7071:                     $udom.'_'.$uname => {
1.921     raeburn  7072:                                      description => $description,
                   7073:                                      inst_code   => $inst_code,
                   7074:                                      owner       => $course_owner,
                   7075:                                      type        => $crstype,
1.1029    raeburn  7076:                                      creator     => $env{'user.name'}.':'.
                   7077:                                                     $env{'user.domain'},
                   7078:                                      created     => $now,
                   7079:                                      context     => $context,
1.918     raeburn  7080:                                                 },
                   7081:                     };
1.921     raeburn  7082:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7083: # set toplevel url
1.271     www      7084:     my $topurl=$url;
                   7085:     unless ($nonstandard) {
                   7086: # ------------------------------------------ For standard courses, make top url
                   7087:         my $mapurl=&clutter($url);
1.278     www      7088:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7089:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7090: <map>
                   7091: <resource id="1" type="start"></resource>
                   7092: <resource id="2" src="$mapurl"></resource>
                   7093: <resource id="3" type="finish"></resource>
                   7094: <link index="1" from="1" to="2"></link>
                   7095: <link index="2" from="2" to="3"></link>
                   7096: </map>
                   7097: ENDINITMAP
                   7098:         $topurl=&declutter(
1.638     albertel 7099:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7100:                           );
                   7101:     }
                   7102: # ----------------------------------------------------------- Write preferences
1.84      www      7103:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7104:                      ('description'              => $description,
                   7105:                       'url'                      => $topurl,
                   7106:                       'internal.creator'         => $env{'user.name'}.':'.
                   7107:                                                     $env{'user.domain'},
                   7108:                       'internal.created'         => $now,
                   7109:                       'internal.creationcontext' => $context)
                   7110:                     );
1.84      www      7111:     return '/'.$udom.'/'.$uname;
                   7112: }
                   7113: 
1.1011    raeburn  7114: # ------------------------------------------------------------------- Create ID
                   7115: sub generate_coursenum {
1.1038    raeburn  7116:     my ($udom,$crstype) = @_;
1.1011    raeburn  7117:     my $domdesc = &domain($udom);
                   7118:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7119:     my $first;
                   7120:     if ($crstype eq 'Community') {
                   7121:         $first = '0';
                   7122:     } else {
                   7123:         $first = int(1+rand(9)); 
                   7124:     } 
                   7125:     my $uname=$first.
1.1011    raeburn  7126:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7127:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7128:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7129: # ----------------------------------------------- Make sure that does not exist
                   7130:     my $uhome=&homeserver($uname,$udom,'true');
                   7131:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7132:         if ($crstype eq 'Community') {
                   7133:             $first = '0';
                   7134:         } else {
                   7135:             $first = int(1+rand(9));
                   7136:         }
                   7137:         $uname=$first.
1.1011    raeburn  7138:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7139:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7140:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7141:         $uhome=&homeserver($uname,$udom,'true');
                   7142:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7143:             return 'error: unable to generate unique course-ID';
                   7144:         }
                   7145:     }
                   7146:     return $uname;
                   7147: }
                   7148: 
1.813     albertel 7149: sub is_course {
                   7150:     my ($cdom,$cnum) = @_;
                   7151:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7152: 				undef,'.');
1.813     albertel 7153:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7154:         return 1;
                   7155:     }
                   7156:     return 0;
                   7157: }
                   7158: 
1.1015    raeburn  7159: sub store_userdata {
                   7160:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7161:     my $result;
1.1016    raeburn  7162:     if ($datakey ne '') {
1.1013    raeburn  7163:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7164:             if ($udom eq '' || $uname eq '') {
                   7165:                 $udom = $env{'user.domain'};
                   7166:                 $uname = $env{'user.name'};
                   7167:             }
                   7168:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7169:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7170:                 $result = 'error: no_host';
                   7171:             } else {
                   7172:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7173:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7174: 
                   7175:                 my $namevalue='';
                   7176:                 foreach my $key (keys(%{$storehash})) {
                   7177:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7178:                 }
                   7179:                 $namevalue=~s/\&$//;
                   7180:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7181:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7182:             }
                   7183:         } else {
                   7184:             $result = 'error: data to store was not a hash reference'; 
                   7185:         }
                   7186:     } else {
                   7187:         $result= 'error: invalid requestkey'; 
                   7188:     }
                   7189:     return $result;
                   7190: }
                   7191: 
1.21      www      7192: # ---------------------------------------------------------- Assign Custom Role
                   7193: 
                   7194: sub assigncustomrole {
1.957     raeburn  7195:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7196:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7197:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7198: }
                   7199: 
                   7200: # ----------------------------------------------------------------- Revoke Role
                   7201: 
                   7202: sub revokerole {
1.957     raeburn  7203:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7204:     my $now=time;
1.965     raeburn  7205:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7206: }
                   7207: 
                   7208: # ---------------------------------------------------------- Revoke Custom Role
                   7209: 
                   7210: sub revokecustomrole {
1.957     raeburn  7211:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7212:     my $now=time;
1.357     www      7213:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7214:            $deleteflag,$selfenroll,$context);
1.17      www      7215: }
                   7216: 
1.533     banghart 7217: # ------------------------------------------------------------ Disk usage
1.535     albertel 7218: sub diskusage {
1.955     raeburn  7219:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7220:     $directorypath =~ s/\/$//;
                   7221:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7222:                        .&escape($getpropath).':'.&escape($uname).':'
                   7223:                        .&escape($udom),homeserver($uname,$udom));
                   7224:     if ($listing eq 'unknown_cmd') {
                   7225:         if ($getpropath) {
                   7226:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7227:         }
                   7228:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7229:     }
1.514     albertel 7230:     return $listing;
1.512     banghart 7231: }
                   7232: 
1.566     banghart 7233: sub is_locked {
                   7234:     my ($file_name, $domain, $user) = @_;
                   7235:     my @check;
                   7236:     my $is_locked;
                   7237:     push @check, $file_name;
1.613     albertel 7238:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7239: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7240:     my ($tmp)=keys(%locked);
                   7241:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7242:     
1.566     banghart 7243:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7244:         $is_locked = 'false';
                   7245:         foreach my $entry (@{$locked{$file_name}}) {
                   7246:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7247:                $is_locked = 'true';
                   7248:                last;
1.745     raeburn  7249:            }
                   7250:        }
1.566     banghart 7251:     } else {
                   7252:         $is_locked = 'false';
                   7253:     }
                   7254: }
                   7255: 
1.759     albertel 7256: sub declutter_portfile {
                   7257:     my ($file) = @_;
1.833     albertel 7258:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7259:     return $file;
                   7260: }
                   7261: 
1.559     banghart 7262: # ------------------------------------------------------------- Mark as Read Only
                   7263: 
                   7264: sub mark_as_readonly {
                   7265:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7266:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7267:     my ($tmp)=keys(%current_permissions);
                   7268:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7269:     foreach my $file (@{$files}) {
1.759     albertel 7270: 	$file = &declutter_portfile($file);
1.561     banghart 7271:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7272:     }
1.613     albertel 7273:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7274:     return;
                   7275: }
                   7276: 
1.572     banghart 7277: # ------------------------------------------------------------Save Selected Files
                   7278: 
                   7279: sub save_selected_files {
                   7280:     my ($user, $path, @files) = @_;
                   7281:     my $filename = $user."savedfiles";
1.573     banghart 7282:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7283:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7284:     foreach my $file (@files) {
1.620     albertel 7285:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7286:     }
                   7287:     foreach my $file (@other_files) {
1.574     banghart 7288:         print (OUT $file."\n");
1.572     banghart 7289:     }
1.574     banghart 7290:     close (OUT);
1.572     banghart 7291:     return 'ok';
                   7292: }
                   7293: 
1.574     banghart 7294: sub clear_selected_files {
                   7295:     my ($user) = @_;
                   7296:     my $filename = $user."savedfiles";
                   7297:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7298:     print (OUT undef);
                   7299:     close (OUT);
                   7300:     return ("ok");    
                   7301: }
                   7302: 
1.572     banghart 7303: sub files_in_path {
                   7304:     my ($user, $path) = @_;
                   7305:     my $filename = $user."savedfiles";
                   7306:     my %return_files;
1.574     banghart 7307:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7308:     while (my $line_in = <IN>) {
1.574     banghart 7309:         chomp ($line_in);
                   7310:         my @paths_and_file = split (m!/!, $line_in);
                   7311:         my $file_part = pop (@paths_and_file);
                   7312:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7313:         $path_part.='/';
                   7314:         my $path_and_file = $path_part.$file_part;
                   7315:         if ($path_part eq $path) {
                   7316:             $return_files{$file_part}= 'selected';
                   7317:         }
                   7318:     }
1.574     banghart 7319:     close (IN);
                   7320:     return (\%return_files);
1.572     banghart 7321: }
                   7322: 
                   7323: # called in portfolio select mode, to show files selected NOT in current directory
                   7324: sub files_not_in_path {
                   7325:     my ($user, $path) = @_;
                   7326:     my $filename = $user."savedfiles";
                   7327:     my @return_files;
                   7328:     my $path_part;
1.800     albertel 7329:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7330:     while (my $line = <IN>) {
1.572     banghart 7331:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7332:         my @paths_and_file = split(m|/|, $line);
                   7333:         my $file_part = pop(@paths_and_file);
                   7334:         chomp($file_part);
                   7335:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7336:         $path_part .= '/';
                   7337:         my $path_and_file = $path_part.$file_part;
                   7338:         if ($path_part ne $path) {
1.800     albertel 7339:             push(@return_files, ($path_and_file));
1.572     banghart 7340:         }
                   7341:     }
1.800     albertel 7342:     close(OUT);
1.574     banghart 7343:     return (@return_files);
1.572     banghart 7344: }
                   7345: 
1.745     raeburn  7346: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7347: 
1.745     raeburn  7348: sub get_portfile_permissions {
                   7349:     my ($domain,$user) = @_;
1.613     albertel 7350:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7351:     my ($tmp)=keys(%current_permissions);
                   7352:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7353:     return \%current_permissions;
                   7354: }
                   7355: 
                   7356: #---------------------------------------------Get portfolio file access controls
                   7357: 
1.749     raeburn  7358: sub get_access_controls {
1.745     raeburn  7359:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7360:     my %access;
                   7361:     my $real_file = $file;
                   7362:     $file =~ s/\.meta$//;
1.745     raeburn  7363:     if (defined($file)) {
1.749     raeburn  7364:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7365:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7366:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7367:             }
                   7368:         }
1.745     raeburn  7369:     } else {
1.749     raeburn  7370:         foreach my $key (keys(%{$current_permissions})) {
                   7371:             if ($key =~ /\0accesscontrol$/) {
                   7372:                 if (defined($group)) {
                   7373:                     if ($key !~ m-^\Q$group\E/-) {
                   7374:                         next;
                   7375:                     }
                   7376:                 }
                   7377:                 my ($fullpath) = split(/\0/,$key);
                   7378:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7379:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7380:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7381:                     }
                   7382:                 }
                   7383:             }
                   7384:         }
                   7385:     }
                   7386:     return %access;
                   7387: }
                   7388: 
                   7389: sub modify_access_controls {
                   7390:     my ($file_name,$changes,$domain,$user)=@_;
                   7391:     my ($outcome,$deloutcome);
                   7392:     my %store_permissions;
                   7393:     my %new_values;
                   7394:     my %new_control;
                   7395:     my %translation;
                   7396:     my @deletions = ();
                   7397:     my $now = time;
                   7398:     if (exists($$changes{'activate'})) {
                   7399:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7400:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7401:             my $numnew = scalar(@newitems);
                   7402:             for (my $i=0; $i<$numnew; $i++) {
                   7403:                 my $newkey = $newitems[$i];
                   7404:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7405:                 if ($newkey =~ /^\d+:/) { 
                   7406:                     $newkey =~ s/^(\d+)/$newid/;
                   7407:                     $translation{$1} = $newid;
                   7408:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7409:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7410:                     $translation{$1} = $newid;
                   7411:                 }
1.749     raeburn  7412:                 $new_values{$file_name."\0".$newkey} = 
                   7413:                                           $$changes{'activate'}{$newitems[$i]};
                   7414:                 $new_control{$newkey} = $now;
                   7415:             }
                   7416:         }
                   7417:     }
                   7418:     my %todelete;
                   7419:     my %changed_items;
                   7420:     foreach my $action ('delete','update') {
                   7421:         if (exists($$changes{$action})) {
                   7422:             if (ref($$changes{$action}) eq 'HASH') {
                   7423:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7424:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7425:                     if ($action eq 'delete') { 
                   7426:                         $todelete{$itemnum} = 1;
                   7427:                     } else {
                   7428:                         $changed_items{$itemnum} = $key;
                   7429:                     }
                   7430:                 }
1.745     raeburn  7431:             }
                   7432:         }
1.749     raeburn  7433:     }
                   7434:     # get lock on access controls for file.
                   7435:     my $lockhash = {
                   7436:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7437:                                                        ':'.$env{'user.domain'},
                   7438:                    }; 
                   7439:     my $tries = 0;
                   7440:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7441:    
                   7442:     while (($gotlock ne 'ok') && $tries <3) {
                   7443:         $tries ++;
                   7444:         sleep 1;
                   7445:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7446:     }
                   7447:     if ($gotlock eq 'ok') {
                   7448:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7449:         my ($tmp)=keys(%curr_permissions);
                   7450:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7451:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7452:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7453:             if (ref($curr_controls) eq 'HASH') {
                   7454:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7455:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7456:                     if (defined($todelete{$itemnum})) {
                   7457:                         push(@deletions,$file_name."\0".$control_item);
                   7458:                     } else {
                   7459:                         if (defined($changed_items{$itemnum})) {
                   7460:                             $new_control{$changed_items{$itemnum}} = $now;
                   7461:                             push(@deletions,$file_name."\0".$control_item);
                   7462:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7463:                         } else {
                   7464:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7465:                         }
                   7466:                     }
1.745     raeburn  7467:                 }
                   7468:             }
                   7469:         }
1.970     raeburn  7470:         my ($group);
                   7471:         if (&is_course($domain,$user)) {
                   7472:             ($group,my $file) = split(/\//,$file_name,2);
                   7473:         }
1.749     raeburn  7474:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7475:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7476:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7477:         #  remove lock
                   7478:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7479:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7480:         my $sqlresult =
1.970     raeburn  7481:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7482:                                     $group);
1.749     raeburn  7483:     } else {
                   7484:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7485:     }
1.749     raeburn  7486:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7487: }
                   7488: 
1.827     raeburn  7489: sub make_public_indefinitely {
                   7490:     my ($requrl) = @_;
                   7491:     my $now = time;
                   7492:     my $action = 'activate';
                   7493:     my $aclnum = 0;
                   7494:     if (&is_portfolio_url($requrl)) {
                   7495:         my (undef,$udom,$unum,$file_name,$group) =
                   7496:             &parse_portfolio_url($requrl);
                   7497:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7498:         my %access_controls = &get_access_controls($current_perms,
                   7499:                                                    $group,$file_name);
                   7500:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7501:             my ($num,$scope,$end,$start) = 
                   7502:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7503:             if ($scope eq 'public') {
                   7504:                 if ($start <= $now && $end == 0) {
                   7505:                     $action = 'none';
                   7506:                 } else {
                   7507:                     $action = 'update';
                   7508:                     $aclnum = $num;
                   7509:                 }
                   7510:                 last;
                   7511:             }
                   7512:         }
                   7513:         if ($action eq 'none') {
                   7514:              return 'ok';
                   7515:         } else {
                   7516:             my %changes;
                   7517:             my $newend = 0;
                   7518:             my $newstart = $now;
                   7519:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7520:             $changes{$action}{$newkey} = {
                   7521:                 type => 'public',
                   7522:                 time => {
                   7523:                     start => $newstart,
                   7524:                     end   => $newend,
                   7525:                 },
                   7526:             };
                   7527:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7528:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7529:             return $outcome;
                   7530:         }
                   7531:     } else {
                   7532:         return 'invalid';
                   7533:     }
                   7534: }
                   7535: 
1.745     raeburn  7536: #------------------------------------------------------Get Marked as Read Only
                   7537: 
                   7538: sub get_marked_as_readonly {
                   7539:     my ($domain,$user,$what,$group) = @_;
                   7540:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7541:     my @readonly_files;
1.629     banghart 7542:     my $cmp1=$what;
                   7543:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7544:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7545:         if (defined($group)) {
                   7546:             if ($file_name !~ m-^\Q$group\E/-) {
                   7547:                 next;
                   7548:             }
                   7549:         }
1.561     banghart 7550:         if (ref($value) eq "ARRAY"){
                   7551:             foreach my $stored_what (@{$value}) {
1.629     banghart 7552:                 my $cmp2=$stored_what;
1.759     albertel 7553:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7554:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7555:                 }
1.629     banghart 7556:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7557:                     push(@readonly_files, $file_name);
1.745     raeburn  7558:                     last;
1.563     banghart 7559:                 } elsif (!defined($what)) {
                   7560:                     push(@readonly_files, $file_name);
1.745     raeburn  7561:                     last;
1.561     banghart 7562:                 }
                   7563:             }
1.745     raeburn  7564:         }
1.561     banghart 7565:     }
                   7566:     return @readonly_files;
                   7567: }
1.577     banghart 7568: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7569: 
1.577     banghart 7570: sub get_marked_as_readonly_hash {
1.745     raeburn  7571:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7572:     my %readonly_files;
1.745     raeburn  7573:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7574:         if (defined($group)) {
                   7575:             if ($file_name !~ m-^\Q$group\E/-) {
                   7576:                 next;
                   7577:             }
                   7578:         }
1.577     banghart 7579:         if (ref($value) eq "ARRAY"){
                   7580:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7581:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7582:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7583:                         if ($lock_descriptor eq 'graded') {
                   7584:                             $readonly_files{$file_name} = 'graded';
                   7585:                         } elsif ($lock_descriptor eq 'handback') {
                   7586:                             $readonly_files{$file_name} = 'handback';
                   7587:                         } else {
                   7588:                             if (!exists($readonly_files{$file_name})) {
                   7589:                                 $readonly_files{$file_name} = 'locked';
                   7590:                             }
                   7591:                         }
1.745     raeburn  7592:                     }
1.750     banghart 7593:                 } 
1.577     banghart 7594:             }
                   7595:         } 
                   7596:     }
                   7597:     return %readonly_files;
                   7598: }
1.559     banghart 7599: # ------------------------------------------------------------ Unmark as Read Only
                   7600: 
                   7601: sub unmark_as_readonly {
1.629     banghart 7602:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7603:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7604:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7605:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7606:     my $symb_crs = $what;
                   7607:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7608:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7609:     my ($tmp)=keys(%current_permissions);
                   7610:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7611:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7612:     foreach my $file (@readonly_files) {
1.759     albertel 7613: 	my $clean_file = &declutter_portfile($file);
                   7614: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7615: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7616:         my @new_locks;
                   7617:         my @del_keys;
                   7618:         if (ref($current_locks) eq "ARRAY"){
                   7619:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7620:                 my $compare=$locker;
1.749     raeburn  7621:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7622:                     $compare=join('',@{$locker});
1.746     raeburn  7623:                     if ($compare ne $symb_crs) {
                   7624:                         push(@new_locks, $locker);
                   7625:                     }
1.563     banghart 7626:                 }
                   7627:             }
1.650     albertel 7628:             if (scalar(@new_locks) > 0) {
1.563     banghart 7629:                 $current_permissions{$file} = \@new_locks;
                   7630:             } else {
                   7631:                 push(@del_keys, $file);
1.613     albertel 7632:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7633:                 delete($current_permissions{$file});
1.563     banghart 7634:             }
                   7635:         }
1.561     banghart 7636:     }
1.613     albertel 7637:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7638:     return;
                   7639: }
1.512     banghart 7640: 
1.17      www      7641: # ------------------------------------------------------------ Directory lister
                   7642: 
                   7643: sub dirlist {
1.955     raeburn  7644:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7645:     $uri=~s/^\///;
                   7646:     $uri=~s/\/$//;
1.253     stredwic 7647:     my ($udom, $uname);
1.955     raeburn  7648:     if ($getuserdir) {
1.253     stredwic 7649:         $udom = $userdomain;
                   7650:         $uname = $username;
1.955     raeburn  7651:     } else {
                   7652:         (undef,$udom,$uname)=split(/\//,$uri);
                   7653:         if(defined($userdomain)) {
                   7654:             $udom = $userdomain;
                   7655:         }
                   7656:         if(defined($username)) {
                   7657:             $uname = $username;
                   7658:         }
1.253     stredwic 7659:     }
1.955     raeburn  7660:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7661: 
1.955     raeburn  7662:     $dirRoot = $perlvar{'lonDocRoot'};
                   7663:     if (defined($getpropath)) {
                   7664:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7665:         $dirRoot =~ s/\/$//;
1.955     raeburn  7666:     } elsif (defined($getuserdir)) {
                   7667:         my $subdir=$uname.'__';
                   7668:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7669:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7670:                    ."/$udom/$subdir/$uname";
                   7671:     } elsif (defined($alternateRoot)) {
                   7672:         $dirRoot = $alternateRoot;
1.751     banghart 7673:     }
1.253     stredwic 7674: 
                   7675:     if($udom) {
                   7676:         if($uname) {
1.955     raeburn  7677:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7678:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7679:                               .':'.&escape($uname).':'.&escape($udom),
                   7680:                               &homeserver($uname,$udom));
                   7681:             if ($listing eq 'unknown_cmd') {
                   7682:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7683:                                   &homeserver($uname,$udom));
                   7684:             } else {
                   7685:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7686:             }
1.605     matthew  7687:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7688:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7689: 				  &homeserver($uname,$udom));
1.605     matthew  7690:                 @listing_results = split(/:/,$listing);
                   7691:             } else {
                   7692:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7693:             }
                   7694:             return @listing_results;
1.955     raeburn  7695:         } elsif(!$alternateRoot) {
1.800     albertel 7696:             my %allusers;
1.841     albertel 7697: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7698:  	    foreach my $tryserver (keys(%servers)) {
                   7699:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7700:                                   &escape($udom),$tryserver);
                   7701:                 if ($listing eq 'unknown_cmd') {
                   7702: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7703: 				      $udom, $tryserver);
                   7704:                 } else {
                   7705:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7706:                 }
1.841     albertel 7707: 		if ($listing eq 'unknown_cmd') {
                   7708: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7709: 				      $udom, $tryserver);
                   7710: 		    @listing_results = split(/:/,$listing);
                   7711: 		} else {
                   7712: 		    @listing_results =
                   7713: 			map { &unescape($_); } split(/:/,$listing);
                   7714: 		}
                   7715: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7716: 		    $listing_results[0] ne 'empty'       &&
                   7717: 		    $listing_results[0] ne 'con_lost') {
                   7718: 		    foreach my $line (@listing_results) {
                   7719: 			my ($entry) = split(/&/,$line,2);
                   7720: 			$allusers{$entry} = 1;
                   7721: 		    }
                   7722: 		}
1.253     stredwic 7723:             }
                   7724:             my $alluserstr='';
1.800     albertel 7725:             foreach my $user (sort(keys(%allusers))) {
                   7726:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7727:             }
                   7728:             $alluserstr=~s/:$//;
                   7729:             return split(/:/,$alluserstr);
                   7730:         } else {
1.800     albertel 7731:             return ('missing user name');
1.253     stredwic 7732:         }
1.955     raeburn  7733:     } elsif(!defined($getpropath)) {
1.841     albertel 7734:         my @all_domains = sort(&all_domains());
1.955     raeburn  7735:         foreach my $domain (@all_domains) {
                   7736:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7737:         }
                   7738:         return @all_domains;
                   7739:     } else {
1.800     albertel 7740:         return ('missing domain');
1.275     stredwic 7741:     }
                   7742: }
                   7743: 
                   7744: # --------------------------------------------- GetFileTimestamp
                   7745: # This function utilizes dirlist and returns the date stamp for
                   7746: # when it was last modified.  It will also return an error of -1
                   7747: # if an error occurs
                   7748: 
                   7749: sub GetFileTimestamp {
1.955     raeburn  7750:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7751:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7752:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7753:     my ($fileStat) = 
                   7754:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7755:                                  undef,$getuserdir);
1.275     stredwic 7756:     my @stats = split('&', $fileStat);
                   7757:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7758:         # @stats contains first the filename, then the stat output
                   7759:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7760:     } else {
                   7761:         return -1;
1.253     stredwic 7762:     }
1.26      www      7763: }
                   7764: 
1.712     albertel 7765: sub stat_file {
                   7766:     my ($uri) = @_;
1.787     albertel 7767:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7768: 
1.955     raeburn  7769:     my ($udom,$uname,$file);
1.712     albertel 7770:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7771: 	($udom,$uname,$file) =
1.811     albertel 7772: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7773: 	$file = 'userfiles/'.$file;
                   7774:     }
                   7775:     if ($uri =~ m-^/res/-) {
                   7776: 	($udom,$uname) = 
1.807     albertel 7777: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7778: 	$file = $uri;
                   7779:     }
                   7780: 
                   7781:     if (!$udom || !$uname || !$file) {
                   7782: 	# unable to handle the uri
                   7783: 	return ();
                   7784:     }
1.956     raeburn  7785:     my $getpropath;
                   7786:     if ($file =~ /^userfiles\//) {
                   7787:         $getpropath = 1;
                   7788:     }
1.955     raeburn  7789:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7790:     my @stats = split('&', $result);
1.721     banghart 7791:     
1.712     albertel 7792:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7793: 	shift(@stats); #filename is first
                   7794: 	return @stats;
                   7795:     }
                   7796:     return ();
                   7797: }
                   7798: 
1.26      www      7799: # -------------------------------------------------------- Value of a Condition
                   7800: 
1.713     albertel 7801: # gets the value of a specific preevaluated condition
                   7802: #    stored in the string  $env{user.state.<cid>}
                   7803: # or looks up a condition reference in the bighash and if if hasn't
                   7804: # already been evaluated recurses into docondval to get the value of
                   7805: # the condition, then memoizing it to 
                   7806: #   $env{user.state.<cid>.<condition>}
1.40      www      7807: sub directcondval {
                   7808:     my $number=shift;
1.620     albertel 7809:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7810: 	&Apache::lonuserstate::evalstate();
                   7811:     }
1.713     albertel 7812:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7813: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7814:     } elsif ($number =~ /^_/) {
                   7815: 	my $sub_condition;
                   7816: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7817: 		&GDBM_READER(),0640)) {
                   7818: 	    $sub_condition=$bighash{'conditions'.$number};
                   7819: 	    untie(%bighash);
                   7820: 	}
                   7821: 	my $value = &docondval($sub_condition);
1.949     raeburn  7822: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7823: 	return $value;
                   7824:     }
1.620     albertel 7825:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7826:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7827:     } else {
                   7828:        return 2;
                   7829:     }
                   7830: }
                   7831: 
1.713     albertel 7832: # get the collection of conditions for this resource
1.26      www      7833: sub condval {
                   7834:     my $condidx=shift;
1.54      www      7835:     my $allpathcond='';
1.713     albertel 7836:     foreach my $cond (split(/\|/,$condidx)) {
                   7837: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7838: 	    $allpathcond.=
                   7839: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7840: 	}
1.191     harris41 7841:     }
1.54      www      7842:     $allpathcond=~s/\|$//;
1.713     albertel 7843:     return &docondval($allpathcond);
                   7844: }
                   7845: 
                   7846: #evaluates an expression of conditions
                   7847: sub docondval {
                   7848:     my ($allpathcond) = @_;
                   7849:     my $result=0;
                   7850:     if ($env{'request.course.id'}
                   7851: 	&& defined($allpathcond)) {
                   7852: 	my $operand='|';
                   7853: 	my @stack;
                   7854: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7855: 	    if ($chunk eq '(') {
                   7856: 		push @stack,($operand,$result);
                   7857: 	    } elsif ($chunk eq ')') {
                   7858: 		my $before=pop @stack;
                   7859: 		if (pop @stack eq '&') {
                   7860: 		    $result=$result>$before?$before:$result;
                   7861: 		} else {
                   7862: 		    $result=$result>$before?$result:$before;
                   7863: 		}
                   7864: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7865: 		$operand=$chunk;
                   7866: 	    } else {
                   7867: 		my $new=directcondval($chunk);
                   7868: 		if ($operand eq '&') {
                   7869: 		    $result=$result>$new?$new:$result;
                   7870: 		} else {
                   7871: 		    $result=$result>$new?$result:$new;
                   7872: 		}
                   7873: 	    }
                   7874: 	}
1.26      www      7875:     }
                   7876:     return $result;
1.421     albertel 7877: }
                   7878: 
                   7879: # ---------------------------------------------------- Devalidate courseresdata
                   7880: 
                   7881: sub devalidatecourseresdata {
                   7882:     my ($coursenum,$coursedomain)=@_;
                   7883:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7884:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7885: }
                   7886: 
1.763     www      7887: 
1.200     www      7888: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7889: #
                   7890: #  Parameters:
                   7891: #      $coursenum    - Number of the course.
                   7892: #      $coursedomain - Domain at which the course was created.
                   7893: #  Returns:
                   7894: #     A hash of the course parameters along (I think) with timestamps
                   7895: #     and version info.
1.877     foxr     7896: 
1.624     albertel 7897: sub get_courseresdata {
                   7898:     my ($coursenum,$coursedomain)=@_;
1.200     www      7899:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7900:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7901:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7902:     my %dumpreply;
1.417     albertel 7903:     unless (defined($cached)) {
1.624     albertel 7904: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7905: 	$result=\%dumpreply;
1.251     albertel 7906: 	my ($tmp) = keys(%dumpreply);
                   7907: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7908: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7909: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7910: 	    return $tmp;
1.416     albertel 7911: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7912: 	    $result=undef;
1.599     albertel 7913: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7914: 	}
                   7915:     }
1.624     albertel 7916:     return $result;
                   7917: }
                   7918: 
1.633     albertel 7919: sub devalidateuserresdata {
                   7920:     my ($uname,$udom)=@_;
                   7921:     my $hashid="$udom:$uname";
                   7922:     &devalidate_cache_new('userres',$hashid);
                   7923: }
                   7924: 
1.624     albertel 7925: sub get_userresdata {
                   7926:     my ($uname,$udom)=@_;
                   7927:     #most student don\'t have any data set, check if there is some data
                   7928:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7929: 
                   7930:     my $hashid="$udom:$uname";
                   7931:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7932:     if (!defined($cached)) {
                   7933: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7934: 	$result=\%resourcedata;
                   7935: 	&do_cache_new('userres',$hashid,$result,600);
                   7936:     }
                   7937:     my ($tmp)=keys(%$result);
                   7938:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7939: 	return $result;
                   7940:     }
                   7941:     #error 2 occurs when the .db doesn't exist
                   7942:     if ($tmp!~/error: 2 /) {
1.672     albertel 7943: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7944: 		 " Trying to get resource data for ".
                   7945: 		 $uname." at ".$udom.": ".
                   7946: 		 $tmp."</font>");
                   7947:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7948: 	#&EXT_cache_set($udom,$uname);
                   7949: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7950: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7951:     }
                   7952:     return $tmp;
                   7953: }
1.879     foxr     7954: #----------------------------------------------- resdata - return resource data
                   7955: #  Purpose:
                   7956: #    Return resource data for either users or for a course.
                   7957: #  Parameters:
                   7958: #     $name      - Course/user name.
                   7959: #     $domain    - Name of the domain the user/course is registered on.
                   7960: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7961: #     @which     - Array of names of resources desired.
                   7962: #  Returns:
                   7963: #     The value of the first reasource in @which that is found in the
                   7964: #     resource hash.
                   7965: #  Exceptional Conditions:
                   7966: #     If the $type passed in is not valid (not the string 'course' or 
                   7967: #     'user', an undefined  reference is returned.
                   7968: #     If none of the resources are found, an undef is returned
1.624     albertel 7969: sub resdata {
                   7970:     my ($name,$domain,$type,@which)=@_;
                   7971:     my $result;
                   7972:     if ($type eq 'course') {
                   7973: 	$result=&get_courseresdata($name,$domain);
                   7974:     } elsif ($type eq 'user') {
                   7975: 	$result=&get_userresdata($name,$domain);
                   7976:     }
                   7977:     if (!ref($result)) { return $result; }    
1.251     albertel 7978:     foreach my $item (@which) {
1.927     albertel 7979: 	if (defined($result->{$item->[0]})) {
                   7980: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7981: 	}
1.250     albertel 7982:     }
1.291     albertel 7983:     return undef;
1.200     www      7984: }
                   7985: 
1.379     matthew  7986: #
                   7987: # EXT resource caching routines
                   7988: #
                   7989: 
                   7990: sub clear_EXT_cache_status {
1.383     albertel 7991:     &delenv('cache.EXT.');
1.379     matthew  7992: }
                   7993: 
                   7994: sub EXT_cache_status {
                   7995:     my ($target_domain,$target_user) = @_;
1.383     albertel 7996:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7997:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7998:         # We know already the user has no data
                   7999:         return 1;
                   8000:     } else {
                   8001:         return 0;
                   8002:     }
                   8003: }
                   8004: 
                   8005: sub EXT_cache_set {
                   8006:     my ($target_domain,$target_user) = @_;
1.383     albertel 8007:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8008:     #&appenv({$cachename => time});
1.379     matthew  8009: }
                   8010: 
1.28      www      8011: # --------------------------------------------------------- Value of a Variable
1.58      www      8012: sub EXT {
1.715     albertel 8013: 
1.395     albertel 8014:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8015:     unless ($varname) { return ''; }
1.218     albertel 8016:     #get real user name/domain, courseid and symb
                   8017:     my $courseid;
1.359     albertel 8018:     my $publicuser;
1.427     www      8019:     if ($symbparm) {
                   8020: 	$symbparm=&get_symb_from_alias($symbparm);
                   8021:     }
1.218     albertel 8022:     if (!($uname && $udom)) {
1.790     albertel 8023:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8024:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8025:     } else {
1.620     albertel 8026: 	$courseid=$env{'request.course.id'};
1.218     albertel 8027:     }
1.48      www      8028:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8029:     my $rest;
1.320     albertel 8030:     if (defined($therest[0])) {
1.48      www      8031:        $rest=join('.',@therest);
                   8032:     } else {
                   8033:        $rest='';
                   8034:     }
1.320     albertel 8035: 
1.57      www      8036:     my $qualifierrest=$qualifier;
                   8037:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8038:     my $spacequalifierrest=$space;
                   8039:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8040:     if ($realm eq 'user') {
1.48      www      8041: # --------------------------------------------------------------- user.resource
                   8042: 	if ($space eq 'resource') {
1.651     albertel 8043: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8044: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8045: 		 &&
1.744     albertel 8046: 		 ($symbparm eq &symbread()) ) {	
                   8047: 		# if we are in the middle of processing the resource the
                   8048: 		# get the value we are planning on committing
                   8049:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8050:                     return $Apache::lonhomework::results{$qualifierrest};
                   8051:                 } else {
                   8052:                     return $Apache::lonhomework::history{$qualifierrest};
                   8053:                 }
1.335     albertel 8054: 	    } else {
1.359     albertel 8055: 		my %restored;
1.620     albertel 8056: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8057: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8058: 		} else {
                   8059: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8060: 		}
1.335     albertel 8061: 		return $restored{$qualifierrest};
                   8062: 	    }
1.48      www      8063: # ----------------------------------------------------------------- user.access
                   8064:         } elsif ($space eq 'access') {
1.218     albertel 8065: 	    # FIXME - not supporting calls for a specific user
1.48      www      8066:             return &allowed($qualifier,$rest);
                   8067: # ------------------------------------------ user.preferences, user.environment
                   8068:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8069: 	    if (($uname eq $env{'user.name'}) &&
                   8070: 		($udom eq $env{'user.domain'})) {
                   8071: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8072: 	    } else {
1.359     albertel 8073: 		my %returnhash;
                   8074: 		if (!$publicuser) {
                   8075: 		    %returnhash=&userenvironment($udom,$uname,
                   8076: 						 $qualifierrest);
                   8077: 		}
1.218     albertel 8078: 		return $returnhash{$qualifierrest};
                   8079: 	    }
1.48      www      8080: # ----------------------------------------------------------------- user.course
                   8081:         } elsif ($space eq 'course') {
1.218     albertel 8082: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8083:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8084: # ------------------------------------------------------------------- user.role
                   8085:         } elsif ($space eq 'role') {
1.218     albertel 8086: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8087:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8088:             if ($qualifier eq 'value') {
                   8089: 		return $role;
                   8090:             } elsif ($qualifier eq 'extent') {
                   8091:                 return $where;
                   8092:             }
                   8093: # ----------------------------------------------------------------- user.domain
                   8094:         } elsif ($space eq 'domain') {
1.218     albertel 8095:             return $udom;
1.48      www      8096: # ------------------------------------------------------------------- user.name
                   8097:         } elsif ($space eq 'name') {
1.218     albertel 8098:             return $uname;
1.48      www      8099: # ---------------------------------------------------- Any other user namespace
1.29      www      8100:         } else {
1.359     albertel 8101: 	    my %reply;
                   8102: 	    if (!$publicuser) {
                   8103: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8104: 	    }
                   8105: 	    return $reply{$qualifierrest};
1.48      www      8106:         }
1.236     www      8107:     } elsif ($realm eq 'query') {
                   8108: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8109:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8110: 						[$spacequalifierrest]);
1.620     albertel 8111: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8112:    } elsif ($realm eq 'request') {
1.48      www      8113: # ------------------------------------------------------------- request.browser
                   8114:         if ($space eq 'browser') {
1.430     www      8115: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8116: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8117: 		    return 1;
                   8118: 		} else {
                   8119: 		    return 0;
                   8120: 		}
                   8121: 	    } else {
1.620     albertel 8122: 		return $env{'browser.'.$qualifier};
1.430     www      8123: 	    }
1.57      www      8124: # ------------------------------------------------------------ request.filename
                   8125:         } else {
1.620     albertel 8126:             return $env{'request.'.$spacequalifierrest};
1.29      www      8127:         }
1.28      www      8128:     } elsif ($realm eq 'course') {
1.48      www      8129: # ---------------------------------------------------------- course.description
1.620     albertel 8130:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8131:     } elsif ($realm eq 'resource') {
1.165     www      8132: 
1.620     albertel 8133: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8134: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8135: 	}
1.693     albertel 8136: 
                   8137: 	if ($space eq 'title') {
                   8138: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8139: 	    return &gettitle($symbparm);
                   8140: 	}
                   8141: 	
                   8142: 	if ($space eq 'map') {
                   8143: 	    my ($map) = &decode_symb($symbparm);
                   8144: 	    return &symbread($map);
                   8145: 	}
1.905     albertel 8146: 	if ($space eq 'filename') {
                   8147: 	    if ($symbparm) {
                   8148: 		return &clutter((&decode_symb($symbparm))[2]);
                   8149: 	    }
                   8150: 	    return &hreflocation('',$env{'request.filename'});
                   8151: 	}
1.693     albertel 8152: 
                   8153: 	my ($section, $group, @groups);
1.593     albertel 8154: 	my ($courselevelm,$courselevel);
1.539     albertel 8155: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8156: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8157: 
1.218     albertel 8158: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8159: 
1.60      www      8160: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8161: 	    my $symbp=$symbparm;
1.735     albertel 8162: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8163: 
                   8164: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8165: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8166: 
1.620     albertel 8167: 	    if (($env{'user.name'} eq $uname) &&
                   8168: 		($env{'user.domain'} eq $udom)) {
                   8169: 		$section=$env{'request.course.sec'};
1.733     raeburn  8170:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8171:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8172: 	    } else {
1.539     albertel 8173: 		if (! defined($usection)) {
1.551     albertel 8174: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8175: 		} else {
                   8176: 		    $section = $usection;
                   8177: 		}
1.733     raeburn  8178:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8179: 	    }
                   8180: 
                   8181: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8182: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8183: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8184: 
1.593     albertel 8185: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8186: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8187: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8188: 
1.60      www      8189: # ----------------------------------------------------------- first, check user
1.624     albertel 8190: 
                   8191: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8192: 				       ([$courselevelr,'resource'],
                   8193: 					[$courselevelm,'map'     ],
                   8194: 					[$courselevel, 'course'  ]));
1.931     albertel 8195: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8196: 
1.594     albertel 8197: # ------------------------------------------------ second, check some of course
1.684     raeburn  8198:             my $coursereply;
1.691     raeburn  8199:             if (@groups > 0) {
                   8200:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8201:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8202:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8203:             }
1.96      www      8204: 
1.684     raeburn  8205: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8206: 				  $env{'course.'.$courseid.'.domain'},
                   8207: 				  'course',
                   8208: 				  ([$seclevelr,   'resource'],
                   8209: 				   [$seclevelm,   'map'     ],
                   8210: 				   [$seclevel,    'course'  ],
                   8211: 				   [$courselevelr,'resource']));
                   8212: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8213: 
1.60      www      8214: # ------------------------------------------------------ third, check map parms
1.218     albertel 8215: 	    my %parmhash=();
                   8216: 	    my $thisparm='';
                   8217: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8218: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8219: 		    &GDBM_READER(),0640)) {
1.218     albertel 8220: 		$thisparm=$parmhash{$symbparm};
                   8221: 		untie(%parmhash);
                   8222: 	    }
1.927     albertel 8223: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8224: 	}
1.594     albertel 8225: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8226: 
1.218     albertel 8227: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8228: 	my $filename;
                   8229: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8230: 	if ($symbparm) {
1.409     www      8231: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8232: 	} else {
1.620     albertel 8233: 	    $filename=$env{'request.filename'};
1.282     albertel 8234: 	}
                   8235: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8236: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8237: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8238: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8239: 
1.927     albertel 8240: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8241: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8242: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8243: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8244: 				     $env{'course.'.$courseid.'.domain'},
                   8245: 				     'course',
1.927     albertel 8246: 				     ([$courselevelm,'map'   ],
                   8247: 				      [$courselevel, 'course']));
                   8248: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8249: 	}
1.145     www      8250: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8251: 	unless ($space eq '0') {
1.336     albertel 8252: 	    my @parts=split(/_/,$space);
                   8253: 	    my $id=pop(@parts);
                   8254: 	    my $part=join('_',@parts);
                   8255: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8256: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8257: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8258: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8259: 	}
1.395     albertel 8260: 	if ($recurse) { return undef; }
                   8261: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8262: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8263: # ---------------------------------------------------- Any other user namespace
                   8264:     } elsif ($realm eq 'environment') {
                   8265: # ----------------------------------------------------------------- environment
1.620     albertel 8266: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8267: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8268: 	} else {
1.770     albertel 8269: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8270: 		return '';
                   8271: 	    }
1.219     albertel 8272: 	    my %returnhash=&userenvironment($udom,$uname,
                   8273: 					    $spacequalifierrest);
                   8274: 	    return $returnhash{$spacequalifierrest};
                   8275: 	}
1.28      www      8276:     } elsif ($realm eq 'system') {
1.48      www      8277: # ----------------------------------------------------------------- system.time
                   8278: 	if ($space eq 'time') {
                   8279: 	    return time;
                   8280:         }
1.696     albertel 8281:     } elsif ($realm eq 'server') {
                   8282: # ----------------------------------------------------------------- system.time
                   8283: 	if ($space eq 'name') {
                   8284: 	    return $ENV{'SERVER_NAME'};
                   8285:         }
1.28      www      8286:     }
1.48      www      8287:     return '';
1.61      www      8288: }
                   8289: 
1.927     albertel 8290: sub get_reply {
                   8291:     my ($reply_value) = @_;
1.940     raeburn  8292:     if (ref($reply_value) eq 'ARRAY') {
                   8293:         if (wantarray) {
                   8294: 	    return @$reply_value;
                   8295:         }
                   8296:         return $reply_value->[0];
                   8297:     } else {
                   8298:         return $reply_value;
1.927     albertel 8299:     }
                   8300: }
                   8301: 
1.691     raeburn  8302: sub check_group_parms {
                   8303:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8304:     my @groupitems = ();
                   8305:     my $resultitem;
1.927     albertel 8306:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8307:     foreach my $group (@{$groups}) {
                   8308:         foreach my $level (@levels) {
1.927     albertel 8309:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8310:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8311:         }
                   8312:     }
                   8313:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8314:                             $env{'course.'.$courseid.'.domain'},
                   8315:                                      'course',@groupitems);
                   8316:     return $coursereply;
                   8317: }
                   8318: 
                   8319: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8320:     my ($courseid,@groups) = @_;
                   8321:     @groups = sort(@groups);
1.691     raeburn  8322:     return @groups;
                   8323: }
                   8324: 
1.395     albertel 8325: sub packages_tab_default {
                   8326:     my ($uri,$varname)=@_;
                   8327:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8328: 
                   8329:     my (@extension,@specifics,$do_default);
                   8330:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8331: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8332: 	if ($pack_type eq 'default') {
                   8333: 	    $do_default=1;
                   8334: 	} elsif ($pack_type eq 'extension') {
                   8335: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8336: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8337: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8338: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8339: 	}
                   8340:     }
                   8341:     # first look for a package that matches the requested part id
                   8342:     foreach my $package (@specifics) {
                   8343: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8344: 	next if ($pack_part ne $part);
                   8345: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8346: 	    return $packagetab{"$pack_type&$name&default"};
                   8347: 	}
                   8348:     }
                   8349:     # look for any possible matching non extension_ package
                   8350:     foreach my $package (@specifics) {
                   8351: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8352: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8353: 	    return $packagetab{"$pack_type&$name&default"};
                   8354: 	}
1.585     albertel 8355: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8356: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8357: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8358: 	}
                   8359:     }
1.738     albertel 8360:     # look for any posible extension_ match
                   8361:     foreach my $package (@extension) {
                   8362: 	my ($package,$pack_type)=@{$package};
                   8363: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8364: 	    return $packagetab{"$pack_type&$name&default"};
                   8365: 	}
                   8366: 	if (defined($packagetab{$package."&$name&default"})) {
                   8367: 	    return $packagetab{$package."&$name&default"};
                   8368: 	}
                   8369:     }
                   8370:     # look for a global default setting
                   8371:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8372: 	return $packagetab{"default&$name&default"};
                   8373:     }
1.395     albertel 8374:     return undef;
                   8375: }
                   8376: 
1.334     albertel 8377: sub add_prefix_and_part {
                   8378:     my ($prefix,$part)=@_;
                   8379:     my $keyroot;
                   8380:     if (defined($prefix) && $prefix !~ /^__/) {
                   8381: 	# prefix that has a part already
                   8382: 	$keyroot=$prefix;
                   8383:     } elsif (defined($prefix)) {
                   8384: 	# prefix that is missing a part
                   8385: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8386:     } else {
                   8387: 	# no prefix at all
                   8388: 	if (defined($part)) { $keyroot='_'.$part; }
                   8389:     }
                   8390:     return $keyroot;
                   8391: }
                   8392: 
1.71      www      8393: # ---------------------------------------------------------------- Get metadata
                   8394: 
1.599     albertel 8395: my %metaentry;
1.1070    www      8396: my %importedpartids;
1.71      www      8397: sub metadata {
1.176     www      8398:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8399:     $uri=&declutter($uri);
1.288     albertel 8400:     # if it is a non metadata possible uri return quickly
1.529     albertel 8401:     if (($uri eq '') || 
                   8402: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8403: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8404:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8405: 	return undef;
                   8406:     }
                   8407:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8408: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8409: 	return undef;
1.288     albertel 8410:     }
1.73      www      8411:     my $filename=$uri;
                   8412:     $uri=~s/\.meta$//;
1.172     www      8413: #
                   8414: # Is the metadata already cached?
1.177     www      8415: # Look at timestamp of caching
1.172     www      8416: # Everything is cached by the main uri, libraries are never directly cached
                   8417: #
1.428     albertel 8418:     if (!defined($liburi)) {
1.599     albertel 8419: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8420: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8421:     }
                   8422:     {
1.1069    www      8423: # Imported parts would go here
1.1070    www      8424:         my %importedids=();
                   8425:         my @origfileimportpartids=();
1.1069    www      8426:         my $importedparts=0;
1.172     www      8427: #
                   8428: # Is this a recursive call for a library?
                   8429: #
1.599     albertel 8430: #	if (! exists($metacache{$uri})) {
                   8431: #	    $metacache{$uri}={};
                   8432: #	}
1.924     albertel 8433: 	my $cachetime = 60*60;
1.171     www      8434:         if ($liburi) {
                   8435: 	    $liburi=&declutter($liburi);
                   8436:             $filename=$liburi;
1.401     bowersj2 8437:         } else {
1.599     albertel 8438: 	    &devalidate_cache_new('meta',$uri);
                   8439: 	    undef(%metaentry);
1.401     bowersj2 8440: 	}
1.140     www      8441:         my %metathesekeys=();
1.73      www      8442:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8443: 	my $metastring;
1.924     albertel 8444: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8445: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8446: 	    $metastring = 
1.929     albertel 8447: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8448: 					  ('grade_target' => 'meta'));
                   8449: 	    $cachetime = 1; # only want this cached in the child not long term
                   8450: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8451: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8452: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8453: 	    $metastring=&getfile($file);
1.489     albertel 8454: 	}
1.208     albertel 8455:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8456:         my $token;
1.140     www      8457:         undef %metathesekeys;
1.71      www      8458:         while ($token=$parser->get_token) {
1.339     albertel 8459: 	    if ($token->[0] eq 'S') {
                   8460: 		if (defined($token->[2]->{'package'})) {
1.172     www      8461: #
                   8462: # This is a package - get package info
                   8463: #
1.339     albertel 8464: 		    my $package=$token->[2]->{'package'};
                   8465: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8466: 		    if (defined($token->[2]->{'id'})) { 
                   8467: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8468: 		    }
1.599     albertel 8469: 		    if ($metaentry{':packages'}) {
                   8470: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8471: 		    } else {
1.599     albertel 8472: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8473: 		    }
1.736     albertel 8474: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8475: 			my $part=$keyroot;
                   8476: 			$part=~s/^\_//;
1.736     albertel 8477: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8478: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8479: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8480: 			    # ignore package.tab specified default values
                   8481:                             # here &package_tab_default() will fetch those
                   8482: 			    if ($subp eq 'default') { next; }
1.736     albertel 8483: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8484: 			    my $unikey;
                   8485: 			    if ($pack =~ /_0$/) {
                   8486: 				$unikey='parameter_0_'.$name;
                   8487: 				$part=0;
                   8488: 			    } else {
                   8489: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8490: 			    }
1.339     albertel 8491: 			    if ($subp eq 'display') {
                   8492: 				$value.=' [Part: '.$part.']';
                   8493: 			    }
1.599     albertel 8494: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8495: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8496: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8497: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8498: 			    }
1.599     albertel 8499: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8500: 				$metaentry{':'.$unikey}=
                   8501: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8502: 			    }
1.339     albertel 8503: 			}
                   8504: 		    }
                   8505: 		} else {
1.172     www      8506: #
                   8507: # This is not a package - some other kind of start tag
1.339     albertel 8508: #
                   8509: 		    my $entry=$token->[1];
1.1068    www      8510: 		    my $unikey='';
1.175     www      8511: 
1.339     albertel 8512: 		    if ($entry eq 'import') {
1.175     www      8513: #
                   8514: # Importing a library here
1.339     albertel 8515: #
1.1067    www      8516:                         my $location=$parser->get_text('/import');
                   8517:                         my $dir=$filename;
                   8518:                         $dir=~s|[^/]*$||;
                   8519:                         $location=&filelocation($dir,$location);
1.1069    www      8520:                        
1.1068    www      8521:                         my $importmode=$token->[2]->{'importmode'};
                   8522:                         if ($importmode eq 'problem') {
1.1069    www      8523: # Import as problem/response
1.1068    www      8524:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8525:                         } elsif ($importmode eq 'part') {
                   8526: # Import as part(s)
1.1069    www      8527:                            $importedparts=1;
                   8528: # We need to get the original file and the imported file to get the part order correct
                   8529: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8530: # Load and inspect original file
1.1070    www      8531:                            if ($#origfileimportpartids<0) {
                   8532:                               undef(%importedpartids);
                   8533:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8534:                               my $origfile=&getfile($origfilelocation);
                   8535:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8536:                            }
                   8537: 
1.1069    www      8538: # Load and inspect imported file
                   8539:                            my $impfile=&getfile($location);
                   8540:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8541:                            if ($#impfilepartids>=0) {
                   8542: # This problem had parts
1.1070    www      8543:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8544:                            } else {
                   8545: # Importing by turning a single problem into a problem part
                   8546: # It gets the import-tags ID as part-ID
                   8547:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8548:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8549:                            }
1.1068    www      8550:                         } else {
                   8551: # Normal import
                   8552:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8553:                            if (defined($token->[2]->{'id'})) {
                   8554:                               $unikey.='_'.$token->[2]->{'id'};
                   8555:                            }
1.1067    www      8556:                         }
                   8557: 
1.339     albertel 8558: 			if ($depthcount<20) {
1.736     albertel 8559: 			    my $metadata = 
                   8560: 				&metadata($uri,'keys', $location,$unikey,
                   8561: 					  $depthcount+1);
                   8562: 			    foreach my $meta (split(',',$metadata)) {
                   8563: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8564: 				$metathesekeys{$meta}=1;
1.339     albertel 8565: 			    }
1.1068    www      8566: 			
                   8567:                         }
1.1067    www      8568: 		    } else {
                   8569: #
                   8570: # Not importing, some other kind of non-package, non-library start tag
                   8571: # 
                   8572:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8573:                         if (defined($token->[2]->{'id'})) {
                   8574:                             $unikey.='_'.$token->[2]->{'id'};
                   8575:                         }
1.339     albertel 8576: 			if (defined($token->[2]->{'name'})) { 
                   8577: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8578: 			}
                   8579: 			$metathesekeys{$unikey}=1;
1.736     albertel 8580: 			foreach my $param (@{$token->[3]}) {
                   8581: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8582: 				$token->[2]->{$param};
1.339     albertel 8583: 			}
                   8584: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8585: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8586: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8587: 		 # only ws inside the tag, and not in default, so use default
                   8588: 		 # as value
1.599     albertel 8589: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8590: 			} elsif ( $internaltext =~ /\S/ ) {
                   8591: 		  # something interesting inside the tag
                   8592: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8593: 			} else {
1.908     albertel 8594: 		  # no interesting values, don't set a default
1.339     albertel 8595: 			}
1.172     www      8596: # end of not-a-package not-a-library import
1.339     albertel 8597: 		    }
1.172     www      8598: # end of not-a-package start tag
1.339     albertel 8599: 		}
1.172     www      8600: # the next is the end of "start tag"
1.339     albertel 8601: 	    }
                   8602: 	}
1.483     albertel 8603: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8604: 	$extension = lc($extension);
                   8605: 	if ($extension eq 'htm') { $extension='html'; }
                   8606: 
1.737     albertel 8607: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8608: 	    #no specific packages #how's our extension
                   8609: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8610: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8611: 					 \%metathesekeys);
                   8612: 	}
1.883     albertel 8613: 
                   8614: 	if (!exists($metaentry{':packages'})
                   8615: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8616: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8617: 		#no specific packages well let's get default then
                   8618: 		if ($key!~/^default&/) { next; }
1.488     albertel 8619: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8620: 					     \%metathesekeys);
                   8621: 	    }
                   8622: 	}
1.338     www      8623: # are there custom rights to evaluate
1.599     albertel 8624: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8625: 
1.338     www      8626:     #
                   8627:     # Importing a rights file here
1.339     albertel 8628:     #
                   8629: 	    unless ($depthcount) {
1.599     albertel 8630: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8631: 		my $dir=$filename;
                   8632: 		$dir=~s|[^/]*$||;
                   8633: 		$location=&filelocation($dir,$location);
1.736     albertel 8634: 		my $rights_metadata =
                   8635: 		    &metadata($uri,'keys',$location,'_rights',
                   8636: 			      $depthcount+1);
                   8637: 		foreach my $rights (split(',',$rights_metadata)) {
                   8638: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8639: 		    $metathesekeys{$rights}=1;
1.339     albertel 8640: 		}
                   8641: 	    }
                   8642: 	}
1.737     albertel 8643: 	# uniqifiy package listing
                   8644: 	my %seen;
                   8645: 	my @uniq_packages =
                   8646: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8647: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8648: 
1.1070    www      8649:         if ($importedparts) {
                   8650: # We had imported parts and need to rebuild partorder
                   8651:            $metaentry{':partorder'}='';
                   8652:            $metathesekeys{'partorder'}=1;
                   8653:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8654:                if ($origfileimportpartids[$index] eq 'part') {
                   8655: # original part, part of the problem
                   8656:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8657:                } else {
                   8658: # we have imported parts at this position
                   8659:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8660:                }
                   8661:            }
                   8662:            $metaentry{':partorder'}=~s/^\,//;
                   8663:         }
                   8664: 
1.737     albertel 8665: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8666: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8667: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8668: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8669: # this is the end of "was not already recently cached
1.71      www      8670:     }
1.599     albertel 8671:     return $metaentry{':'.$what};
1.261     albertel 8672: }
                   8673: 
1.488     albertel 8674: sub metadata_create_package_def {
1.483     albertel 8675:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8676:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8677:     if ($subp eq 'default') { next; }
                   8678:     
1.599     albertel 8679:     if (defined($metaentry{':packages'})) {
                   8680: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8681:     } else {
1.599     albertel 8682: 	$metaentry{':packages'}=$package;
1.483     albertel 8683:     }
                   8684:     my $value=$packagetab{$key};
                   8685:     my $unikey;
                   8686:     $unikey='parameter_0_'.$name;
1.599     albertel 8687:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8688:     $$metathesekeys{$unikey}=1;
1.599     albertel 8689:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8690: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8691:     }
1.599     albertel 8692:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8693: 	$metaentry{':'.$unikey}=
                   8694: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8695:     }
                   8696: }
                   8697: 
1.261     albertel 8698: sub metadata_generate_part0 {
                   8699:     my ($metadata,$metacache,$uri) = @_;
                   8700:     my %allnames;
1.737     albertel 8701:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8702: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8703: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8704: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8705: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8706: 	    $allnames{$name}=$part;
                   8707: 	  }
                   8708: 	}
                   8709:     }
                   8710:     foreach my $name (keys(%allnames)) {
                   8711:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8712:       my $key=":parameter_0_$name";
1.261     albertel 8713:       $$metacache{"$key.part"}='0';
                   8714:       $$metacache{"$key.name"}=$name;
1.428     albertel 8715:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8716: 					   $allnames{$name}.'_'.$name.
                   8717: 					   '.type'};
1.428     albertel 8718:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8719: 			     '.display'};
1.644     www      8720:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8721:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8722:       $$metacache{"$key.display"}=$olddis;
                   8723:     }
1.71      www      8724: }
                   8725: 
1.764     albertel 8726: # ------------------------------------------------------ Devalidate title cache
                   8727: 
                   8728: sub devalidate_title_cache {
                   8729:     my ($url)=@_;
                   8730:     if (!$env{'request.course.id'}) { return; }
                   8731:     my $symb=&symbread($url);
                   8732:     if (!$symb) { return; }
                   8733:     my $key=$env{'request.course.id'}."\0".$symb;
                   8734:     &devalidate_cache_new('title',$key);
                   8735: }
                   8736: 
1.1014    droeschl 8737: # ------------------------------------------------- Get the title of a course
                   8738: 
                   8739: sub current_course_title {
                   8740:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8741: }
1.301     www      8742: # ------------------------------------------------- Get the title of a resource
                   8743: 
                   8744: sub gettitle {
                   8745:     my $urlsymb=shift;
                   8746:     my $symb=&symbread($urlsymb);
1.534     albertel 8747:     if ($symb) {
1.620     albertel 8748: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8749: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8750: 	if (defined($cached)) { 
                   8751: 	    return $result;
                   8752: 	}
1.534     albertel 8753: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8754: 	my $title='';
1.907     albertel 8755: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8756: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8757: 	} else {
                   8758: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8759: 		    &GDBM_READER(),0640)) {
                   8760: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8761: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8762: 		untie(%bighash);
                   8763: 	    }
1.534     albertel 8764: 	}
                   8765: 	$title=~s/\&colon\;/\:/gs;
                   8766: 	if ($title) {
1.599     albertel 8767: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8768: 	}
                   8769: 	$urlsymb=$url;
                   8770:     }
                   8771:     my $title=&metadata($urlsymb,'title');
                   8772:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8773:     return $title;
1.301     www      8774: }
1.613     albertel 8775: 
1.614     albertel 8776: sub get_slot {
                   8777:     my ($which,$cnum,$cdom)=@_;
                   8778:     if (!$cnum || !$cdom) {
1.790     albertel 8779: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8780: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8781: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8782:     }
1.703     albertel 8783:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8784:     my %slotinfo;
                   8785:     if (exists($remembered{$key})) {
                   8786: 	$slotinfo{$which} = $remembered{$key};
                   8787:     } else {
                   8788: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8789: 	&Apache::lonhomework::showhash(%slotinfo);
                   8790: 	my ($tmp)=keys(%slotinfo);
                   8791: 	if ($tmp=~/^error:/) { return (); }
                   8792: 	$remembered{$key} = $slotinfo{$which};
                   8793:     }
1.616     albertel 8794:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8795: 	return %{$slotinfo{$which}};
                   8796:     }
                   8797:     return $slotinfo{$which};
1.614     albertel 8798: }
1.31      www      8799: # ------------------------------------------------- Update symbolic store links
                   8800: 
                   8801: sub symblist {
                   8802:     my ($mapname,%newhash)=@_;
1.438     www      8803:     $mapname=&deversion(&declutter($mapname));
1.31      www      8804:     my %hash;
1.620     albertel 8805:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8806:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8807:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8808: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8809: 		next if ($url eq 'last_known'
                   8810: 			 && $env{'form.no_update_last_known'});
                   8811: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8812: 						    $newhash{$url}->[1],
                   8813: 						    $newhash{$url}->[0]);
1.191     harris41 8814:             }
1.31      www      8815:             if (untie(%hash)) {
                   8816: 		return 'ok';
                   8817:             }
                   8818:         }
                   8819:     }
                   8820:     return 'error';
1.212     www      8821: }
                   8822: 
                   8823: # --------------------------------------------------------------- Verify a symb
                   8824: 
                   8825: sub symbverify {
1.510     www      8826:     my ($symb,$thisurl)=@_;
                   8827:     my $thisfn=$thisurl;
1.439     www      8828:     $thisfn=&declutter($thisfn);
1.215     www      8829: # direct jump to resource in page or to a sequence - will construct own symbs
                   8830:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8831: # check URL part
1.409     www      8832:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8833: 
1.431     www      8834:     unless ($url eq $thisfn) { return 0; }
1.213     www      8835: 
1.216     www      8836:     $symb=&symbclean($symb);
1.510     www      8837:     $thisurl=&deversion($thisurl);
1.439     www      8838:     $thisfn=&deversion($thisfn);
1.213     www      8839: 
                   8840:     my %bighash;
                   8841:     my $okay=0;
1.431     www      8842: 
1.620     albertel 8843:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8844:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8845:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8846:             $thisurl =~ s/\?.+$//;
                   8847:         }
1.510     www      8848:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8849:         unless ($ids) { 
1.510     www      8850:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8851:         }
                   8852:         if ($ids) {
                   8853: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8854: 	    foreach my $id (split(/\,/,$ids)) {
                   8855: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8856:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8857:                    $symb =~ s/\?.+$//;
                   8858:                }
1.216     www      8859:                if (
                   8860:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8861:    eq $symb) { 
1.620     albertel 8862: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8863: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8864: 		       $okay=1; 
                   8865: 		   }
                   8866: 	       }
1.216     www      8867: 	   }
                   8868:         }
1.213     www      8869: 	untie(%bighash);
                   8870:     }
                   8871:     return $okay;
1.31      www      8872: }
                   8873: 
1.210     www      8874: # --------------------------------------------------------------- Clean-up symb
                   8875: 
                   8876: sub symbclean {
                   8877:     my $symb=shift;
1.568     albertel 8878:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8879: # remove version from map
                   8880:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8881: 
1.210     www      8882: # remove version from URL
                   8883:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8884: 
1.507     www      8885: # remove wrapper
                   8886: 
1.510     www      8887:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8888:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8889:     return $symb;
1.409     www      8890: }
                   8891: 
                   8892: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8893: 
                   8894: sub encode_symb {
                   8895:     my ($map,$resid,$url)=@_;
                   8896:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8897: }
1.409     www      8898: 
                   8899: sub decode_symb {
1.568     albertel 8900:     my $symb=shift;
                   8901:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8902:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8903:     return (&fixversion($map),$resid,&fixversion($url));
                   8904: }
                   8905: 
                   8906: sub fixversion {
                   8907:     my $fn=shift;
1.609     banghart 8908:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8909:     my %bighash;
                   8910:     my $uri=&clutter($fn);
1.620     albertel 8911:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8912: # is this cached?
1.599     albertel 8913:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8914:     if (defined($cached)) { return $result; }
                   8915: # unfortunately not cached, or expired
1.620     albertel 8916:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8917: 	    &GDBM_READER(),0640)) {
                   8918:  	if ($bighash{'version_'.$uri}) {
                   8919:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8920:  	    unless (($version eq 'mostrecent') || 
                   8921: 		    ($version==&getversion($uri))) {
1.440     www      8922:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8923:  	    }
                   8924:  	}
                   8925:  	untie %bighash;
1.413     www      8926:     }
1.599     albertel 8927:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8928: }
                   8929: 
                   8930: sub deversion {
                   8931:     my $url=shift;
                   8932:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8933:     return $url;
1.210     www      8934: }
                   8935: 
1.31      www      8936: # ------------------------------------------------------ Return symb list entry
                   8937: 
                   8938: sub symbread {
1.249     www      8939:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8940:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8941:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8942: # no filename provided? try from environment
1.44      www      8943:     unless ($thisfn) {
1.620     albertel 8944:         if ($env{'request.symb'}) {
                   8945: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8946: 	}
1.620     albertel 8947: 	$thisfn=$env{'request.filename'};
1.44      www      8948:     }
1.569     albertel 8949:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8950: # is that filename actually a symb? Verify, clean, and return
                   8951:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8952: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8953: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8954: 	}
1.242     www      8955:     }
1.44      www      8956:     $thisfn=declutter($thisfn);
1.31      www      8957:     my %hash;
1.37      www      8958:     my %bighash;
                   8959:     my $syval='';
1.620     albertel 8960:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8961:         my $targetfn = $thisfn;
1.609     banghart 8962:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8963:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8964:         }
1.687     albertel 8965: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8966: 	    $targetfn=$1;
                   8967: 	}
1.620     albertel 8968:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8969:                       &GDBM_READER(),0640)) {
1.481     raeburn  8970: 	    $syval=$hash{$targetfn};
1.37      www      8971:             untie(%hash);
                   8972:         }
                   8973: # ---------------------------------------------------------- There was an entry
                   8974:         if ($syval) {
1.601     albertel 8975: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8976: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8977: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8978: 		    #return $env{$cache_str}='';
1.601     albertel 8979: 		#}    
                   8980: 		#$syval.=$1;
                   8981: 	    #}
1.37      www      8982:         } else {
                   8983: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8984:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8985:                             &GDBM_READER(),0640)) {
1.37      www      8986: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8987:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8988:               unless ($ids) { 
                   8989:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8990:               }
                   8991:               unless ($ids) {
                   8992: # alias?
                   8993: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8994:               }
1.37      www      8995:               if ($ids) {
                   8996: # ------------------------------------------------------------------- Has ID(s)
                   8997:                  my @possibilities=split(/\,/,$ids);
1.39      www      8998:                  if ($#possibilities==0) {
                   8999: # ----------------------------------------------- There is only one possibility
1.37      www      9000: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9001: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9002: 						    $resid,$thisfn);
1.249     www      9003:                  } elsif (!$donotrecurse) {
1.39      www      9004: # ------------------------------------------ There is more than one possibility
                   9005:                      my $realpossible=0;
1.800     albertel 9006:                      foreach my $id (@possibilities) {
                   9007: 			 my $file=$bighash{'src_'.$id};
1.39      www      9008:                          if (&allowed('bre',$file)) {
1.800     albertel 9009:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9010:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9011: 				$realpossible++;
1.626     albertel 9012:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9013: 						    $resid,$thisfn);
1.39      www      9014:                             }
                   9015: 			 }
1.191     harris41 9016:                      }
1.39      www      9017: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9018:                  } else {
                   9019:                      $syval='';
1.37      www      9020:                  }
                   9021: 	      }
                   9022:               untie(%bighash)
1.481     raeburn  9023:            }
1.31      www      9024:         }
1.62      www      9025:         if ($syval) {
1.620     albertel 9026: 	    return $env{$cache_str}=$syval;
1.62      www      9027:         }
1.31      www      9028:     }
1.949     raeburn  9029:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9030:     return $env{$cache_str}='';
1.31      www      9031: }
                   9032: 
                   9033: # ---------------------------------------------------------- Return random seed
                   9034: 
1.32      www      9035: sub numval {
                   9036:     my $txt=shift;
                   9037:     $txt=~tr/A-J/0-9/;
                   9038:     $txt=~tr/a-j/0-9/;
                   9039:     $txt=~tr/K-T/0-9/;
                   9040:     $txt=~tr/k-t/0-9/;
                   9041:     $txt=~tr/U-Z/0-5/;
                   9042:     $txt=~tr/u-z/0-5/;
                   9043:     $txt=~s/\D//g;
1.564     albertel 9044:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9045:     return int($txt);
1.368     albertel 9046: }
                   9047: 
1.484     albertel 9048: sub numval2 {
                   9049:     my $txt=shift;
                   9050:     $txt=~tr/A-J/0-9/;
                   9051:     $txt=~tr/a-j/0-9/;
                   9052:     $txt=~tr/K-T/0-9/;
                   9053:     $txt=~tr/k-t/0-9/;
                   9054:     $txt=~tr/U-Z/0-5/;
                   9055:     $txt=~tr/u-z/0-5/;
                   9056:     $txt=~s/\D//g;
                   9057:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9058:     my $total;
                   9059:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9060:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9061:     return int($total);
                   9062: }
                   9063: 
1.575     albertel 9064: sub numval3 {
                   9065:     use integer;
                   9066:     my $txt=shift;
                   9067:     $txt=~tr/A-J/0-9/;
                   9068:     $txt=~tr/a-j/0-9/;
                   9069:     $txt=~tr/K-T/0-9/;
                   9070:     $txt=~tr/k-t/0-9/;
                   9071:     $txt=~tr/U-Z/0-5/;
                   9072:     $txt=~tr/u-z/0-5/;
                   9073:     $txt=~s/\D//g;
                   9074:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9075:     my $total;
                   9076:     foreach my $val (@txts) { $total+=$val; }
                   9077:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9078:     return $total;
                   9079: }
                   9080: 
1.675     albertel 9081: sub digest {
                   9082:     my ($data)=@_;
                   9083:     my $digest=&Digest::MD5::md5($data);
                   9084:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9085:     my ($e,$f);
                   9086:     {
                   9087:         use integer;
                   9088:         $e=($a+$b);
                   9089:         $f=($c+$d);
                   9090:         if ($_64bit) {
                   9091:             $e=(($e<<32)>>32);
                   9092:             $f=(($f<<32)>>32);
                   9093:         }
                   9094:     }
                   9095:     if (wantarray) {
                   9096: 	return ($e,$f);
                   9097:     } else {
                   9098: 	my $g;
                   9099: 	{
                   9100: 	    use integer;
                   9101: 	    $g=($e+$f);
                   9102: 	    if ($_64bit) {
                   9103: 		$g=(($g<<32)>>32);
                   9104: 	    }
                   9105: 	}
                   9106: 	return $g;
                   9107:     }
                   9108: }
                   9109: 
1.368     albertel 9110: sub latest_rnd_algorithm_id {
1.675     albertel 9111:     return '64bit5';
1.366     albertel 9112: }
1.32      www      9113: 
1.503     albertel 9114: sub get_rand_alg {
                   9115:     my ($courseid)=@_;
1.790     albertel 9116:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9117:     if ($courseid) {
1.620     albertel 9118: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9119:     }
                   9120:     return &latest_rnd_algorithm_id();
                   9121: }
                   9122: 
1.562     albertel 9123: sub validCODE {
                   9124:     my ($CODE)=@_;
                   9125:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9126:     return 0;
                   9127: }
                   9128: 
1.491     albertel 9129: sub getCODE {
1.620     albertel 9130:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9131:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9132: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9133: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9134: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9135:     }
                   9136:     return undef;
                   9137: }
                   9138: 
1.31      www      9139: sub rndseed {
1.155     albertel 9140:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9141:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9142:     if (!defined($symb)) {
1.366     albertel 9143: 	unless ($symb=$wsymb) { return time; }
                   9144:     }
                   9145:     if (!$courseid) { $courseid=$wcourseid; }
                   9146:     if (!$domain) { $domain=$wdomain; }
                   9147:     if (!$username) { $username=$wusername }
1.503     albertel 9148:     my $which=&get_rand_alg();
1.803     albertel 9149: 
1.491     albertel 9150:     if (defined(&getCODE())) {
1.675     albertel 9151: 	if ($which eq '64bit5') {
                   9152: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9153: 	} elsif ($which eq '64bit4') {
1.575     albertel 9154: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9155: 	} else {
                   9156: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9157: 	}
1.675     albertel 9158:     } elsif ($which eq '64bit5') {
                   9159: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9160:     } elsif ($which eq '64bit4') {
                   9161: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9162:     } elsif ($which eq '64bit3') {
                   9163: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9164:     } elsif ($which eq '64bit2') {
                   9165: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9166:     } elsif ($which eq '64bit') {
                   9167: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9168:     }
                   9169:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9170: }
                   9171: 
                   9172: sub rndseed_32bit {
                   9173:     my ($symb,$courseid,$domain,$username)=@_;
                   9174:     {
                   9175: 	use integer;
                   9176: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9177: 	my $symbseed=numval($symb) << 22;
                   9178: 	my $namechck=unpack("%32C*",$username) << 17;
                   9179: 	my $nameseed=numval($username) << 12;
                   9180: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9181: 	my $courseseed=unpack("%32C*",$courseid);
                   9182: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9183: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9184: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9185: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9186: 	return $num;
                   9187:     }
                   9188: }
                   9189: 
                   9190: sub rndseed_64bit {
                   9191:     my ($symb,$courseid,$domain,$username)=@_;
                   9192:     {
                   9193: 	use integer;
                   9194: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9195: 	my $symbseed=numval($symb) << 10;
                   9196: 	my $namechck=unpack("%32S*",$username);
                   9197: 	
                   9198: 	my $nameseed=numval($username) << 21;
                   9199: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9200: 	my $courseseed=unpack("%32S*",$courseid);
                   9201: 	
                   9202: 	my $num1=$symbchck+$symbseed+$namechck;
                   9203: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9204: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9205: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9206: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9207: 	return "$num1,$num2";
1.155     albertel 9208:     }
1.366     albertel 9209: }
                   9210: 
1.443     albertel 9211: sub rndseed_64bit2 {
                   9212:     my ($symb,$courseid,$domain,$username)=@_;
                   9213:     {
                   9214: 	use integer;
                   9215: 	# strings need to be an even # of cahracters long, it it is odd the
                   9216:         # last characters gets thrown away
                   9217: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9218: 	my $symbseed=numval($symb) << 10;
                   9219: 	my $namechck=unpack("%32S*",$username.' ');
                   9220: 	
                   9221: 	my $nameseed=numval($username) << 21;
1.501     albertel 9222: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9223: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9224: 	
                   9225: 	my $num1=$symbchck+$symbseed+$namechck;
                   9226: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9227: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9228: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9229: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9230: 	return "$num1,$num2";
                   9231:     }
                   9232: }
                   9233: 
                   9234: sub rndseed_64bit3 {
                   9235:     my ($symb,$courseid,$domain,$username)=@_;
                   9236:     {
                   9237: 	use integer;
                   9238: 	# strings need to be an even # of cahracters long, it it is odd the
                   9239:         # last characters gets thrown away
                   9240: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9241: 	my $symbseed=numval2($symb) << 10;
                   9242: 	my $namechck=unpack("%32S*",$username.' ');
                   9243: 	
                   9244: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9245: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9246: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9247: 	
                   9248: 	my $num1=$symbchck+$symbseed+$namechck;
                   9249: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9250: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9251: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9252: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9253: 	
1.503     albertel 9254: 	return "$num1:$num2";
1.443     albertel 9255:     }
                   9256: }
                   9257: 
1.575     albertel 9258: sub rndseed_64bit4 {
                   9259:     my ($symb,$courseid,$domain,$username)=@_;
                   9260:     {
                   9261: 	use integer;
                   9262: 	# strings need to be an even # of cahracters long, it it is odd the
                   9263:         # last characters gets thrown away
                   9264: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9265: 	my $symbseed=numval3($symb) << 10;
                   9266: 	my $namechck=unpack("%32S*",$username.' ');
                   9267: 	
                   9268: 	my $nameseed=numval3($username) << 21;
                   9269: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9270: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9271: 	
                   9272: 	my $num1=$symbchck+$symbseed+$namechck;
                   9273: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9274: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9275: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9276: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9277: 	
                   9278: 	return "$num1:$num2";
                   9279:     }
                   9280: }
                   9281: 
1.675     albertel 9282: sub rndseed_64bit5 {
                   9283:     my ($symb,$courseid,$domain,$username)=@_;
                   9284:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9285:     return "$num1:$num2";
                   9286: }
                   9287: 
1.366     albertel 9288: sub rndseed_CODE_64bit {
                   9289:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9290:     {
1.366     albertel 9291: 	use integer;
1.443     albertel 9292: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9293: 	my $symbseed=numval2($symb);
1.491     albertel 9294: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9295: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9296: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9297: 	my $num1=$symbseed+$CODEchck;
                   9298: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9299: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9300: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9301: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9302: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9303: 	return "$num1:$num2";
1.366     albertel 9304:     }
                   9305: }
                   9306: 
1.575     albertel 9307: sub rndseed_CODE_64bit4 {
                   9308:     my ($symb,$courseid,$domain,$username)=@_;
                   9309:     {
                   9310: 	use integer;
                   9311: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9312: 	my $symbseed=numval3($symb);
                   9313: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9314: 	my $CODEseed=numval3(&getCODE());
                   9315: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9316: 	my $num1=$symbseed+$CODEchck;
                   9317: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9318: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9319: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9320: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9321: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9322: 	return "$num1:$num2";
                   9323:     }
                   9324: }
                   9325: 
1.675     albertel 9326: sub rndseed_CODE_64bit5 {
                   9327:     my ($symb,$courseid,$domain,$username)=@_;
                   9328:     my $code = &getCODE();
                   9329:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9330:     return "$num1:$num2";
                   9331: }
                   9332: 
1.366     albertel 9333: sub setup_random_from_rndseed {
                   9334:     my ($rndseed)=@_;
1.503     albertel 9335:     if ($rndseed =~/([,:])/) {
                   9336: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9337: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9338:     } else {
                   9339: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9340:     }
1.36      albertel 9341: }
                   9342: 
1.474     albertel 9343: sub latest_receipt_algorithm_id {
1.835     albertel 9344:     return 'receipt3';
1.474     albertel 9345: }
                   9346: 
1.480     www      9347: sub recunique {
                   9348:     my $fucourseid=shift;
                   9349:     my $unique;
1.835     albertel 9350:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9351: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9352: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9353:     } else {
                   9354: 	$unique=$perlvar{'lonReceipt'};
                   9355:     }
                   9356:     return unpack("%32C*",$unique);
                   9357: }
                   9358: 
                   9359: sub recprefix {
                   9360:     my $fucourseid=shift;
                   9361:     my $prefix;
1.835     albertel 9362:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9363: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9364: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9365:     } else {
                   9366: 	$prefix=$perlvar{'lonHostID'};
                   9367:     }
                   9368:     return unpack("%32C*",$prefix);
                   9369: }
                   9370: 
1.76      www      9371: sub ireceipt {
1.474     albertel 9372:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9373: 
                   9374:     my $return =&recprefix($fucourseid).'-';
                   9375: 
                   9376:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9377: 	$env{'request.state'} eq 'construct') {
                   9378: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9379: 	return $return;
                   9380:     }
                   9381: 
1.76      www      9382:     my $cuname=unpack("%32C*",$funame);
                   9383:     my $cudom=unpack("%32C*",$fudom);
                   9384:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9385:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9386:     my $cunique=&recunique($fucourseid);
1.474     albertel 9387:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9388:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9389: 
1.790     albertel 9390: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9391: 			       
                   9392: 	$return.= ($cunique%$cuname+
                   9393: 		   $cunique%$cudom+
                   9394: 		   $cusymb%$cuname+
                   9395: 		   $cusymb%$cudom+
                   9396: 		   $cucourseid%$cuname+
                   9397: 		   $cucourseid%$cudom+
                   9398: 		   $cpart%$cuname+
                   9399: 		   $cpart%$cudom);
                   9400:     } else {
                   9401: 	$return.= ($cunique%$cuname+
                   9402: 		   $cunique%$cudom+
                   9403: 		   $cusymb%$cuname+
                   9404: 		   $cusymb%$cudom+
                   9405: 		   $cucourseid%$cuname+
                   9406: 		   $cucourseid%$cudom);
                   9407:     }
                   9408:     return $return;
1.76      www      9409: }
                   9410: 
                   9411: sub receipt {
1.474     albertel 9412:     my ($part)=@_;
1.790     albertel 9413:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9414:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9415: }
1.260     ng       9416: 
1.790     albertel 9417: sub whichuser {
                   9418:     my ($passedsymb)=@_;
                   9419:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9420:     if (defined($env{'form.grade_symb'})) {
                   9421: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9422: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9423: 	if (!$allowed &&
                   9424: 	    exists($env{'request.course.sec'}) &&
                   9425: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9426: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9427: 			      '/'.$env{'request.course.sec'});
                   9428: 	}
                   9429: 	if ($allowed) {
                   9430: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9431: 	    $courseid=$tmp_courseid;
                   9432: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9433: 	    ($name)=&get_env_multiple('form.grade_username');
                   9434: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9435: 	}
                   9436:     }
                   9437:     if (!$passedsymb) {
                   9438: 	$symb=&symbread();
                   9439:     } else {
                   9440: 	$symb=$passedsymb;
                   9441:     }
                   9442:     $courseid=$env{'request.course.id'};
                   9443:     $domain=$env{'user.domain'};
                   9444:     $name=$env{'user.name'};
                   9445:     if ($name eq 'public' && $domain eq 'public') {
                   9446: 	if (!defined($env{'form.username'})) {
                   9447: 	    $env{'form.username'}.=time.rand(10000000);
                   9448: 	}
                   9449: 	$name.=$env{'form.username'};
                   9450:     }
                   9451:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9452: 
                   9453: }
                   9454: 
1.36      albertel 9455: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9456: # returns either the contents of the file or 
                   9457: # -1 if the file doesn't exist
1.481     raeburn  9458: #
                   9459: # if the target is a file that was uploaded via DOCS, 
                   9460: # a check will be made to see if a current copy exists on the local server,
                   9461: # if it does this will be served, otherwise a copy will be retrieved from
                   9462: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9463: # the local server.   
1.472     albertel 9464: 
1.36      albertel 9465: sub getfile {
1.538     albertel 9466:     my ($file) = @_;
1.609     banghart 9467:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9468:     &repcopy($file);
                   9469:     return &readfile($file);
                   9470: }
                   9471: 
                   9472: sub repcopy_userfile {
                   9473:     my ($file)=@_;
1.609     banghart 9474:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9475:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9476:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9477: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9478:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9479:     if (-e "$file") {
1.828     www      9480: # we already have a local copy, check it out
1.538     albertel 9481: 	my @fileinfo = stat($file);
1.828     www      9482: 	my $rtncode;
                   9483: 	my $info;
1.538     albertel 9484: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9485: 	if ($lwpresp ne 'ok') {
1.828     www      9486: # there is no such file anymore, even though we had a local copy
1.482     albertel 9487: 	    if ($rtncode eq '404') {
1.538     albertel 9488: 		unlink($file);
1.482     albertel 9489: 	    }
                   9490: 	    return -1;
                   9491: 	}
                   9492: 	if ($info < $fileinfo[9]) {
1.828     www      9493: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9494: 	    return 'ok';
1.828     www      9495: 	} else {
                   9496: # the file is outdated, get rid of it
                   9497: 	    unlink($file);
1.482     albertel 9498: 	}
1.828     www      9499:     }
                   9500: # one way or the other, at this point, we don't have the file
                   9501: # construct the correct path for the file
                   9502:     my @parts = ($cdom,$cnum); 
                   9503:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9504: 	push @parts, split(/\//,$1);
                   9505:     }
                   9506:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9507:     foreach my $part (@parts) {
                   9508: 	$path .= '/'.$part;
                   9509: 	if (!-e $path) {
                   9510: 	    mkdir($path,0770);
1.482     albertel 9511: 	}
                   9512:     }
1.828     www      9513: # now the path exists for sure
                   9514: # get a user agent
                   9515:     my $ua=new LWP::UserAgent;
                   9516:     my $transferfile=$file.'.in.transfer';
                   9517: # FIXME: this should flock
                   9518:     if (-e $transferfile) { return 'ok'; }
                   9519:     my $request;
                   9520:     $uri=~s/^\///;
1.980     raeburn  9521:     my $homeserver = &homeserver($cnum,$cdom);
                   9522:     my $protocol = $protocol{$homeserver};
                   9523:     $protocol = 'http' if ($protocol ne 'https');
                   9524:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9525:     my $response=$ua->request($request,$transferfile);
                   9526: # did it work?
                   9527:     if ($response->is_error()) {
                   9528: 	unlink($transferfile);
                   9529: 	&logthis("Userfile repcopy failed for $uri");
                   9530: 	return -1;
                   9531:     }
                   9532: # worked, rename the transfer file
                   9533:     rename($transferfile,$file);
1.607     raeburn  9534:     return 'ok';
1.481     raeburn  9535: }
                   9536: 
1.517     albertel 9537: sub tokenwrapper {
                   9538:     my $uri=shift;
1.980     raeburn  9539:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9540:     $uri=~s|^/||;
1.620     albertel 9541:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9542:     my $token=$1;
1.552     albertel 9543:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9544:     if ($udom && $uname && $file) {
                   9545: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9546:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9547:         my $homeserver = &homeserver($uname,$udom);
                   9548:         my $protocol = $protocol{$homeserver};
                   9549:         $protocol = 'http' if ($protocol ne 'https');
                   9550:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9551:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9552:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9553:     } else {
                   9554:         return '/adm/notfound.html';
                   9555:     }
                   9556: }
                   9557: 
1.828     www      9558: # call with reqtype HEAD: get last modification time
                   9559: # call with reqtype GET: get the file contents
                   9560: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9561: #
1.481     raeburn  9562: sub getuploaded {
                   9563:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9564:     $uri=~s/^\///;
1.980     raeburn  9565:     my $homeserver = &homeserver($cnum,$cdom);
                   9566:     my $protocol = $protocol{$homeserver};
                   9567:     $protocol = 'http' if ($protocol ne 'https');
                   9568:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9569:     my $ua=new LWP::UserAgent;
                   9570:     my $request=new HTTP::Request($reqtype,$uri);
                   9571:     my $response=$ua->request($request);
                   9572:     $$rtncode = $response->code;
1.482     albertel 9573:     if (! $response->is_success()) {
                   9574: 	return 'failed';
                   9575:     }      
                   9576:     if ($reqtype eq 'HEAD') {
1.486     www      9577: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9578:     } elsif ($reqtype eq 'GET') {
                   9579: 	$$info = $response->content;
1.472     albertel 9580:     }
1.482     albertel 9581:     return 'ok';
1.36      albertel 9582: }
                   9583: 
1.481     raeburn  9584: sub readfile {
                   9585:     my $file = shift;
                   9586:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9587:     my $fh;
                   9588:     open($fh,"<$file");
                   9589:     my $a='';
1.800     albertel 9590:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9591:     return $a;
                   9592: }
                   9593: 
1.36      albertel 9594: sub filelocation {
1.590     banghart 9595:     my ($dir,$file) = @_;
                   9596:     my $location;
                   9597:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9598: 
                   9599:     if ($file =~ m-^/adm/-) {
                   9600: 	$file=~s-^/adm/wrapper/-/-;
                   9601: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9602:     }
1.882     albertel 9603: 
1.590     banghart 9604:     if ($file=~m:^/~:) { # is a contruction space reference
                   9605:         $location = $file;
                   9606:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9607:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9608: 	# is a correct contruction space reference
                   9609:         $location = $file;
1.956     raeburn  9610:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9611:         $location = $file;
1.609     banghart 9612:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9613:         my ($udom,$uname,$filename)=
1.811     albertel 9614:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9615:         my $home=&homeserver($uname,$udom);
                   9616:         my $is_me=0;
                   9617:         my @ids=&current_machine_ids();
                   9618:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9619:         if ($is_me) {
1.955     raeburn  9620:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9621:         } else {
                   9622:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9623:   	      $udom.'/'.$uname.'/'.$filename;
                   9624:         }
1.882     albertel 9625:     } elsif ($file =~ m-^/adm/-) {
                   9626: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9627:     } else {
                   9628:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9629:         $file=~s:^/res/:/:;
                   9630:         if ( !( $file =~ m:^/:) ) {
                   9631:             $location = $dir. '/'.$file;
                   9632:         } else {
                   9633:             $location = '/home/httpd/html/res'.$file;
                   9634:         }
1.59      albertel 9635:     }
1.590     banghart 9636:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9637:     while ($location=~m{/\.\./}) {
                   9638: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9639: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9640: 	} else {
                   9641: 	    $location=~ s{/\.\./}{/}g;
                   9642: 	}
                   9643:     } #remove dir/..
1.590     banghart 9644:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9645:     return $location;
1.46      www      9646: }
1.36      albertel 9647: 
1.46      www      9648: sub hreflocation {
                   9649:     my ($dir,$file)=@_;
1.980     raeburn  9650:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9651: 	$file=filelocation($dir,$file);
1.700     albertel 9652:     } elsif ($file=~m-^/adm/-) {
                   9653: 	$file=~s-^/adm/wrapper/-/-;
                   9654: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9655:     }
                   9656:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9657: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9658:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9659: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9660:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9661: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9662: 	    -/uploaded/$1/$2/-x;
1.46      www      9663:     }
1.913     albertel 9664:     if ($file=~ m{^/userfiles/}) {
                   9665: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9666:     }
1.462     albertel 9667:     return $file;
1.465     albertel 9668: }
                   9669: 
                   9670: sub current_machine_domains {
1.853     albertel 9671:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9672: }
                   9673: 
                   9674: sub machine_domains {
                   9675:     my ($hostname) = @_;
1.465     albertel 9676:     my @domains;
1.838     albertel 9677:     my %hostname = &all_hostnames();
1.465     albertel 9678:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9679: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9680: 	if ($hostname eq $name) {
1.844     albertel 9681: 	    push(@domains,&host_domain($id));
1.465     albertel 9682: 	}
                   9683:     }
                   9684:     return @domains;
                   9685: }
                   9686: 
                   9687: sub current_machine_ids {
1.853     albertel 9688:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9689: }
                   9690: 
                   9691: sub machine_ids {
                   9692:     my ($hostname) = @_;
                   9693:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9694:     my @ids;
1.888     albertel 9695:     my %name_to_host = &all_names();
1.889     albertel 9696:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9697: 	return @{ $name_to_host{$hostname} };
                   9698:     }
                   9699:     return;
1.31      www      9700: }
                   9701: 
1.824     raeburn  9702: sub additional_machine_domains {
                   9703:     my @domains;
                   9704:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9705:     while( my $line = <$fh>) {
                   9706:         $line =~ s/\s//g;
                   9707:         push(@domains,$line);
                   9708:     }
                   9709:     return @domains;
                   9710: }
                   9711: 
                   9712: sub default_login_domain {
                   9713:     my $domain = $perlvar{'lonDefDomain'};
                   9714:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9715:     foreach my $posdom (&current_machine_domains(),
                   9716:                         &additional_machine_domains()) {
                   9717:         if (lc($posdom) eq lc($testdomain)) {
                   9718:             $domain=$posdom;
                   9719:             last;
                   9720:         }
                   9721:     }
                   9722:     return $domain;
                   9723: }
                   9724: 
1.31      www      9725: # ------------------------------------------------------------- Declutters URLs
                   9726: 
                   9727: sub declutter {
                   9728:     my $thisfn=shift;
1.569     albertel 9729:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9730:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9731:     $thisfn=~s/^\///;
1.697     albertel 9732:     $thisfn=~s|^adm/wrapper/||;
                   9733:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9734:     $thisfn=~s/^res\///;
1.1032    raeburn  9735:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9736:         $thisfn=~s/\?.+$//;
                   9737:     }
1.268     www      9738:     return $thisfn;
                   9739: }
                   9740: 
                   9741: # ------------------------------------------------------------- Clutter up URLs
                   9742: 
                   9743: sub clutter {
                   9744:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9745:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9746: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9747:        $thisfn='/res'.$thisfn; 
                   9748:     }
1.1031    raeburn  9749:     if ($thisfn !~m|^/adm|) {
                   9750: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9751: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9752: 	} else {
                   9753: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9754: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9755: 	    if ($embstyle eq 'ssi'
                   9756: 		|| ($embstyle eq 'hdn')
                   9757: 		|| ($embstyle eq 'rat')
                   9758: 		|| ($embstyle eq 'prv')
                   9759: 		|| ($embstyle eq 'ign')) {
                   9760: 		#do nothing with these
                   9761: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9762: 		|| ($embstyle eq 'emb')
                   9763: 		|| ($embstyle eq 'wrp')) {
                   9764: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9765: 	    } elsif ($embstyle eq 'unk'
                   9766: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9767: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9768: 	    } else {
1.718     www      9769: #		&logthis("Got a blank emb style");
1.695     albertel 9770: 	    }
1.694     albertel 9771: 	}
                   9772:     }
1.31      www      9773:     return $thisfn;
1.12      www      9774: }
                   9775: 
1.787     albertel 9776: sub clutter_with_no_wrapper {
                   9777:     my $uri = &clutter(shift);
                   9778:     if ($uri =~ m-^/adm/-) {
                   9779: 	$uri =~ s-^/adm/wrapper/-/-;
                   9780: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9781:     }
                   9782:     return $uri;
                   9783: }
                   9784: 
1.557     albertel 9785: sub freeze_escape {
                   9786:     my ($value)=@_;
                   9787:     if (ref($value)) {
                   9788: 	$value=&nfreeze($value);
                   9789: 	return '__FROZEN__'.&escape($value);
                   9790:     }
                   9791:     return &escape($value);
                   9792: }
                   9793: 
1.11      www      9794: 
1.557     albertel 9795: sub thaw_unescape {
                   9796:     my ($value)=@_;
                   9797:     if ($value =~ /^__FROZEN__/) {
                   9798: 	substr($value,0,10,undef);
                   9799: 	$value=&unescape($value);
                   9800: 	return &thaw($value);
                   9801:     }
                   9802:     return &unescape($value);
                   9803: }
                   9804: 
1.436     albertel 9805: sub correct_line_ends {
                   9806:     my ($result)=@_;
                   9807:     $$result =~s/\r\n/\n/mg;
                   9808:     $$result =~s/\r/\n/mg;
1.415     albertel 9809: }
1.1       albertel 9810: # ================================================================ Main Program
                   9811: 
1.184     www      9812: sub goodbye {
1.204     albertel 9813:    &logthis("Starting Shut down");
1.443     albertel 9814: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9815:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9816: #converted
1.599     albertel 9817: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9818:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9819: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9820: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9821: #1.1 only
1.870     albertel 9822: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9823: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9824: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9825: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9826:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9827:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9828:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9829:    &flushcourselogs();
                   9830:    &logthis("Shutting down");
                   9831: }
                   9832: 
1.852     albertel 9833: sub get_dns {
1.869     albertel 9834:     my ($url,$func,$ignore_cache) = @_;
                   9835:     if (!$ignore_cache) {
                   9836: 	my ($content,$cached)=
                   9837: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9838: 	if ($cached) {
                   9839: 	    &$func($content);
                   9840: 	    return;
                   9841: 	}
                   9842:     }
                   9843: 
                   9844:     my %alldns;
1.852     albertel 9845:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9846:     foreach my $dns (<$config>) {
                   9847: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9848:         my $line = $1;
                   9849:         my ($host,$protocol) = split(/:/,$line);
                   9850:         if ($protocol ne 'https') {
                   9851:             $protocol = 'http';
                   9852:         }
                   9853: 	$alldns{$host} = $protocol;
1.869     albertel 9854:     }
                   9855:     while (%alldns) {
                   9856: 	my ($dns) = keys(%alldns);
1.852     albertel 9857: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9858: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9859: 	my $response=$ua->request($request);
1.979     raeburn  9860:         delete($alldns{$dns});
1.852     albertel 9861: 	next if ($response->is_error());
                   9862: 	my @content = split("\n",$response->content);
1.869     albertel 9863: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9864: 	&$func(\@content);
1.869     albertel 9865: 	return;
1.852     albertel 9866:     }
                   9867:     close($config);
1.871     albertel 9868:     my $which = (split('/',$url))[3];
                   9869:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9870:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9871:     my @content = <$config>;
                   9872:     &$func(\@content);
                   9873:     return;
1.852     albertel 9874: }
1.327     albertel 9875: # ------------------------------------------------------------ Read domain file
                   9876: {
1.852     albertel 9877:     my $loaded;
1.846     albertel 9878:     my %domain;
                   9879: 
1.852     albertel 9880:     sub parse_domain_tab {
                   9881: 	my ($lines) = @_;
                   9882: 	foreach my $line (@$lines) {
                   9883: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9884: 
1.846     albertel 9885: 	    chomp($line);
1.852     albertel 9886: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9887: 	    my %this_domain;
                   9888: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9889: 			       'lang_def', 'city', 'longi', 'lati',
                   9890: 			       'primary') {
                   9891: 		$this_domain{$field} = shift(@elements);
                   9892: 	    }
                   9893: 	    $domain{$name} = \%this_domain;
1.852     albertel 9894: 	}
                   9895:     }
1.864     albertel 9896: 
                   9897:     sub reset_domain_info {
                   9898: 	undef($loaded);
                   9899: 	undef(%domain);
                   9900:     }
                   9901: 
1.852     albertel 9902:     sub load_domain_tab {
1.869     albertel 9903: 	my ($ignore_cache) = @_;
                   9904: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9905: 	my $fh;
                   9906: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9907: 	    my @lines = <$fh>;
                   9908: 	    &parse_domain_tab(\@lines);
1.448     albertel 9909: 	}
1.852     albertel 9910: 	close($fh);
                   9911: 	$loaded = 1;
1.327     albertel 9912:     }
1.846     albertel 9913: 
                   9914:     sub domain {
1.852     albertel 9915: 	&load_domain_tab() if (!$loaded);
                   9916: 
1.846     albertel 9917: 	my ($name,$what) = @_;
                   9918: 	return if ( !exists($domain{$name}) );
                   9919: 
                   9920: 	if (!$what) {
                   9921: 	    return $domain{$name}{'description'};
                   9922: 	}
                   9923: 	return $domain{$name}{$what};
                   9924:     }
1.974     raeburn  9925: 
                   9926:     sub domain_info {
                   9927:         &load_domain_tab() if (!$loaded);
                   9928:         return %domain;
                   9929:     }
                   9930: 
1.327     albertel 9931: }
                   9932: 
                   9933: 
1.1       albertel 9934: # ------------------------------------------------------------- Read hosts file
                   9935: {
1.838     albertel 9936:     my %hostname;
1.844     albertel 9937:     my %hostdom;
1.845     albertel 9938:     my %libserv;
1.852     albertel 9939:     my $loaded;
1.888     albertel 9940:     my %name_to_host;
1.1074    raeburn  9941:     my %internetdom;
1.852     albertel 9942: 
                   9943:     sub parse_hosts_tab {
                   9944: 	my ($file) = @_;
                   9945: 	foreach my $configline (@$file) {
                   9946: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9947: 	    next if ($configline =~ /^\^/);
                   9948: 	    chomp($configline);
1.1074    raeburn  9949: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 9950: 	    $name=~s/\s//g;
                   9951: 	    if ($id && $domain && $role && $name) {
                   9952: 		$hostname{$id}=$name;
1.888     albertel 9953: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9954: 		$hostdom{$id}=$domain;
                   9955: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9956:                 if (defined($protocol)) {
                   9957:                     if ($protocol eq 'https') {
                   9958:                         $protocol{$id} = $protocol;
                   9959:                     } else {
                   9960:                         $protocol{$id} = 'http'; 
                   9961:                     }
1.968     raeburn  9962:                 } else {
1.969     raeburn  9963:                     $protocol{$id} = 'http';
1.968     raeburn  9964:                 }
1.1074    raeburn  9965:                 if (defined($intdom)) {
                   9966:                     $internetdom{$id} = $intdom;
                   9967:                 }
1.852     albertel 9968: 	    }
                   9969: 	}
                   9970:     }
1.864     albertel 9971:     
                   9972:     sub reset_hosts_info {
1.897     albertel 9973: 	&purge_remembered();
1.864     albertel 9974: 	&reset_domain_info();
                   9975: 	&reset_hosts_ip_info();
1.892     albertel 9976: 	undef(%name_to_host);
1.864     albertel 9977: 	undef(%hostname);
                   9978: 	undef(%hostdom);
                   9979: 	undef(%libserv);
                   9980: 	undef($loaded);
                   9981:     }
1.1       albertel 9982: 
1.852     albertel 9983:     sub load_hosts_tab {
1.869     albertel 9984: 	my ($ignore_cache) = @_;
                   9985: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9986: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9987: 	my @config = <$config>;
                   9988: 	&parse_hosts_tab(\@config);
                   9989: 	close($config);
                   9990: 	$loaded=1;
1.1       albertel 9991:     }
1.852     albertel 9992: 
1.838     albertel 9993:     sub hostname {
1.852     albertel 9994: 	&load_hosts_tab() if (!$loaded);
                   9995: 
1.838     albertel 9996: 	my ($lonid) = @_;
                   9997: 	return $hostname{$lonid};
                   9998:     }
1.845     albertel 9999: 
1.838     albertel 10000:     sub all_hostnames {
1.852     albertel 10001: 	&load_hosts_tab() if (!$loaded);
                   10002: 
1.838     albertel 10003: 	return %hostname;
                   10004:     }
1.845     albertel 10005: 
1.888     albertel 10006:     sub all_names {
                   10007: 	&load_hosts_tab() if (!$loaded);
                   10008: 
                   10009: 	return %name_to_host;
                   10010:     }
                   10011: 
1.974     raeburn  10012:     sub all_host_domain {
                   10013:         &load_hosts_tab() if (!$loaded);
                   10014:         return %hostdom;
                   10015:     }
                   10016: 
1.845     albertel 10017:     sub is_library {
1.852     albertel 10018: 	&load_hosts_tab() if (!$loaded);
                   10019: 
1.845     albertel 10020: 	return exists($libserv{$_[0]});
                   10021:     }
                   10022: 
                   10023:     sub all_library {
1.852     albertel 10024: 	&load_hosts_tab() if (!$loaded);
                   10025: 
1.845     albertel 10026: 	return %libserv;
                   10027:     }
                   10028: 
1.1062    droeschl 10029:     sub unique_library {
                   10030: 	#2x reverse removes all hostnames that appear more than once
                   10031:         my %unique = reverse &all_library();
                   10032:         return reverse %unique;
                   10033:     }
                   10034: 
1.841     albertel 10035:     sub get_servers {
1.852     albertel 10036: 	&load_hosts_tab() if (!$loaded);
                   10037: 
1.841     albertel 10038: 	my ($domain,$type) = @_;
                   10039: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10040: 	                                          : %hostname;
                   10041: 	my %result;
1.842     albertel 10042: 	if (ref($domain) eq 'ARRAY') {
                   10043: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10044: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10045: 		    $result{$host} = $hostname;
                   10046: 		}
                   10047: 	    }
                   10048: 	} else {
                   10049: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10050: 		if ($hostdom{$host} eq $domain) {
                   10051: 		    $result{$host} = $hostname;
                   10052: 		}
1.841     albertel 10053: 	    }
                   10054: 	}
                   10055: 	return %result;
                   10056:     }
1.845     albertel 10057: 
1.1062    droeschl 10058:     sub get_unique_servers {
                   10059:         my %unique = reverse &get_servers(@_);
                   10060: 	return reverse %unique;
                   10061:     }
                   10062: 
1.844     albertel 10063:     sub host_domain {
1.852     albertel 10064: 	&load_hosts_tab() if (!$loaded);
                   10065: 
1.844     albertel 10066: 	my ($lonid) = @_;
                   10067: 	return $hostdom{$lonid};
                   10068:     }
                   10069: 
1.841     albertel 10070:     sub all_domains {
1.852     albertel 10071: 	&load_hosts_tab() if (!$loaded);
                   10072: 
1.841     albertel 10073: 	my %seen;
                   10074: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10075: 	return @uniq;
                   10076:     }
1.1074    raeburn  10077: 
                   10078:     sub internet_dom {
                   10079:         &load_hosts_tab() if (!$loaded);
                   10080: 
                   10081:         my ($lonid) = @_;
                   10082:         return $internetdom{$lonid};
                   10083:     }
1.1       albertel 10084: }
                   10085: 
1.847     albertel 10086: { 
                   10087:     my %iphost;
1.856     albertel 10088:     my %name_to_ip;
                   10089:     my %lonid_to_ip;
1.869     albertel 10090: 
1.847     albertel 10091:     sub get_hosts_from_ip {
                   10092: 	my ($ip) = @_;
                   10093: 	my %iphosts = &get_iphost();
                   10094: 	if (ref($iphosts{$ip})) {
                   10095: 	    return @{$iphosts{$ip}};
                   10096: 	}
                   10097: 	return;
1.839     albertel 10098:     }
1.864     albertel 10099:     
                   10100:     sub reset_hosts_ip_info {
                   10101: 	undef(%iphost);
                   10102: 	undef(%name_to_ip);
                   10103: 	undef(%lonid_to_ip);
                   10104:     }
1.856     albertel 10105: 
                   10106:     sub get_host_ip {
                   10107: 	my ($lonid) = @_;
                   10108: 	if (exists($lonid_to_ip{$lonid})) {
                   10109: 	    return $lonid_to_ip{$lonid};
                   10110: 	}
                   10111: 	my $name=&hostname($lonid);
                   10112:    	my $ip = gethostbyname($name);
                   10113: 	return if (!$ip || length($ip) ne 4);
                   10114: 	$ip=inet_ntoa($ip);
                   10115: 	$name_to_ip{$name}   = $ip;
                   10116: 	$lonid_to_ip{$lonid} = $ip;
                   10117: 	return $ip;
                   10118:     }
1.847     albertel 10119:     
                   10120:     sub get_iphost {
1.869     albertel 10121: 	my ($ignore_cache) = @_;
1.894     albertel 10122: 
1.869     albertel 10123: 	if (!$ignore_cache) {
                   10124: 	    if (%iphost) {
                   10125: 		return %iphost;
                   10126: 	    }
                   10127: 	    my ($ip_info,$cached)=
                   10128: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10129: 	    if ($cached) {
                   10130: 		%iphost      = %{$ip_info->[0]};
                   10131: 		%name_to_ip  = %{$ip_info->[1]};
                   10132: 		%lonid_to_ip = %{$ip_info->[2]};
                   10133: 		return %iphost;
                   10134: 	    }
                   10135: 	}
1.894     albertel 10136: 
                   10137: 	# get yesterday's info for fallback
                   10138: 	my %old_name_to_ip;
                   10139: 	my ($ip_info,$cached)=
                   10140: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10141: 	if ($cached) {
                   10142: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10143: 	}
                   10144: 
1.888     albertel 10145: 	my %name_to_host = &all_names();
                   10146: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10147: 	    my $ip;
                   10148: 	    if (!exists($name_to_ip{$name})) {
                   10149: 		$ip = gethostbyname($name);
                   10150: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10151: 		    if (defined($old_name_to_ip{$name})) {
                   10152: 			$ip = $old_name_to_ip{$name};
                   10153: 			&logthis("Can't find $name defaulting to old $ip");
                   10154: 		    } else {
                   10155: 			&logthis("Name $name no IP found");
                   10156: 			next;
                   10157: 		    }
                   10158: 		} else {
                   10159: 		    $ip=inet_ntoa($ip);
1.847     albertel 10160: 		}
                   10161: 		$name_to_ip{$name} = $ip;
                   10162: 	    } else {
                   10163: 		$ip = $name_to_ip{$name};
1.653     albertel 10164: 	    }
1.888     albertel 10165: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10166: 		$lonid_to_ip{$id} = $ip;
                   10167: 	    }
                   10168: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10169: 	}
1.869     albertel 10170: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10171: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10172: 				      48*60*60);
1.869     albertel 10173: 
1.847     albertel 10174: 	return %iphost;
1.598     albertel 10175:     }
                   10176: 
1.992     raeburn  10177:     #
                   10178:     #  Given a DNS returns the loncapa host name for that DNS 
                   10179:     # 
                   10180:     sub host_from_dns {
                   10181:         my ($dns) = @_;
                   10182:         my @hosts;
                   10183:         my $ip;
                   10184: 
1.993     raeburn  10185:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10186:             $ip = $name_to_ip{$dns};
                   10187:         }
                   10188:         if (!$ip) {
                   10189:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10190:             if (length($ip) == 4) { 
                   10191: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10192:             }
                   10193:         }
                   10194:         if ($ip) {
                   10195: 	    @hosts = get_hosts_from_ip($ip);
                   10196: 	    return $hosts[0];
                   10197:         }
                   10198:         return undef;
1.986     foxr     10199:     }
1.992     raeburn  10200: 
1.1074    raeburn  10201:     sub get_internet_names {
                   10202:         my ($lonid) = @_;
                   10203:         return if ($lonid eq '');
                   10204:         my ($idnref,$cached)=
                   10205:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10206:         if ($cached) {
                   10207:             return $idnref;
                   10208:         }
                   10209:         my $ip = &get_host_ip($lonid);
                   10210:         my @hosts = &get_hosts_from_ip($ip);
                   10211:         my %iphost = &get_iphost();
                   10212:         my (@idns,%seen);
                   10213:         foreach my $id (@hosts) {
                   10214:             my $dom = &host_domain($id);
                   10215:             my $prim_id = &domain($dom,'primary');
                   10216:             my $prim_ip = &get_host_ip($prim_id);
                   10217:             next if ($seen{$prim_ip});
                   10218:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10219:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10220:                     my $intdom = &internet_dom($id);
                   10221:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10222:                         push(@idns,$intdom);
                   10223:                     }
                   10224:                 }
                   10225:             }
                   10226:             $seen{$prim_ip} = 1;
                   10227:         }
                   10228:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10229:     }
                   10230: 
1.986     foxr     10231: }
                   10232: 
1.1079    raeburn  10233: sub all_loncaparevs {
                   10234:     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);
                   10235: }
                   10236: 
1.862     albertel 10237: BEGIN {
                   10238: 
                   10239: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10240:     unless ($readit) {
                   10241: {
                   10242:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10243:     %perlvar = (%perlvar,%{$configvars});
                   10244: }
                   10245: 
                   10246: 
1.1       albertel 10247: # ------------------------------------------------------ Read spare server file
                   10248: {
1.448     albertel 10249:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10250: 
                   10251:     while (my $configline=<$config>) {
                   10252:        chomp($configline);
1.284     matthew  10253:        if ($configline) {
1.784     albertel 10254: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10255: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10256: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10257:        }
                   10258:     }
1.448     albertel 10259:     close($config);
1.1       albertel 10260: }
1.11      www      10261: # ------------------------------------------------------------ Read permissions
                   10262: {
1.448     albertel 10263:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10264: 
                   10265:     while (my $configline=<$config>) {
1.448     albertel 10266: 	chomp($configline);
                   10267: 	if ($configline) {
                   10268: 	    my ($role,$perm)=split(/ /,$configline);
                   10269: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10270: 	}
1.11      www      10271:     }
1.448     albertel 10272:     close($config);
1.11      www      10273: }
                   10274: 
                   10275: # -------------------------------------------- Read plain texts for permissions
                   10276: {
1.448     albertel 10277:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10278: 
                   10279:     while (my $configline=<$config>) {
1.448     albertel 10280: 	chomp($configline);
                   10281: 	if ($configline) {
1.742     raeburn  10282: 	    my ($short,@plain)=split(/:/,$configline);
                   10283:             %{$prp{$short}} = ();
                   10284: 	    if (@plain > 0) {
                   10285:                 $prp{$short}{'std'} = $plain[0];
                   10286:                 for (my $i=1; $i<@plain; $i++) {
                   10287:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10288:                 }
                   10289:             }
1.448     albertel 10290: 	}
1.135     www      10291:     }
1.448     albertel 10292:     close($config);
1.135     www      10293: }
                   10294: 
                   10295: # ---------------------------------------------------------- Read package table
                   10296: {
1.448     albertel 10297:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10298: 
                   10299:     while (my $configline=<$config>) {
1.483     albertel 10300: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10301: 	chomp($configline);
                   10302: 	my ($short,$plain)=split(/:/,$configline);
                   10303: 	my ($pack,$name)=split(/\&/,$short);
                   10304: 	if ($plain ne '') {
                   10305: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10306: 	    $packagetab{$short}=$plain; 
                   10307: 	}
1.11      www      10308:     }
1.448     albertel 10309:     close($config);
1.329     matthew  10310: }
                   10311: 
1.1073    raeburn  10312: # ---------------------------------------------------------- Read loncaparev table
                   10313: {
                   10314:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10315:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10316:             while (my $configline=<$config>) {
                   10317:                 chomp($configline);
                   10318:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10319:                 $loncaparevs{$hostid}=$loncaparev;
                   10320:             }
                   10321:             close($config);
                   10322:         }
                   10323:     }
                   10324: }
                   10325: 
1.1074    raeburn  10326: # ---------------------------------------------------------- Read serverhostID table
                   10327: {
                   10328:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10329:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10330:             while (my $configline=<$config>) {
                   10331:                 chomp($configline);
                   10332:                 my ($name,$id)=split(/:/,$configline);
                   10333:                 $serverhomeIDs{$name}=$id;
                   10334:             }
                   10335:             close($config);
                   10336:         }
                   10337:     }
                   10338: }
                   10339: 
1.1079    raeburn  10340: {
                   10341:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10342:     if (-e $file) {
                   10343:         my $parser = HTML::LCParser->new($file);
                   10344:         while (my $token = $parser->get_token()) {
                   10345:             if ($token->[0] eq 'S') {
                   10346:                 my $item = $token->[1];
                   10347:                 my $name = $token->[2]{'name'};
                   10348:                 my $value = $token->[2]{'value'};
                   10349:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10350:                     my $release = $parser->get_text();
                   10351:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10352:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10353:                 }
                   10354:             }
                   10355:         }
                   10356:     }
1.1073    raeburn  10357: }
                   10358: 
1.329     matthew  10359: # ------------- set up temporary directory
                   10360: {
                   10361:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10362: 
1.11      www      10363: }
                   10364: 
1.794     albertel 10365: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10366: 				'compress_threshold'=> 20_000,
                   10367:  			        });
1.185     www      10368: 
1.281     www      10369: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10370: $dumpcount=0;
1.958     www      10371: $locknum=0;
1.22      www      10372: 
1.163     harris41 10373: &logtouch();
1.672     albertel 10374: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10375: $readit=1;
1.564     albertel 10376:     {
                   10377: 	use integer;
                   10378: 	my $test=(2**32)+1;
1.568     albertel 10379: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10380: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10381:     }
1.195     www      10382: }
1.1       albertel 10383: }
1.179     www      10384: 
1.1       albertel 10385: 1;
1.191     harris41 10386: __END__
                   10387: 
1.243     albertel 10388: =pod
                   10389: 
1.191     harris41 10390: =head1 NAME
                   10391: 
1.243     albertel 10392: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10393: 
                   10394: =head1 SYNOPSIS
                   10395: 
1.243     albertel 10396: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10397: 
                   10398:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10399: 
1.243     albertel 10400: Common parameters:
                   10401: 
                   10402: =over 4
                   10403: 
                   10404: =item *
                   10405: 
                   10406: $uname : an internal username (if $cname expecting a course Id specifically)
                   10407: 
                   10408: =item *
                   10409: 
                   10410: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10411: 
                   10412: =item *
                   10413: 
                   10414: $symb : a resource instance identifier
                   10415: 
                   10416: =item *
                   10417: 
                   10418: $namespace : the name of a .db file that contains the data needed or
                   10419: being set.
                   10420: 
                   10421: =back
                   10422: 
1.394     bowersj2 10423: =head1 OVERVIEW
1.191     harris41 10424: 
1.394     bowersj2 10425: lonnet provides subroutines which interact with the
                   10426: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10427: about classes, users, and resources.
1.243     albertel 10428: 
                   10429: For many of these objects you can also use this to store data about
                   10430: them or modify them in various ways.
1.191     harris41 10431: 
1.394     bowersj2 10432: =head2 Symbs
1.191     harris41 10433: 
1.394     bowersj2 10434: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10435: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10436: map, the resource number of the resource in the map, and the URL of
                   10437: the resource itself. The latter is somewhat redundant, but might help
                   10438: if maps change.
                   10439: 
                   10440: An example is
                   10441: 
                   10442:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10443: 
                   10444: The respective map entry is
                   10445: 
                   10446:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10447:   title="Problem 2">
                   10448:  </resource>
                   10449: 
                   10450: Symbs are used by the random number generator, as well as to store and
                   10451: restore data specific to a certain instance of for example a problem.
                   10452: 
                   10453: =head2 Storing And Retrieving Data
                   10454: 
                   10455: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10456: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10457: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10458: is is the non-critical message twin of cstore. These functions are for
                   10459: handlers to store a perl hash to a user's permanent data space in an
                   10460: easy manner, and to retrieve it again on another call. It is expected
                   10461: that a handler would use this once at the beginning to retrieve data,
                   10462: and then again once at the end to send only the new data back.
                   10463: 
                   10464: The data is stored in the user's data directory on the user's
                   10465: homeserver under the ID of the course.
                   10466: 
                   10467: The hash that is returned by restore will have all of the previous
                   10468: value for all of the elements of the hash.
                   10469: 
                   10470: Example:
                   10471: 
                   10472:  #creating a hash
                   10473:  my %hash;
                   10474:  $hash{'foo'}='bar';
                   10475: 
                   10476:  #storing it
                   10477:  &Apache::lonnet::cstore(\%hash);
                   10478: 
                   10479:  #changing a value
                   10480:  $hash{'foo'}='notbar';
                   10481: 
                   10482:  #adding a new value
                   10483:  $hash{'bar'}='foo';
                   10484:  &Apache::lonnet::cstore(\%hash);
                   10485: 
                   10486:  #retrieving the hash
                   10487:  my %history=&Apache::lonnet::restore();
                   10488: 
                   10489:  #print the hash
                   10490:  foreach my $key (sort(keys(%history))) {
                   10491:    print("\%history{$key} = $history{$key}");
                   10492:  }
                   10493: 
                   10494: Will print out:
1.191     harris41 10495: 
1.394     bowersj2 10496:  %history{1:foo} = bar
                   10497:  %history{1:keys} = foo:timestamp
                   10498:  %history{1:timestamp} = 990455579
                   10499:  %history{2:bar} = foo
                   10500:  %history{2:foo} = notbar
                   10501:  %history{2:keys} = foo:bar:timestamp
                   10502:  %history{2:timestamp} = 990455580
                   10503:  %history{bar} = foo
                   10504:  %history{foo} = notbar
                   10505:  %history{timestamp} = 990455580
                   10506:  %history{version} = 2
                   10507: 
                   10508: Note that the special hash entries C<keys>, C<version> and
                   10509: C<timestamp> were added to the hash. C<version> will be equal to the
                   10510: total number of versions of the data that have been stored. The
                   10511: C<timestamp> attribute will be the UNIX time the hash was
                   10512: stored. C<keys> is available in every historical section to list which
                   10513: keys were added or changed at a specific historical revision of a
                   10514: hash.
                   10515: 
                   10516: B<Warning>: do not store the hash that restore returns directly. This
                   10517: will cause a mess since it will restore the historical keys as if the
                   10518: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10519: 
1.394     bowersj2 10520: Calling convention:
1.191     harris41 10521: 
1.394     bowersj2 10522:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10523:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10524: 
1.394     bowersj2 10525: For more detailed information, see lonnet specific documentation.
1.191     harris41 10526: 
1.394     bowersj2 10527: =head1 RETURN MESSAGES
1.191     harris41 10528: 
1.394     bowersj2 10529: =over 4
1.191     harris41 10530: 
1.394     bowersj2 10531: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10532: 
1.394     bowersj2 10533: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10534: when the connection is brought back up
1.191     harris41 10535: 
1.394     bowersj2 10536: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10537: for later delivery
1.191     harris41 10538: 
1.967     bisitz   10539: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10540: 
1.394     bowersj2 10541: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10542: that was requested
1.191     harris41 10543: 
1.243     albertel 10544: =back
1.191     harris41 10545: 
1.243     albertel 10546: =head1 PUBLIC SUBROUTINES
1.191     harris41 10547: 
1.243     albertel 10548: =head2 Session Environment Functions
1.191     harris41 10549: 
1.243     albertel 10550: =over 4
1.191     harris41 10551: 
1.394     bowersj2 10552: =item * 
                   10553: X<appenv()>
1.949     raeburn  10554: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10555: the user envirnoment file, and will be restored for each access this
1.620     albertel 10556: user makes during this session, also modifies the %env for the current
1.949     raeburn  10557: process. Optional rolesarrayref - if defined contains a reference to an array
                   10558: of roles which are exempt from the restriction on modifying user.role entries 
                   10559: in the user's environment.db and in %env.    
1.191     harris41 10560: 
                   10561: =item *
1.394     bowersj2 10562: X<delenv()>
1.987     raeburn  10563: B<delenv($delthis,$regexp)>: removes all items from the session
                   10564: environment file that begin with $delthis. If the 
                   10565: optional second arg - $regexp - is true, $delthis is treated as a 
                   10566: regular expression, otherwise \Q$delthis\E is used. 
                   10567: The values are also deleted from the current processes %env.
1.191     harris41 10568: 
1.795     albertel 10569: =item * get_env_multiple($name) 
                   10570: 
                   10571: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10572: values may be defined and end up as an array ref.
                   10573: 
                   10574: returns an array of values
                   10575: 
1.243     albertel 10576: =back
                   10577: 
                   10578: =head2 User Information
1.191     harris41 10579: 
1.243     albertel 10580: =over 4
1.191     harris41 10581: 
                   10582: =item *
1.394     bowersj2 10583: X<queryauthenticate()>
                   10584: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10585: authentication scheme
                   10586: 
                   10587: =item *
1.394     bowersj2 10588: X<authenticate()>
1.1073    raeburn  10589: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10590: authenticate user from domain's lib servers (first use the current
                   10591: one). C<$upass> should be the users password.
1.1073    raeburn  10592: $checkdefauth is optional (value is 1 if a check should be made to
                   10593:    authenticate user using default authentication method, and allow
                   10594:    account creation if username does not have account in the domain).
                   10595: $clientcancheckhost is optional (value is 1 if checking whether the
                   10596:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10597: 
                   10598: =item *
1.394     bowersj2 10599: X<homeserver()>
                   10600: B<homeserver($uname,$udom)>: find the server which has
                   10601: the user's directory and files (there must be only one), this caches
                   10602: the answer, and also caches if there is a borken connection.
1.191     harris41 10603: 
                   10604: =item *
1.394     bowersj2 10605: X<idget()>
                   10606: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10607: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10608: username, and only 1 username per ID in a specific domain) (returns
                   10609: hash: id=>name,id=>name)
1.191     harris41 10610: 
                   10611: =item *
1.394     bowersj2 10612: X<idrget()>
                   10613: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10614: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10615: 
                   10616: =item *
1.394     bowersj2 10617: X<idput()>
                   10618: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10619: 
                   10620: =item *
1.394     bowersj2 10621: X<rolesinit()>
                   10622: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10623: 
                   10624: =item *
1.551     albertel 10625: X<getsection()>
                   10626: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10627: course $cname, return section name/number or '' for "not in course"
                   10628: and '-1' for "no section"
                   10629: 
                   10630: =item *
1.394     bowersj2 10631: X<userenvironment()>
                   10632: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10633: passed in @what from the requested user's environment, returns a hash
                   10634: 
1.858     raeburn  10635: =item * 
                   10636: X<userlog_query()>
1.859     albertel 10637: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10638: activity.log file. %filters defines filters applied when parsing the
                   10639: log file. These can be start or end timestamps, or the type of action
                   10640: - log to look for Login or Logout events, check for Checkin or
                   10641: Checkout, role for role selection. The response is in the form
                   10642: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10643: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10644: 
1.243     albertel 10645: =back
                   10646: 
                   10647: =head2 User Roles
                   10648: 
                   10649: =over 4
                   10650: 
                   10651: =item *
                   10652: 
1.810     raeburn  10653: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10654:  F: full access
                   10655:  U,I,K: authentication modes (cxx only)
                   10656:  '': forbidden
                   10657:  1: user needs to choose course
                   10658:  2: browse allowed
1.766     albertel 10659:  A: passphrase authentication needed
1.243     albertel 10660: 
                   10661: =item *
                   10662: 
                   10663: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10664: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10665: and course level
                   10666: 
                   10667: =item *
                   10668: 
1.988     raeburn  10669: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10670: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10671: $type is Course (default) or Community.
1.988     raeburn  10672: If $forcedefault evaluates to true, text returned will be default 
                   10673: text for $type. Otherwise, if this is a course, the text returned 
                   10674: will be a custom name for the role (if defined in the course's 
                   10675: environment).  If no custom name is defined the default is returned.
                   10676:    
1.832     raeburn  10677: =item *
                   10678: 
1.935     raeburn  10679: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10680: All arguments are optional. Returns a hash of a roles, either for
                   10681: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10682: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10683: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10684: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10685: For each key, value is set to colon-separated start and end times for
                   10686: the role.  If no username and domain are specified, will default to
1.934     raeburn  10687: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10688: of role statuses (active, future or previous), roles 
                   10689: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10690: to restrict the list of roles reported. If no array ref is 
                   10691: provided for types, will default to return only active roles.
1.834     albertel 10692: 
1.243     albertel 10693: =back
                   10694: 
                   10695: =head2 User Modification
                   10696: 
                   10697: =over 4
                   10698: 
                   10699: =item *
                   10700: 
1.957     raeburn  10701: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10702: user for the level given by URL.  Optional start and end dates (leave empty
                   10703: string or zero for "no date")
1.191     harris41 10704: 
                   10705: =item *
                   10706: 
1.243     albertel 10707: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10708: change a users, password, possible return values are: ok,
                   10709: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10710: refused
1.191     harris41 10711: 
                   10712: =item *
                   10713: 
1.243     albertel 10714: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10715: 
                   10716: =item *
                   10717: 
1.1058    raeburn  10718: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10719:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10720: 
                   10721: will update user information (firstname,middlename,lastname,generation,
                   10722: permanentemail), and if forceid is true, student/employee ID also.
                   10723: A user's institutional affiliation(s) can also be updated.
                   10724: User information fields will not be overwritten with empty entries 
                   10725: unless the field is included in the $candelete array reference.
                   10726: This array is included when a single user is modified via "Manage Users",
                   10727: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10728: 
                   10729: =item *
                   10730: 
1.286     matthew  10731: modifystudent
                   10732: 
1.957     raeburn  10733: modify a student's enrollment and identification information.
1.286     matthew  10734: The course id is resolved based on the current users environment.  
                   10735: This means the envoking user must be a course coordinator or otherwise
                   10736: associated with a course.
                   10737: 
1.297     matthew  10738: This call is essentially a wrapper for lonnet::modifyuser and
                   10739: lonnet::modify_student_enrollment
1.286     matthew  10740: 
                   10741: Inputs: 
                   10742: 
                   10743: =over 4
                   10744: 
1.957     raeburn  10745: =item B<$udom> Student's loncapa domain
1.286     matthew  10746: 
1.957     raeburn  10747: =item B<$uname> Student's loncapa login name
1.286     matthew  10748: 
1.964     bisitz   10749: =item B<$uid> Student/Employee ID
1.286     matthew  10750: 
1.957     raeburn  10751: =item B<$umode> Student's authentication mode
1.286     matthew  10752: 
1.957     raeburn  10753: =item B<$upass> Student's password
1.286     matthew  10754: 
1.957     raeburn  10755: =item B<$first> Student's first name
1.286     matthew  10756: 
1.957     raeburn  10757: =item B<$middle> Student's middle name
1.286     matthew  10758: 
1.957     raeburn  10759: =item B<$last> Student's last name
1.286     matthew  10760: 
1.957     raeburn  10761: =item B<$gene> Student's generation
1.286     matthew  10762: 
1.957     raeburn  10763: =item B<$usec> Student's section in course
1.286     matthew  10764: 
                   10765: =item B<$end> Unix time of the roles expiration
                   10766: 
                   10767: =item B<$start> Unix time of the roles start date
                   10768: 
                   10769: =item B<$forceid> If defined, allow $uid to be changed
                   10770: 
                   10771: =item B<$desiredhome> server to use as home server for student
                   10772: 
1.957     raeburn  10773: =item B<$email> Student's permanent e-mail address
                   10774: 
                   10775: =item B<$type> Type of enrollment (auto or manual)
                   10776: 
1.963     raeburn  10777: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10778: 
                   10779: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10780: 
1.963     raeburn  10781: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10782: 
1.963     raeburn  10783: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10784: 
1.963     raeburn  10785: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10786: 
1.286     matthew  10787: =back
1.297     matthew  10788: 
                   10789: =item *
                   10790: 
                   10791: modify_student_enrollment
                   10792: 
                   10793: Change a students enrollment status in a class.  The environment variable
                   10794: 'role.request.course' must be defined for this function to proceed.
                   10795: 
                   10796: Inputs:
                   10797: 
                   10798: =over 4
                   10799: 
                   10800: =item $udom, students domain
                   10801: 
                   10802: =item $uname, students name
                   10803: 
                   10804: =item $uid, students user id
                   10805: 
                   10806: =item $first, students first name
                   10807: 
                   10808: =item $middle
                   10809: 
                   10810: =item $last
                   10811: 
                   10812: =item $gene
                   10813: 
                   10814: =item $usec
                   10815: 
                   10816: =item $end
                   10817: 
                   10818: =item $start
                   10819: 
1.957     raeburn  10820: =item $type
                   10821: 
                   10822: =item $locktype
                   10823: 
                   10824: =item $cid
                   10825: 
                   10826: =item $selfenroll
                   10827: 
                   10828: =item $context
                   10829: 
1.297     matthew  10830: =back
                   10831: 
1.191     harris41 10832: 
                   10833: =item *
                   10834: 
1.243     albertel 10835: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10836: custom role; give a custom role to a user for the level given by URL.  Specify
                   10837: name and domain of role author, and role name
1.191     harris41 10838: 
                   10839: =item *
                   10840: 
1.243     albertel 10841: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10842: 
                   10843: =item *
                   10844: 
1.243     albertel 10845: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10846: 
                   10847: =back
                   10848: 
                   10849: =head2 Course Infomation
                   10850: 
                   10851: =over 4
1.191     harris41 10852: 
                   10853: =item *
                   10854: 
1.631     albertel 10855: coursedescription($courseid) : returns a hash of information about the
                   10856: specified course id, including all environment settings for the
                   10857: course, the description of the course will be in the hash under the
                   10858: key 'description'
1.191     harris41 10859: 
                   10860: =item *
                   10861: 
1.624     albertel 10862: resdata($name,$domain,$type,@which) : request for current parameter
                   10863: setting for a specific $type, where $type is either 'course' or 'user',
                   10864: @what should be a list of parameters to ask about. This routine caches
                   10865: answers for 5 minutes.
1.243     albertel 10866: 
1.877     foxr     10867: =item *
                   10868: 
                   10869: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10870: data base, returning a hash that is keyed by the resource name and has
                   10871: values that are the resource value.  I believe that the timestamps and
                   10872: versions are also returned.
                   10873: 
                   10874: 
1.243     albertel 10875: =back
                   10876: 
                   10877: =head2 Course Modification
                   10878: 
                   10879: =over 4
1.191     harris41 10880: 
                   10881: =item *
                   10882: 
1.243     albertel 10883: writecoursepref($courseid,%prefs) : write preferences (environment
                   10884: database) for a course
1.191     harris41 10885: 
                   10886: =item *
                   10887: 
1.1011    raeburn  10888: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10889: 
                   10890: =item *
                   10891: 
1.1038    raeburn  10892: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10893: 
                   10894: =back
                   10895: 
                   10896: =head2 Resource Subroutines
                   10897: 
                   10898: =over 4
1.191     harris41 10899: 
                   10900: =item *
                   10901: 
1.243     albertel 10902: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10903: 
                   10904: =item *
                   10905: 
1.243     albertel 10906: repcopy($filename) : subscribes to the requested file, and attempts to
                   10907: replicate from the owning library server, Might return
1.607     raeburn  10908: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10909: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10910: resource. Expects the local filesystem pathname
                   10911: (/home/httpd/html/res/....)
                   10912: 
                   10913: =back
                   10914: 
                   10915: =head2 Resource Information
                   10916: 
                   10917: =over 4
1.191     harris41 10918: 
                   10919: =item *
                   10920: 
1.243     albertel 10921: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10922: a vairety of different possible values, $varname should be a request
                   10923: string, and the other parameters can be used to specify who and what
                   10924: one is asking about.
                   10925: 
                   10926: Possible values for $varname are environment.lastname (or other item
                   10927: from the envirnment hash), user.name (or someother aspect about the
                   10928: user), resource.0.maxtries (or some other part and parameter of a
                   10929: resource)
1.204     albertel 10930: 
                   10931: =item *
                   10932: 
1.243     albertel 10933: directcondval($number) : get current value of a condition; reads from a state
                   10934: string
1.204     albertel 10935: 
                   10936: =item *
                   10937: 
1.243     albertel 10938: condval($condidx) : value of condition index based on state
1.204     albertel 10939: 
                   10940: =item *
                   10941: 
1.243     albertel 10942: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10943: resource's metadata, $what should be either a specific key, or either
                   10944: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10945: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10946: 
                   10947: this function automatically caches all requests
1.191     harris41 10948: 
                   10949: =item *
                   10950: 
1.243     albertel 10951: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10952: network of library servers; returns file handle of where SQL and regex results
                   10953: will be stored for query
1.191     harris41 10954: 
                   10955: =item *
                   10956: 
1.243     albertel 10957: symbread($filename) : return symbolic list entry (filename argument optional);
                   10958: returns the data handle
1.191     harris41 10959: 
                   10960: =item *
                   10961: 
1.243     albertel 10962: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10963: a possible symb for the URL in $thisfn, and if is an encryypted
                   10964: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10965: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10966: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10967: 
1.191     harris41 10968: 
                   10969: =item *
                   10970: 
1.243     albertel 10971: symbclean($symb) : removes versions numbers from a symb, returns the
                   10972: cleaned symb
1.191     harris41 10973: 
                   10974: =item *
                   10975: 
1.243     albertel 10976: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10977: course map, user must be in a course for it to work.
1.191     harris41 10978: 
                   10979: =item *
                   10980: 
1.243     albertel 10981: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10982: 
                   10983: =item *
                   10984: 
1.243     albertel 10985: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10986: a random seed, all arguments are optional, if they aren't sent it uses the
                   10987: environment to derive them. Note: if symb isn't sent and it can't get one
                   10988: from &symbread it will use the current time as its return value
1.191     harris41 10989: 
                   10990: =item *
                   10991: 
1.243     albertel 10992: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10993: unfakeable, receipt
1.191     harris41 10994: 
                   10995: =item *
                   10996: 
1.620     albertel 10997: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10998: 
                   10999: =item *
                   11000: 
1.243     albertel 11001: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11002: 
                   11003: =item *
                   11004: 
1.243     albertel 11005: 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 11006: 
                   11007: =item *
                   11008: 
1.243     albertel 11009: 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 11010: 
                   11011: =item *
                   11012: 
1.243     albertel 11013: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11014: 
                   11015: =item *
                   11016: 
1.243     albertel 11017: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11018: forcing spreadsheet to reevaluate the resource scores next time.
                   11019: 
                   11020: =back
                   11021: 
                   11022: =head2 Storing/Retreiving Data
                   11023: 
                   11024: =over 4
1.191     harris41 11025: 
                   11026: =item *
                   11027: 
1.243     albertel 11028: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11029: for this url; hashref needs to be given and should be a \%hashname; the
                   11030: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11031: be derived from the env
1.191     harris41 11032: 
                   11033: =item *
                   11034: 
1.243     albertel 11035: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11036: uses critical subroutine
1.191     harris41 11037: 
                   11038: =item *
                   11039: 
1.243     albertel 11040: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11041: all args are optional
1.191     harris41 11042: 
                   11043: =item *
                   11044: 
1.717     albertel 11045: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11046: dumps the complete (or key matching regexp) namespace into a hash
                   11047: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11048: normally &store()ed into
                   11049: 
                   11050: $range should be either an integer '100' (give me the first 100
                   11051:                                            matching records)
                   11052:               or be  two integers sperated by a - with no spaces
                   11053:                  '30-50' (give me the 30th through the 50th matching
                   11054:                           records)
                   11055: 
                   11056: 
                   11057: =item *
                   11058: 
                   11059: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11060: replaces a &store() version of data with a replacement set of data
                   11061: for a particular resource in a namespace passed in the $storehash hash 
                   11062: reference
                   11063: 
                   11064: =item *
                   11065: 
1.243     albertel 11066: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11067: works very similar to store/cstore, but all data is stored in a
                   11068: temporary location and can be reset using tmpreset, $storehash should
                   11069: be a hash reference, returns nothing on success
1.191     harris41 11070: 
                   11071: =item *
                   11072: 
1.243     albertel 11073: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11074: similar to restore, but all data is stored in a temporary location and
                   11075: can be reset using tmpreset. Returns a hash of values on success,
                   11076: error string otherwise.
1.191     harris41 11077: 
                   11078: =item *
                   11079: 
1.243     albertel 11080: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11081: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11082: 
                   11083: =item *
                   11084: 
1.243     albertel 11085: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11086: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11087: 
                   11088: =item *
                   11089: 
1.243     albertel 11090: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11091: namesp ($udom and $uname are optional)
1.191     harris41 11092: 
                   11093: =item *
                   11094: 
1.702     albertel 11095: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11096: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11097: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11098: 
1.702     albertel 11099: $range should be either an integer '100' (give me the first 100
                   11100:                                            matching records)
                   11101:               or be  two integers sperated by a - with no spaces
                   11102:                  '30-50' (give me the 30th through the 50th matching
                   11103:                           records)
1.449     matthew  11104: =item *
                   11105: 
                   11106: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11107: $store can be a scalar, an array reference, or if the amount to be 
                   11108: incremented is > 1, a hash reference.
                   11109: 
                   11110: ($udom and $uname are optional)
1.191     harris41 11111: 
                   11112: =item *
                   11113: 
1.243     albertel 11114: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11115: ($udom and $uname are optional)
1.191     harris41 11116: 
                   11117: =item *
                   11118: 
1.243     albertel 11119: cput($namespace,$storehash,$udom,$uname) : critical put
                   11120: ($udom and $uname are optional)
1.191     harris41 11121: 
                   11122: =item *
                   11123: 
1.748     albertel 11124: newput($namespace,$storehash,$udom,$uname) :
                   11125: 
                   11126: Attempts to store the items in the $storehash, but only if they don't
                   11127: currently exist, if this succeeds you can be certain that you have 
                   11128: successfully created a new key value pair in the $namespace db.
                   11129: 
                   11130: 
                   11131: Args:
                   11132:  $namespace: name of database to store values to
                   11133:  $storehash: hashref to store to the db
                   11134:  $udom: (optional) domain of user containing the db
                   11135:  $uname: (optional) name of user caontaining the db
                   11136: 
                   11137: Returns:
                   11138:  'ok' -> succeeded in storing all keys of $storehash
                   11139:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11140:                         least <key> already existed in the db (other
                   11141:                         requested keys may also already exist)
1.967     bisitz   11142:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11143:  'con_lost' -> unable to contact request server
                   11144:  'refused' -> action was not allowed by remote machine
                   11145: 
                   11146: 
                   11147: =item *
                   11148: 
1.243     albertel 11149: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11150: reference filled in from namesp (encrypts the return communication)
                   11151: ($udom and $uname are optional)
1.191     harris41 11152: 
                   11153: =item *
                   11154: 
1.243     albertel 11155: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11156: critical subroutine
                   11157: 
1.806     raeburn  11158: =item *
                   11159: 
1.860     raeburn  11160: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11161: array reference filled in from namespace found in domain level on either
                   11162: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11163: 
                   11164: =item *
                   11165: 
1.860     raeburn  11166: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11167: domain level either on specified domain server ($uhome) or primary domain 
                   11168: server ($udom and $uhome are optional)
1.806     raeburn  11169: 
1.943     raeburn  11170: =item * 
                   11171: 
                   11172: get_domain_defaults($target_domain) : returns hash with defaults for
                   11173: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11174: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11175: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11176: Values are retrieved from cache (if current), or from domain's configuration.db
                   11177: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11178: or lonTabs/domain.tab. 
                   11179: 
                   11180: %domdefaults = &get_auth_defaults($target_domain);
                   11181: 
1.243     albertel 11182: =back
                   11183: 
                   11184: =head2 Network Status Functions
                   11185: 
                   11186: =over 4
1.191     harris41 11187: 
                   11188: =item *
                   11189: 
                   11190: dirlist($uri) : return directory list based on URI
                   11191: 
                   11192: =item *
                   11193: 
1.243     albertel 11194: spareserver() : find server with least workload from spare.tab
                   11195: 
1.986     foxr     11196: 
                   11197: =item *
                   11198: 
                   11199: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11200: if there is no corresponding loncapa host.
                   11201: 
1.243     albertel 11202: =back
                   11203: 
1.986     foxr     11204: 
1.243     albertel 11205: =head2 Apache Request
                   11206: 
                   11207: =over 4
1.191     harris41 11208: 
                   11209: =item *
                   11210: 
1.243     albertel 11211: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11212: localhost, posts hash
                   11213: 
                   11214: =back
                   11215: 
                   11216: =head2 Data to String to Data
                   11217: 
                   11218: =over 4
1.191     harris41 11219: 
                   11220: =item *
                   11221: 
1.243     albertel 11222: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11223: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11224: 
                   11225: =item *
                   11226: 
1.243     albertel 11227: hashref2str($hashref) : convert a hashref into a string complete with
                   11228: escaping and '=' and '&' separators, supports elements that are
                   11229: arrayrefs and hashrefs
1.191     harris41 11230: 
                   11231: =item *
                   11232: 
1.243     albertel 11233: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11234: with escaping and '&' separators, supports elements that are arrayrefs
                   11235: and hashrefs
1.191     harris41 11236: 
                   11237: =item *
                   11238: 
1.243     albertel 11239: str2hash($string) : convert string to hash using unescaping and
                   11240: splitting on '=' and '&', supports elements that are arrayrefs and
                   11241: hashrefs
1.191     harris41 11242: 
                   11243: =item *
                   11244: 
1.243     albertel 11245: str2array($string) : convert string to hash using unescaping and
                   11246: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11247: 
                   11248: =back
                   11249: 
                   11250: =head2 Logging Routines
                   11251: 
                   11252: =over 4
                   11253: 
                   11254: These routines allow one to make log messages in the lonnet.log and
                   11255: lonnet.perm logfiles.
1.191     harris41 11256: 
                   11257: =item *
                   11258: 
1.243     albertel 11259: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11260: 
                   11261: =item *
                   11262: 
1.243     albertel 11263: logthis() : append message to the normal lonnet.log file, it gets
                   11264: preiodically rolled over and deleted.
1.191     harris41 11265: 
                   11266: =item *
                   11267: 
1.243     albertel 11268: logperm() : append a permanent message to lonnet.perm.log, this log
                   11269: file never gets deleted by any automated portion of the system, only
                   11270: messages of critical importance should go in here.
                   11271: 
                   11272: =back
                   11273: 
                   11274: =head2 General File Helper Routines
                   11275: 
                   11276: =over 4
1.191     harris41 11277: 
                   11278: =item *
                   11279: 
1.481     raeburn  11280: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11281: (a) files in /uploaded
                   11282:   (i) If a local copy of the file exists - 
                   11283:       compares modification date of local copy with last-modified date for 
                   11284:       definitive version stored on home server for course. If local copy is 
                   11285:       stale, requests a new version from the home server and stores it. 
                   11286:       If the original has been removed from the home server, then local copy 
                   11287:       is unlinked.
                   11288:   (ii) If local copy does not exist -
                   11289:       requests the file from the home server and stores it. 
                   11290:   
                   11291:   If $caller is 'uploadrep':  
                   11292:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11293:     for request for files originally uploaded via DOCS. 
                   11294:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11295:   
                   11296:   Otherwise:
                   11297:      This indicates a call from the content generation phase of the request.
                   11298:      -  returns the entire contents of the file or -1.
                   11299:      
                   11300: (b) files in /res
                   11301:    - returns the entire contents of a file or -1; 
                   11302:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11303: 
1.712     albertel 11304: 
                   11305: =item *
                   11306: 
                   11307: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11308:                   reference
                   11309: 
                   11310: returns either a stat() list of data about the file or an empty list
                   11311: if the file doesn't exist or couldn't find out about it (connection
                   11312: problems or user unknown)
                   11313: 
1.191     harris41 11314: =item *
                   11315: 
1.243     albertel 11316: filelocation($dir,$file) : returns file system location of a file
                   11317: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11318: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11319: and a file of ../bob will become /a/bob)
1.191     harris41 11320: 
                   11321: =item *
                   11322: 
                   11323: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11324: filelocation except for hrefs
                   11325: 
                   11326: =item *
                   11327: 
                   11328: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11329: 
1.243     albertel 11330: =back
                   11331: 
1.608     albertel 11332: =head2 Usererfile file routines (/uploaded*)
                   11333: 
                   11334: =over 4
                   11335: 
                   11336: =item *
                   11337: 
                   11338: userfileupload(): main rotine for putting a file in a user or course's
                   11339:                   filespace, arguments are,
                   11340: 
1.620     albertel 11341:  formname - required - this is the name of the element in $env where the
1.608     albertel 11342:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11343:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11344:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 11345:  coursedoc - if true, store the file in the course of the active role
                   11346:              of the current user
                   11347:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11348:          if undefined, it will be placed in "unknown"
                   11349: 
                   11350:  (This routine calls clean_filename() to remove any dangerous
                   11351:  characters from the filename, and then calls finuserfileupload() to
                   11352:  complete the transaction)
                   11353: 
                   11354:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11355:  and /adm/notfound.html if unsuccessful
                   11356: 
                   11357: =item *
                   11358: 
                   11359: clean_filename(): routine for cleaing a filename up for storage in
                   11360:                  userfile space, argument is:
                   11361: 
                   11362:  filename - proposed filename
                   11363: 
                   11364: returns: the new clean filename
                   11365: 
                   11366: =item *
                   11367: 
                   11368: finishuserfileupload(): routine that creaes and sends the file to
                   11369: userspace, probably shouldn't be called directly
                   11370: 
                   11371:   docuname: username or courseid of destination for the file
                   11372:   docudom: domain of user/course of destination for the file
                   11373:   formname: same as for userfileupload()
                   11374:   fname: filename (inculding subdirectories) for the file
                   11375: 
                   11376:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11377:  and /adm/notfound.html if unsuccessful
                   11378: 
                   11379: =item *
                   11380: 
                   11381: renameuserfile(): renames an existing userfile to a new name
                   11382: 
                   11383:   Args:
                   11384:    docuname: username or courseid of destination for the file
                   11385:    docudom: domain of user/course of destination for the file
                   11386:    old: current file name (including any subdirs under userfiles)
                   11387:    new: desired file name (including any subdirs under userfiles)
                   11388: 
                   11389: =item *
                   11390: 
                   11391: mkdiruserfile(): creates a directory is a userfiles dir
                   11392: 
                   11393:   Args:
                   11394:    docuname: username or courseid of destination for the file
                   11395:    docudom: domain of user/course of destination for the file
                   11396:    dir: dir to create (including any subdirs under userfiles)
                   11397: 
                   11398: =item *
                   11399: 
                   11400: removeuserfile(): removes a file that exists in userfiles
                   11401: 
                   11402:   Args:
                   11403:    docuname: username or courseid of destination for the file
                   11404:    docudom: domain of user/course of destination for the file
                   11405:    fname: filname to delete (including any subdirs under userfiles)
                   11406: 
                   11407: =item *
                   11408: 
                   11409: removeuploadedurl(): convience function for removeuserfile()
                   11410: 
                   11411:   Args:
                   11412:    url:  a full /uploaded/... url to delete
                   11413: 
1.747     albertel 11414: =item * 
                   11415: 
                   11416: get_portfile_permissions():
                   11417:   Args:
                   11418:     domain: domain of user or course contain the portfolio files
                   11419:     user: name of user or num of course contain the portfolio files
                   11420:   Returns:
                   11421:     hashref of a dump of the proper file_permissions.db
                   11422:    
                   11423: 
                   11424: =item * 
                   11425: 
                   11426: get_access_controls():
                   11427: 
                   11428: Args:
                   11429:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11430:   group: (optional) the group you want the files associated with
                   11431:   file: (optional) the file you want access info on
                   11432: 
                   11433: Returns:
1.749     raeburn  11434:     a hash (keys are file names) of hashes containing
                   11435:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11436:         values are XML containing access control settings (see below) 
1.747     albertel 11437: 
                   11438: Internal notes:
                   11439: 
1.749     raeburn  11440:  access controls are stored in file_permissions.db as key=value pairs.
                   11441:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11442:         where scope -> public,guest,course,group,domains or users.
                   11443:               end -> UNIX time for end of access (0 -> no end date)
                   11444:               start -> UNIX time for start of access
                   11445: 
                   11446:     value -> XML description of access control
                   11447:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11448:             <start></start>
                   11449:             <end></end>
                   11450: 
                   11451:             <password></password>  for scope type = guest
                   11452: 
                   11453:             <domain></domain>     for scope type = course or group
                   11454:             <number></number>
                   11455:             <roles id="">
                   11456:              <role></role>
                   11457:              <access></access>
                   11458:              <section></section>
                   11459:              <group></group>
                   11460:             </roles>
                   11461: 
                   11462:             <dom></dom>         for scope type = domains
                   11463: 
                   11464:             <users>             for scope type = users
                   11465:              <user>
                   11466:               <uname></uname>
                   11467:               <udom></udom>
                   11468:              </user>
                   11469:             </users>
                   11470:            </scope> 
                   11471:               
                   11472:  Access data is also aggregated for each file in an additional key=value pair:
                   11473:  key -> path to file/file_name\0accesscontrol 
                   11474:  value -> reference to hash
                   11475:           hash contains key = value pairs
                   11476:           where key = uniqueID:scope_end_start
                   11477:                 value = UNIX time record was last updated
                   11478: 
                   11479:           Used to improve speed of look-ups of access controls for each file.  
                   11480:  
                   11481:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11482: 
                   11483: modify_access_controls():
                   11484: 
                   11485: Modifies access controls for a portfolio file
                   11486: Args
                   11487: 1. file name
                   11488: 2. reference to hash of required changes,
                   11489: 3. domain
                   11490: 4. username
                   11491:   where domain,username are the domain of the portfolio owner 
                   11492:   (either a user or a course) 
                   11493: 
                   11494: Returns:
                   11495: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11496: 2. result of deletions ('ok' or 'error', with error message).
                   11497: 3. reference to hash of any new or updated access controls.
                   11498: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11499:    key = integer (inbound ID)
                   11500:    value = uniqueID  
1.747     albertel 11501: 
1.608     albertel 11502: =back
                   11503: 
1.243     albertel 11504: =head2 HTTP Helper Routines
                   11505: 
                   11506: =over 4
                   11507: 
1.191     harris41 11508: =item *
                   11509: 
                   11510: escape() : unpack non-word characters into CGI-compatible hex codes
                   11511: 
                   11512: =item *
                   11513: 
                   11514: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11515: 
1.243     albertel 11516: =back
                   11517: 
                   11518: =head1 PRIVATE SUBROUTINES
                   11519: 
                   11520: =head2 Underlying communication routines (Shouldn't call)
                   11521: 
                   11522: =over 4
                   11523: 
                   11524: =item *
                   11525: 
                   11526: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11527: 
                   11528: =item *
                   11529: 
                   11530: reply() : uses subreply to send a message to remote machine, logs all failures
                   11531: 
                   11532: =item *
                   11533: 
                   11534: critical() : passes a critical message to another server; if cannot
                   11535: get through then place message in connection buffer directory and
                   11536: returns con_delayed, if incapable of saving message, returns
                   11537: con_failed
                   11538: 
                   11539: =item *
                   11540: 
                   11541: reconlonc() : tries to reconnect lonc client processes.
                   11542: 
                   11543: =back
                   11544: 
                   11545: =head2 Resource Access Logging
                   11546: 
                   11547: =over 4
                   11548: 
                   11549: =item *
                   11550: 
                   11551: flushcourselogs() : flush (save) buffer logs and access logs
                   11552: 
                   11553: =item *
                   11554: 
                   11555: courselog($what) : save message for course in hash
                   11556: 
                   11557: =item *
                   11558: 
                   11559: courseacclog($what) : save message for course using &courselog().  Perform
                   11560: special processing for specific resource types (problems, exams, quizzes, etc).
                   11561: 
1.191     harris41 11562: =item *
                   11563: 
                   11564: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11565: as a PerlChildExitHandler
1.243     albertel 11566: 
                   11567: =back
                   11568: 
                   11569: =head2 Other
                   11570: 
                   11571: =over 4
                   11572: 
                   11573: =item *
                   11574: 
                   11575: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11576: 
                   11577: =back
                   11578: 
                   11579: =cut
1.877     foxr     11580: 

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