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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1083  ! raeburn     4: # $Id: lonnet.pm,v 1.1082 2010/08/20 18:17: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.985     raeburn  4923:     my ($uname,$udom,$tool,$action,$context) = @_;
                   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.1025    raeburn  4965:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985     raeburn  4966:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4967:         $inststatus = $userenv{'inststatus'};
                   4968:     }
                   4969: 
                   4970:     if ($toolstatus ne '') {
                   4971:         if ($toolstatus) {
                   4972:             $access = 1;
                   4973:         } else {
                   4974:             $access = 0;
                   4975:         }
                   4976:         return $access;
                   4977:     }
                   4978: 
                   4979:     my $is_adv = &is_advanced_user($udom,$uname);
                   4980:     my %domdef = &get_domain_defaults($udom);
                   4981:     if (ref($domdef{$tool}) eq 'HASH') {
                   4982:         if ($is_adv) {
                   4983:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4984:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4985:                     $access = 1;
                   4986:                 } else {
                   4987:                     $access = 0;
                   4988:                 }
                   4989:                 return $access;
                   4990:             }
                   4991:         }
                   4992:         if ($inststatus ne '') {
                   4993:             my ($hasaccess,$hasnoaccess);
                   4994:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4995:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4996:                     if ($domdef{$tool}{$affiliation}) {
                   4997:                         $hasaccess = 1;
                   4998:                     } else {
                   4999:                         $hasnoaccess = 1;
                   5000:                     }
                   5001:                 }
                   5002:             }
                   5003:             if ($hasaccess || $hasnoaccess) {
                   5004:                 if ($hasaccess) {
                   5005:                     $access = 1;
                   5006:                 } elsif ($hasnoaccess) {
                   5007:                     $access = 0; 
                   5008:                 }
                   5009:                 return $access;
                   5010:             }
                   5011:         } else {
                   5012:             if ($domdef{$tool}{'default'} ne '') {
                   5013:                 if ($domdef{$tool}{'default'}) {
                   5014:                     $access = 1;
                   5015:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5016:                     $access = 0;
                   5017:                 }
                   5018:                 return $access;
                   5019:             }
                   5020:         }
                   5021:     } else {
1.985     raeburn  5022:         if ($context eq 'tools') {
                   5023:             $access = 1;
                   5024:         } else {
                   5025:             $access = 0;
                   5026:         }
1.976     raeburn  5027:         return $access;
                   5028:     }
                   5029: }
                   5030: 
1.1050    raeburn  5031: sub is_course_owner {
                   5032:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5033:     if (($udom eq '') || ($uname eq '')) {
                   5034:         $udom = $env{'user.domain'};
                   5035:         $uname = $env{'user.name'};
                   5036:     }
                   5037:     unless (($udom eq '') || ($uname eq '')) {
                   5038:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5039:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5040:                 return 1;
                   5041:             } else {
                   5042:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5043:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5044:                     return 1;
                   5045:                 }
                   5046:             }
                   5047:         }
                   5048:     }
                   5049:     return;
                   5050: }
                   5051: 
1.976     raeburn  5052: sub is_advanced_user {
                   5053:     my ($udom,$uname) = @_;
                   5054:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5055:     my %allroles;
                   5056:     my $is_adv;
                   5057:     foreach my $role (keys(%roleshash)) {
                   5058:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5059:         my $area = '/'.$tdomain.'/'.$trest;
                   5060:         if ($sec ne '') {
                   5061:             $area .= '/'.$sec;
                   5062:         }
                   5063:         if (($area ne '') && ($trole ne '')) {
                   5064:             my $spec=$trole.'.'.$area;
                   5065:             if ($trole =~ /^cr\//) {
                   5066:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5067:             } elsif ($trole ne 'gr') {
                   5068:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5069:             }
                   5070:         }
                   5071:     }
                   5072:     foreach my $role (keys(%allroles)) {
                   5073:         last if ($is_adv);
                   5074:         foreach my $item (split(/:/,$allroles{$role})) {
                   5075:             if ($item ne '') {
                   5076:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5077:                 if ($privilege eq 'adv') {
                   5078:                     $is_adv = 1;
                   5079:                     last;
                   5080:                 }
                   5081:             }
                   5082:         }
                   5083:     }
                   5084:     return $is_adv;
                   5085: }
1.798     raeburn  5086: 
1.1035    raeburn  5087: sub check_can_request {
1.1036    raeburn  5088:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5089:     my $canreq = 0;
                   5090:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5091:     my @options = ('approval','validate','autolimit');
                   5092:     my $optregex = join('|',@options);
                   5093:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5094:         foreach my $type (@{$types}) {
                   5095:             if (&usertools_access($env{'user.name'},
                   5096:                                   $env{'user.domain'},
                   5097:                                   $type,undef,'requestcourses')) {
                   5098:                 $canreq ++;
1.1036    raeburn  5099:                 if (ref($request_domains) eq 'HASH') {
                   5100:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5101:                 }
1.1035    raeburn  5102:                 if ($dom eq $env{'user.domain'}) {
                   5103:                     $can_request->{$type} = 1;
                   5104:                 }
                   5105:             }
                   5106:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5107:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5108:                 if (@curr > 0) {
1.1036    raeburn  5109:                     foreach my $item (@curr) {
                   5110:                         if (ref($request_domains) eq 'HASH') {
                   5111:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5112:                             if ($otherdom ne '') {
                   5113:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5114:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5115:                                         push(@{$request_domains->{$type}},$otherdom);
                   5116:                                     }
                   5117:                                 } else {
                   5118:                                     push(@{$request_domains->{$type}},$otherdom);
                   5119:                                 }
                   5120:                             }
                   5121:                         }
                   5122:                     }
                   5123:                     unless($dom eq $env{'user.domain'}) {
                   5124:                         $canreq ++;
1.1035    raeburn  5125:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5126:                             $can_request->{$type} = 1;
                   5127:                         }
                   5128:                     }
                   5129:                 }
                   5130:             }
                   5131:         }
                   5132:     }
                   5133:     return $canreq;
                   5134: }
                   5135: 
1.341     www      5136: # ---------------------------------------------- Custom access rule evaluation
                   5137: 
                   5138: sub customaccess {
                   5139:     my ($priv,$uri)=@_;
1.807     albertel 5140:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5141:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5142:     $udom = &LONCAPA::clean_domain($udom);
                   5143:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5144:     my $access=0;
1.800     albertel 5145:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5146: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5147: 	if ($type eq 'user') {
                   5148: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5149: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5150: 		if ($tdom) {
                   5151: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5152: 		}
1.896     albertel 5153: 		if ($tuname) {
                   5154: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5155: 		}
                   5156: 		$access=($effect eq 'allow');
                   5157: 		last;
                   5158: 	    }
                   5159: 	} else {
                   5160: 	    if ($role) {
                   5161: 		if ($role ne $urole) { next; }
                   5162: 	    }
                   5163: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5164: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5165: 		if ($tdom) {
                   5166: 		    if ($tdom ne $udom) { next; }
                   5167: 		}
                   5168: 		if ($tcrs) {
                   5169: 		    if ($tcrs ne $ucrs) { next; }
                   5170: 		}
                   5171: 		if ($tsec) {
                   5172: 		    if ($tsec ne $usec) { next; }
                   5173: 		}
                   5174: 		$access=($effect eq 'allow');
                   5175: 		last;
                   5176: 	    }
                   5177: 	    if ($realm eq '' && $role eq '') {
                   5178: 		$access=($effect eq 'allow');
                   5179: 	    }
1.402     bowersj2 5180: 	}
1.341     www      5181:     }
                   5182:     return $access;
                   5183: }
                   5184: 
1.103     harris41 5185: # ------------------------------------------------- Check for a user privilege
1.12      www      5186: 
                   5187: sub allowed {
1.810     raeburn  5188:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5189:     my $ver_orguri=$uri;
1.439     www      5190:     $uri=&deversion($uri);
1.152     www      5191:     my $orguri=$uri;
1.52      www      5192:     $uri=&declutter($uri);
1.809     raeburn  5193: 
1.810     raeburn  5194:     if ($priv eq 'evb') {
                   5195: # Evade communication block restrictions for specified role in a course
                   5196:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5197:             return $1;
                   5198:         } else {
                   5199:             return;
                   5200:         }
                   5201:     }
                   5202: 
1.620     albertel 5203:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5204: # Free bre access to adm and meta resources
1.775     albertel 5205:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5206: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5207: 	&& ($priv eq 'bre')) {
1.14      www      5208: 	return 'F';
1.159     www      5209:     }
                   5210: 
1.545     banghart 5211: # Free bre access to user's own portfolio contents
1.714     raeburn  5212:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5213:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5214: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5215:         my %setters;
                   5216:         my ($startblock,$endblock) = 
                   5217:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5218:         if ($startblock && $endblock) {
                   5219:             return 'B';
                   5220:         } else {
                   5221:             return 'F';
                   5222:         }
1.545     banghart 5223:     }
                   5224: 
1.762     raeburn  5225: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5226:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5227:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5228:         if (exists($env{'request.course.id'})) {
                   5229:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5230:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5231:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5232:                 my $courseprivid=$env{'request.course.id'};
                   5233:                 $courseprivid=~s/\_/\//;
                   5234:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5235:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5236:                     return $1; 
1.762     raeburn  5237:                 } else {
                   5238:                     if ($env{'request.course.sec'}) {
                   5239:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5240:                     }
                   5241:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5242:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5243:                         return $2;
                   5244:                     }
1.714     raeburn  5245:                 }
                   5246:             }
                   5247:         }
                   5248:     }
                   5249: 
1.159     www      5250: # Free bre to public access
                   5251: 
                   5252:     if ($priv eq 'bre') {
1.238     www      5253:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5254: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5255:            return 'F'; 
                   5256:         }
1.238     www      5257:         if ($copyright eq 'priv') {
                   5258:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5259: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5260: 		return '';
                   5261:             }
                   5262:         }
                   5263:         if ($copyright eq 'domain') {
                   5264:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5265: 	    unless (($env{'user.domain'} eq $1) ||
                   5266:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5267: 		return '';
                   5268:             }
1.262     matthew  5269:         }
1.620     albertel 5270:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5271:             # Library role, so allow browsing of resources in this domain.
                   5272:             return 'F';
1.238     www      5273:         }
1.341     www      5274:         if ($copyright eq 'custom') {
                   5275: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5276:         }
1.14      www      5277:     }
1.264     matthew  5278:     # Domain coordinator is trying to create a course
1.620     albertel 5279:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5280:         # uri is the requested domain in this case.
                   5281:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5282:         # a role of dc for the domain in question.
1.620     albertel 5283:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5284:     }
1.29      www      5285: 
1.52      www      5286:     my $thisallowed='';
                   5287:     my $statecond=0;
                   5288:     my $courseprivid='';
                   5289: 
1.1039    raeburn  5290:     my $ownaccess;
1.1043    raeburn  5291:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5292:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5293:         if ($uri eq '') {
                   5294:             $ownaccess = 1;
                   5295:         } else {
                   5296:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5297:                 my $udom = $env{'user.domain'};
                   5298:                 my $uname = $env{'user.name'};
                   5299:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5300:                     $ownaccess = 1;
1.1040    raeburn  5301:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5302:                     unless ($uri =~ m{\.\./}) {
                   5303:                         $ownaccess = 1;
                   5304:                     }
                   5305:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5306:                     my $now = time;
                   5307:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5308:                         my $adom = $1;
                   5309:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5310:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5311:                                 my ($start,$end) = split('.',$env{$key});
                   5312:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5313:                                     $ownaccess = 1;
                   5314:                                     last;
                   5315:                                 }
                   5316:                             }
                   5317:                         }
                   5318:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5319:                         my $adom = $1;
                   5320:                         my $aname = $2;
1.1042    raeburn  5321:                         foreach my $role ('ca','aa') { 
                   5322:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5323:                                 my ($start,$end) =
                   5324:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5325:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5326:                                     $ownaccess = 1;
                   5327:                                     last;
                   5328:                                 }
1.1039    raeburn  5329:                             }
                   5330:                         }
                   5331:                     }
                   5332:                 }
                   5333:             }
                   5334:         }
                   5335:     }
                   5336: 
1.52      www      5337: # Course
                   5338: 
1.620     albertel 5339:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5340:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5341:             $thisallowed.=$1;
                   5342:         }
1.52      www      5343:     }
1.29      www      5344: 
1.52      www      5345: # Domain
                   5346: 
1.620     albertel 5347:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5348:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5349:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5350:             $thisallowed.=$1;
                   5351:         }
1.12      www      5352:     }
1.52      www      5353: 
                   5354: # Course: uri itself is a course
1.66      www      5355:     my $courseuri=$uri;
                   5356:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5357:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5358: 
1.620     albertel 5359:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5360:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5361:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5362:             $thisallowed.=$1;
                   5363:         }
1.12      www      5364:     }
1.29      www      5365: 
1.665     albertel 5366: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5367: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5368:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5369: 	$thisallowed='';
1.671     raeburn  5370:         my ($match)=&is_on_map($uri);
                   5371:         if ($match) {
                   5372:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5373:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5374:                 $thisallowed.=$1;
                   5375:             }
                   5376:         } else {
1.705     albertel 5377:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5378:             if ($refuri) {
                   5379:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5380:                     $thisallowed='F';
1.671     raeburn  5381:                 } else {
                   5382:                     $refuri=&declutter($refuri);
                   5383:                     my ($match) = &is_on_map($refuri);
                   5384:                     if ($match) {
                   5385:                         $thisallowed='F';
                   5386:                     }
1.669     raeburn  5387:                 }
1.671     raeburn  5388:             }
                   5389:         }
1.314     www      5390:     }
1.492     albertel 5391: 
1.766     albertel 5392:     if ($priv eq 'bre'
                   5393: 	&& $thisallowed ne 'F' 
                   5394: 	&& $thisallowed ne '2'
                   5395: 	&& &is_portfolio_url($uri)) {
                   5396: 	$thisallowed = &portfolio_access($uri);
                   5397:     }
                   5398:     
1.52      www      5399: # Full access at system, domain or course-wide level? Exit.
1.29      www      5400:     if ($thisallowed=~/F/) {
                   5401: 	return 'F';
                   5402:     }
                   5403: 
1.52      www      5404: # If this is generating or modifying users, exit with special codes
1.29      www      5405: 
1.643     www      5406:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5407: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5408: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5409: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5410: 	    unless ($auname) { return $thisallowed; }
                   5411: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5412: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5413: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5414: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5415: 	}
1.52      www      5416: 	return $thisallowed;
                   5417:     }
                   5418: #
1.103     harris41 5419: # Gathered so far: system, domain and course wide privileges
1.52      www      5420: #
                   5421: # Course: See if uri or referer is an individual resource that is part of 
                   5422: # the course
                   5423: 
1.620     albertel 5424:     if ($env{'request.course.id'}) {
1.232     www      5425: 
1.620     albertel 5426:        $courseprivid=$env{'request.course.id'};
                   5427:        if ($env{'request.course.sec'}) {
                   5428:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5429:        }
                   5430:        $courseprivid=~s/\_/\//;
                   5431:        my $checkreferer=1;
1.232     www      5432:        my ($match,$cond)=&is_on_map($uri);
                   5433:        if ($match) {
                   5434:            $statecond=$cond;
1.620     albertel 5435:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5436:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5437:                $thisallowed.=$1;
                   5438:                $checkreferer=0;
                   5439:            }
1.29      www      5440:        }
1.83      www      5441:        
1.148     www      5442:        if ($checkreferer) {
1.620     albertel 5443: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5444:             unless ($refuri) {
1.800     albertel 5445:                 foreach my $key (keys(%env)) {
                   5446: 		    if ($key=~/^httpref\..*\*/) {
                   5447: 			my $pattern=$key;
1.156     www      5448:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5449:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5450:                         $pattern=~s/\//\\\//g;
1.152     www      5451:                         if ($orguri=~/$pattern/) {
1.800     albertel 5452: 			    $refuri=$env{$key};
1.148     www      5453:                         }
                   5454:                     }
1.191     harris41 5455:                 }
1.148     www      5456:             }
1.232     www      5457: 
1.148     www      5458:          if ($refuri) { 
1.152     www      5459: 	  $refuri=&declutter($refuri);
1.232     www      5460:           my ($match,$cond)=&is_on_map($refuri);
                   5461:             if ($match) {
                   5462:               my $refstatecond=$cond;
1.620     albertel 5463:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5464:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5465:                   $thisallowed.=$1;
1.53      www      5466:                   $uri=$refuri;
                   5467:                   $statecond=$refstatecond;
1.52      www      5468:               }
                   5469:           }
1.148     www      5470:         }
1.29      www      5471:        }
1.52      www      5472:    }
1.29      www      5473: 
1.52      www      5474: #
1.103     harris41 5475: # Gathered now: all privileges that could apply, and condition number
1.52      www      5476: # 
                   5477: #
                   5478: # Full or no access?
                   5479: #
1.29      www      5480: 
1.52      www      5481:     if ($thisallowed=~/F/) {
                   5482: 	return 'F';
                   5483:     }
1.29      www      5484: 
1.52      www      5485:     unless ($thisallowed) {
                   5486:         return '';
                   5487:     }
1.29      www      5488: 
1.52      www      5489: # Restrictions exist, deal with them
                   5490: #
                   5491: #   C:according to course preferences
                   5492: #   R:according to resource settings
                   5493: #   L:unless locked
                   5494: #   X:according to user session state
                   5495: #
                   5496: 
                   5497: # Possibly locked functionality, check all courses
1.54      www      5498: # Locks might take effect only after 10 minutes cache expiration for other
                   5499: # courses, and 2 minutes for current course
1.52      www      5500: 
                   5501:     my $envkey;
                   5502:     if ($thisallowed=~/L/) {
1.1000    raeburn  5503:         foreach $envkey (keys(%env)) {
1.54      www      5504:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5505:                my $courseid=$2;
                   5506:                my $roleid=$1.'.'.$2;
1.92      www      5507:                $courseid=~s/^\///;
1.54      www      5508:                my $expiretime=600;
1.620     albertel 5509:                if ($env{'request.role'} eq $roleid) {
1.54      www      5510: 		  $expiretime=120;
                   5511:                }
                   5512: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5513:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5514:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5515: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5516:                }
1.620     albertel 5517:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5518:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5519: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5520:                        &log($env{'user.domain'},$env{'user.name'},
                   5521:                             $env{'user.home'},
1.57      www      5522:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5523:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5524:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5525: 		       return '';
                   5526:                    }
                   5527:                }
1.620     albertel 5528:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5529:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5530: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5531:                        &log($env{'user.domain'},$env{'user.name'},
                   5532:                             $env{'user.home'},
1.57      www      5533:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5534:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5535:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5536: 		       return '';
                   5537:                    }
                   5538:                }
                   5539: 	   }
1.29      www      5540:        }
1.52      www      5541:     }
                   5542:    
                   5543: #
                   5544: # Rest of the restrictions depend on selected course
                   5545: #
                   5546: 
1.620     albertel 5547:     unless ($env{'request.course.id'}) {
1.766     albertel 5548: 	if ($thisallowed eq 'A') {
                   5549: 	    return 'A';
1.814     raeburn  5550:         } elsif ($thisallowed eq 'B') {
                   5551:             return 'B';
1.766     albertel 5552: 	} else {
                   5553: 	    return '1';
                   5554: 	}
1.52      www      5555:     }
1.29      www      5556: 
1.52      www      5557: #
                   5558: # Now user is definitely in a course
                   5559: #
1.53      www      5560: 
                   5561: 
                   5562: # Course preferences
                   5563: 
                   5564:    if ($thisallowed=~/C/) {
1.620     albertel 5565:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5566:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5567:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5568: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5569: 	   if ($priv ne 'pch') { 
                   5570: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5571: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5572: 			$env{'request.course.id'});
                   5573: 	   }
1.237     www      5574:            return '';
                   5575:        }
                   5576: 
1.620     albertel 5577:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5578: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5579: 	   if ($priv ne 'pch') { 
                   5580: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5581: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5582: 			$env{'request.course.id'});
                   5583: 	   }
1.54      www      5584:            return '';
                   5585:        }
1.53      www      5586:    }
                   5587: 
                   5588: # Resource preferences
                   5589: 
                   5590:    if ($thisallowed=~/R/) {
1.620     albertel 5591:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5592:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5593: 	   if ($priv ne 'pch') { 
                   5594: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5595: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5596: 	   }
                   5597: 	   return '';
1.54      www      5598:        }
1.53      www      5599:    }
1.30      www      5600: 
1.246     www      5601: # Restricted by state or randomout?
1.30      www      5602: 
1.52      www      5603:    if ($thisallowed=~/X/) {
1.620     albertel 5604:       if ($env{'acc.randomout'}) {
1.579     albertel 5605: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5606:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5607:             return ''; 
                   5608:          }
1.247     www      5609:       }
                   5610:       if (&condval($statecond)) {
1.52      www      5611: 	 return '2';
                   5612:       } else {
                   5613:          return '';
                   5614:       }
                   5615:    }
1.30      www      5616: 
1.766     albertel 5617:     if ($thisallowed eq 'A') {
                   5618: 	return 'A';
1.814     raeburn  5619:     } elsif ($thisallowed eq 'B') {
                   5620:         return 'B';
1.766     albertel 5621:     }
1.52      www      5622:    return 'F';
1.232     www      5623: }
                   5624: 
1.710     albertel 5625: sub split_uri_for_cond {
                   5626:     my $uri=&deversion(&declutter(shift));
                   5627:     my @uriparts=split(/\//,$uri);
                   5628:     my $filename=pop(@uriparts);
                   5629:     my $pathname=join('/',@uriparts);
                   5630:     return ($pathname,$filename);
                   5631: }
1.232     www      5632: # --------------------------------------------------- Is a resource on the map?
                   5633: 
                   5634: sub is_on_map {
1.710     albertel 5635:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5636:     #Trying to find the conditional for the file
1.620     albertel 5637:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5638: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5639:     if ($match) {
1.289     bowersj2 5640: 	return (1,$1);
                   5641:     } else {
1.434     www      5642: 	return (0,0);
1.289     bowersj2 5643:     }
1.12      www      5644: }
                   5645: 
1.427     www      5646: # --------------------------------------------------------- Get symb from alias
                   5647: 
                   5648: sub get_symb_from_alias {
                   5649:     my $symb=shift;
                   5650:     my ($map,$resid,$url)=&decode_symb($symb);
                   5651: # Already is a symb
                   5652:     if ($url) { return $symb; }
                   5653: # Must be an alias
                   5654:     my $aliassymb='';
                   5655:     my %bighash;
1.620     albertel 5656:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5657:                             &GDBM_READER(),0640)) {
                   5658:         my $rid=$bighash{'mapalias_'.$symb};
                   5659: 	if ($rid) {
                   5660: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5661: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5662: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5663: 	}
                   5664:         untie %bighash;
                   5665:     }
                   5666:     return $aliassymb;
                   5667: }
                   5668: 
1.12      www      5669: # ----------------------------------------------------------------- Define Role
                   5670: 
                   5671: sub definerole {
                   5672:   if (allowed('mcr','/')) {
                   5673:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5674:     foreach my $role (split(':',$sysrole)) {
                   5675: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5676:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5677:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5678: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5679:                return "refused:s:$crole&$cqual"; 
                   5680:             }
                   5681:         }
1.191     harris41 5682:     }
1.800     albertel 5683:     foreach my $role (split(':',$domrole)) {
                   5684: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5685:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5686:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5687: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5688:                return "refused:d:$crole&$cqual"; 
                   5689:             }
                   5690:         }
1.191     harris41 5691:     }
1.800     albertel 5692:     foreach my $role (split(':',$courole)) {
                   5693: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5694:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5695:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5696: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5697:                return "refused:c:$crole&$cqual"; 
                   5698:             }
                   5699:         }
1.191     harris41 5700:     }
1.620     albertel 5701:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5702:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5703: 	        "rolesdef_$rolename=".
                   5704:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5705:     return reply($command,$env{'user.home'});
1.12      www      5706:   } else {
                   5707:     return 'refused';
                   5708:   }
1.105     harris41 5709: }
                   5710: 
                   5711: # ---------------- Make a metadata query against the network of library servers
                   5712: 
                   5713: sub metadata_query {
1.244     matthew  5714:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5715:     my %rhash;
1.845     albertel 5716:     my %libserv = &all_library();
1.244     matthew  5717:     my @server_list = (defined($server_array) ? @$server_array
                   5718:                                               : keys(%libserv) );
                   5719:     for my $server (@server_list) {
1.118     harris41 5720: 	unless ($custom or $customshow) {
                   5721: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5722: 	    $rhash{$server}=$reply;
                   5723: 	}
                   5724: 	else {
                   5725: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5726: 			     &escape($custom).':'.&escape($customshow),
                   5727: 			     $server);
                   5728: 	    $rhash{$server}=$reply;
                   5729: 	}
1.112     harris41 5730:     }
1.118     harris41 5731:     return \%rhash;
1.240     www      5732: }
                   5733: 
                   5734: # ----------------------------------------- Send log queries and wait for reply
                   5735: 
                   5736: sub log_query {
                   5737:     my ($uname,$udom,$query,%filters)=@_;
                   5738:     my $uhome=&homeserver($uname,$udom);
                   5739:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5740:     my $uhost=&hostname($uhome);
1.800     albertel 5741:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5742:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5743:                        $uhome);
1.479     albertel 5744:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5745:     return get_query_reply($queryid);
                   5746: }
                   5747: 
1.818     raeburn  5748: # -------------------------- Update MySQL table for portfolio file
                   5749: 
                   5750: sub update_portfolio_table {
1.821     raeburn  5751:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5752:     if ($group ne '') {
                   5753:         $file_name =~s /^\Q$group\E//;
                   5754:     }
1.818     raeburn  5755:     my $homeserver = &homeserver($uname,$udom);
                   5756:     my $queryid=
1.821     raeburn  5757:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5758:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5759:     my $reply = &get_query_reply($queryid);
                   5760:     return $reply;
                   5761: }
                   5762: 
1.899     raeburn  5763: # -------------------------- Update MySQL allusers table
                   5764: 
                   5765: sub update_allusers_table {
                   5766:     my ($uname,$udom,$names) = @_;
                   5767:     my $homeserver = &homeserver($uname,$udom);
                   5768:     my $queryid=
                   5769:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5770:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5771:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5772:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5773:                'generation='.&escape($names->{'generation'}).'%%'.
                   5774:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5775:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  5776:     return;
1.899     raeburn  5777: }
                   5778: 
1.508     raeburn  5779: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5780: 
                   5781: sub fetch_enrollment_query {
1.511     raeburn  5782:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5783:     my $homeserver;
1.547     raeburn  5784:     my $maxtries = 1;
1.508     raeburn  5785:     if ($context eq 'automated') {
                   5786:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5787:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5788:     } else {
                   5789:         $homeserver = &homeserver($cnum,$dom);
                   5790:     }
1.838     albertel 5791:     my $host=&hostname($homeserver);
1.506     raeburn  5792:     my $cmd = '';
1.1000    raeburn  5793:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5794:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5795:     }
                   5796:     $cmd =~ s/%%$//;
                   5797:     $cmd = &escape($cmd);
                   5798:     my $query = 'fetchenrollment';
1.620     albertel 5799:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5800:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5801:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5802:         return 'error: '.$queryid;
                   5803:     }
1.506     raeburn  5804:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5805:     my $tries = 1;
                   5806:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5807:         $reply = &get_query_reply($queryid);
                   5808:         $tries ++;
                   5809:     }
1.526     raeburn  5810:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5811:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5812:     } else {
1.901     albertel 5813:         my @responses = split(/:/,$reply);
1.515     raeburn  5814:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5815:             foreach my $line (@responses) {
                   5816:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5817:                 $$replyref{$key} = $value;
                   5818:             }
                   5819:         } else {
1.506     raeburn  5820:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5821:             foreach my $line (@responses) {
                   5822:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5823:                 $$replyref{$key} = $value;
                   5824:                 if ($value > 0) {
1.800     albertel 5825:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5826:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5827:                         my $destname = $pathname.'/'.$filename;
                   5828:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5829:                         if ($xml_classlist =~ /^error/) {
                   5830:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5831:                         } else {
1.506     raeburn  5832:                             if ( open(FILE,">$destname") ) {
                   5833:                                 print FILE &unescape($xml_classlist);
                   5834:                                 close(FILE);
1.526     raeburn  5835:                             } else {
                   5836:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5837:                             }
                   5838:                         }
                   5839:                     }
                   5840:                 }
                   5841:             }
                   5842:         }
                   5843:         return 'ok';
                   5844:     }
                   5845:     return 'error';
                   5846: }
                   5847: 
1.242     www      5848: sub get_query_reply {
                   5849:     my $queryid=shift;
1.240     www      5850:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5851:     my $reply='';
                   5852:     for (1..100) {
                   5853: 	sleep 2;
                   5854:         if (-e $replyfile.'.end') {
1.448     albertel 5855: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5856: 		$reply = join('',<$fh>);
                   5857: 		close($fh);
1.240     www      5858: 	   } else { return 'error: reply_file_error'; }
1.242     www      5859:            return &unescape($reply);
                   5860: 	}
1.240     www      5861:     }
1.242     www      5862:     return 'timeout:'.$queryid;
1.240     www      5863: }
                   5864: 
                   5865: sub courselog_query {
1.241     www      5866: #
                   5867: # possible filters:
                   5868: # url: url or symb
                   5869: # username
                   5870: # domain
                   5871: # action: view, submit, grade
                   5872: # start: timestamp
                   5873: # end: timestamp
                   5874: #
1.240     www      5875:     my (%filters)=@_;
1.620     albertel 5876:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5877:     if ($filters{'url'}) {
                   5878: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5879:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5880:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5881:     }
1.620     albertel 5882:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5883:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5884:     return &log_query($cname,$cdom,'courselog',%filters);
                   5885: }
                   5886: 
                   5887: sub userlog_query {
1.858     raeburn  5888: #
                   5889: # possible filters:
                   5890: # action: log check role
                   5891: # start: timestamp
                   5892: # end: timestamp
                   5893: #
1.240     www      5894:     my ($uname,$udom,%filters)=@_;
                   5895:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5896: }
                   5897: 
1.506     raeburn  5898: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5899: 
                   5900: sub auto_run {
1.508     raeburn  5901:     my ($cnum,$cdom) = @_;
1.876     raeburn  5902:     my $response = 0;
                   5903:     my $settings;
                   5904:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5905:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5906:         $settings = $domconfig{'autoenroll'};
                   5907:         if ($settings->{'run'} eq '1') {
                   5908:             $response = 1;
                   5909:         }
                   5910:     } else {
1.934     raeburn  5911:         my $homeserver;
                   5912:         if (&is_course($cdom,$cnum)) {
                   5913:             $homeserver = &homeserver($cnum,$cdom);
                   5914:         } else {
                   5915:             $homeserver = &domain($cdom,'primary');
                   5916:         }
                   5917:         if ($homeserver ne 'no_host') {
                   5918:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5919:         }
1.876     raeburn  5920:     }
1.506     raeburn  5921:     return $response;
                   5922: }
1.776     albertel 5923: 
1.506     raeburn  5924: sub auto_get_sections {
1.508     raeburn  5925:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5926:     my $homeserver;
                   5927:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5928:         $homeserver = &homeserver($cnum,$cdom);
                   5929:     }
                   5930:     if (!defined($homeserver)) { 
                   5931:         if ($cdom =~ /^$match_domain$/) {
                   5932:             $homeserver = &domain($cdom,'primary');
                   5933:         }
                   5934:     }
                   5935:     my @secs;
                   5936:     if (defined($homeserver)) {
                   5937:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5938:         unless ($response eq 'refused') {
                   5939:             @secs = split(/:/,$response);
                   5940:         }
1.506     raeburn  5941:     }
                   5942:     return @secs;
                   5943: }
1.776     albertel 5944: 
1.506     raeburn  5945: sub auto_new_course {
1.508     raeburn  5946:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5947:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5948:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5949:     return $response;
                   5950: }
1.776     albertel 5951: 
1.506     raeburn  5952: sub auto_validate_courseID {
1.508     raeburn  5953:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5954:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5955:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5956:     return $response;
                   5957: }
1.776     albertel 5958: 
1.1007    raeburn  5959: sub auto_validate_instcode {
1.1020    raeburn  5960:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  5961:     my ($homeserver,$response);
                   5962:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5963:         $homeserver = &homeserver($cnum,$cdom);
                   5964:     }
                   5965:     if (!defined($homeserver)) {
                   5966:         if ($cdom =~ /^$match_domain$/) {
                   5967:             $homeserver = &domain($cdom,'primary');
                   5968:         }
                   5969:     }
1.1065    raeburn  5970:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   5971:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  5972:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   5973:     return ($outcome,$description);
1.1007    raeburn  5974: }
                   5975: 
1.506     raeburn  5976: sub auto_create_password {
1.873     raeburn  5977:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5978:     my ($homeserver,$response);
1.506     raeburn  5979:     my $create_passwd = 0;
                   5980:     my $authchk = '';
1.873     raeburn  5981:     if ($udom =~ /^$match_domain$/) {
                   5982:         $homeserver = &domain($udom,'primary');
                   5983:     }
                   5984:     if ($homeserver eq '') {
                   5985:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5986:             $homeserver = &homeserver($cnum,$cdom);
                   5987:         }
                   5988:     }
                   5989:     if ($homeserver eq '') {
                   5990:         $authchk = 'nodomain';
1.506     raeburn  5991:     } else {
1.873     raeburn  5992:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5993:         if ($response eq 'refused') {
                   5994:             $authchk = 'refused';
                   5995:         } else {
1.901     albertel 5996:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5997:         }
1.506     raeburn  5998:     }
                   5999:     return ($authparam,$create_passwd,$authchk);
                   6000: }
                   6001: 
1.706     raeburn  6002: sub auto_photo_permission {
                   6003:     my ($cnum,$cdom,$students) = @_;
                   6004:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6005:     my ($outcome,$perm_reqd,$conditions) = 
                   6006: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6007:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6008: 	return (undef,undef);
                   6009:     }
1.706     raeburn  6010:     return ($outcome,$perm_reqd,$conditions);
                   6011: }
                   6012: 
                   6013: sub auto_checkphotos {
                   6014:     my ($uname,$udom,$pid) = @_;
                   6015:     my $homeserver = &homeserver($uname,$udom);
                   6016:     my ($result,$resulttype);
                   6017:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6018: 				   &escape($uname).':'.&escape($pid),
                   6019: 				   $homeserver));
1.709     albertel 6020:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6021: 	return (undef,undef);
                   6022:     }
1.706     raeburn  6023:     if ($outcome) {
                   6024:         ($result,$resulttype) = split(/:/,$outcome);
                   6025:     } 
                   6026:     return ($result,$resulttype);
                   6027: }
                   6028: 
                   6029: sub auto_photochoice {
                   6030:     my ($cnum,$cdom) = @_;
                   6031:     my $homeserver = &homeserver($cnum,$cdom);
                   6032:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6033: 						       &escape($cdom),
                   6034: 						       $homeserver)));
1.709     albertel 6035:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6036: 	return (undef,undef);
                   6037:     }
1.706     raeburn  6038:     return ($update,$comment);
                   6039: }
                   6040: 
                   6041: sub auto_photoupdate {
                   6042:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6043:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6044:     my $host=&hostname($homeserver);
1.706     raeburn  6045:     my $cmd = '';
                   6046:     my $maxtries = 1;
1.800     albertel 6047:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6048:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6049:     }
                   6050:     $cmd =~ s/%%$//;
                   6051:     $cmd = &escape($cmd);
                   6052:     my $query = 'institutionalphotos';
                   6053:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6054:     unless ($queryid=~/^\Q$host\E\_/) {
                   6055:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6056:         return 'error: '.$queryid;
                   6057:     }
                   6058:     my $reply = &get_query_reply($queryid);
                   6059:     my $tries = 1;
                   6060:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6061:         $reply = &get_query_reply($queryid);
                   6062:         $tries ++;
                   6063:     }
                   6064:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6065:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6066:     } else {
                   6067:         my @responses = split(/:/,$reply);
                   6068:         my $outcome = shift(@responses); 
                   6069:         foreach my $item (@responses) {
                   6070:             my ($key,$value) = split(/=/,$item);
                   6071:             $$photo{$key} = $value;
                   6072:         }
                   6073:         return $outcome;
                   6074:     }
                   6075:     return 'error';
                   6076: }
                   6077: 
1.521     raeburn  6078: sub auto_instcode_format {
1.793     albertel 6079:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6080: 	$cat_order) = @_;
1.521     raeburn  6081:     my $courses = '';
1.772     raeburn  6082:     my @homeservers;
1.521     raeburn  6083:     if ($caller eq 'global') {
1.841     albertel 6084: 	my %servers = &get_servers($codedom,'library');
                   6085: 	foreach my $tryserver (keys(%servers)) {
                   6086: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6087: 		push(@homeservers,$tryserver);
                   6088: 	    }
1.584     raeburn  6089:         }
1.1022    raeburn  6090:     } elsif ($caller eq 'requests') {
                   6091:         if ($codedom =~ /^$match_domain$/) {
                   6092:             my $chome = &domain($codedom,'primary');
                   6093:             unless ($chome eq 'no_host') {
                   6094:                 push(@homeservers,$chome);
                   6095:             }
                   6096:         }
1.521     raeburn  6097:     } else {
1.772     raeburn  6098:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6099:     }
1.793     albertel 6100:     foreach my $code (keys(%{$instcodes})) {
                   6101:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6102:     }
                   6103:     chop($courses);
1.772     raeburn  6104:     my $ok_response = 0;
                   6105:     my $response;
                   6106:     while (@homeservers > 0 && $ok_response == 0) {
                   6107:         my $server = shift(@homeservers); 
                   6108:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6109:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6110:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6111: 		split(/:/,$response);
1.772     raeburn  6112:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6113:             push(@{$codetitles},&str2array($codetitles_str));
                   6114:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6115:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6116:             $ok_response = 1;
                   6117:         }
                   6118:     }
                   6119:     if ($ok_response) {
1.521     raeburn  6120:         return 'ok';
1.772     raeburn  6121:     } else {
                   6122:         return $response;
1.521     raeburn  6123:     }
                   6124: }
                   6125: 
1.792     raeburn  6126: sub auto_instcode_defaults {
                   6127:     my ($domain,$returnhash,$code_order) = @_;
                   6128:     my @homeservers;
1.841     albertel 6129: 
                   6130:     my %servers = &get_servers($domain,'library');
                   6131:     foreach my $tryserver (keys(%servers)) {
                   6132: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6133: 	    push(@homeservers,$tryserver);
                   6134: 	}
1.792     raeburn  6135:     }
1.841     albertel 6136: 
1.792     raeburn  6137:     my $response;
1.841     albertel 6138:     foreach my $server (@homeservers) {
1.792     raeburn  6139:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6140:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6141: 	
                   6142: 	foreach my $pair (split(/\&/,$response)) {
                   6143: 	    my ($name,$value)=split(/\=/,$pair);
                   6144: 	    if ($name eq 'code_order') {
                   6145: 		@{$code_order} = split(/\&/,&unescape($value));
                   6146: 	    } else {
                   6147: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6148: 	    }
                   6149: 	}
                   6150: 	return 'ok';
1.792     raeburn  6151:     }
1.841     albertel 6152: 
                   6153:     return $response;
1.1003    raeburn  6154: }
                   6155: 
                   6156: sub auto_possible_instcodes {
1.1007    raeburn  6157:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6158:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6159:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6160:         return;
                   6161:     }
1.1003    raeburn  6162:     my (@homeservers,$uhome);
                   6163:     if (defined(&domain($domain,'primary'))) {
                   6164:         $uhome=&domain($domain,'primary');
                   6165:         push(@homeservers,&domain($domain,'primary'));
                   6166:     } else {
                   6167:         my %servers = &get_servers($domain,'library');
                   6168:         foreach my $tryserver (keys(%servers)) {
                   6169:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6170:                 push(@homeservers,$tryserver);
                   6171:             }
                   6172:         }
                   6173:     }
                   6174:     my $response;
                   6175:     foreach my $server (@homeservers) {
                   6176:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6177:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6178:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6179:             split(':',$response);
                   6180:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6181:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6182:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6183:             my ($name,$value)=split('=',$item);
                   6184:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6185:         }
                   6186:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6187:             my ($name,$value)=split('=',$item);
                   6188:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6189:         }
                   6190:         return 'ok';
                   6191:     }
                   6192:     return $response;
                   6193: }
1.792     raeburn  6194: 
1.1010    raeburn  6195: sub auto_courserequest_checks {
                   6196:     my ($dom) = @_;
1.1020    raeburn  6197:     my ($homeserver,%validations);
                   6198:     if ($dom =~ /^$match_domain$/) {
                   6199:         $homeserver = &domain($dom,'primary');
                   6200:     }
                   6201:     unless ($homeserver eq 'no_host') {
                   6202:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6203:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6204:             my @items = split(/&/,$response);
                   6205:             foreach my $item (@items) {
                   6206:                 my ($key,$value) = split('=',$item);
                   6207:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6208:             }
                   6209:         }
                   6210:     }
1.1010    raeburn  6211:     return %validations; 
                   6212: }
                   6213: 
1.1020    raeburn  6214: sub auto_courserequest_validation {
                   6215:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6216:     my ($homeserver,$response);
                   6217:     if ($dom =~ /^$match_domain$/) {
                   6218:         $homeserver = &domain($dom,'primary');
                   6219:     }
                   6220:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6221:           
1.1020    raeburn  6222:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6223:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6224:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6225:                                     $homeserver));
                   6226:     }
                   6227:     return $response;
                   6228: }
                   6229: 
1.777     albertel 6230: sub auto_validate_class_sec {
1.918     raeburn  6231:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6232:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6233:     my $ownerlist;
                   6234:     if (ref($owners) eq 'ARRAY') {
                   6235:         $ownerlist = join(',',@{$owners});
                   6236:     } else {
                   6237:         $ownerlist = $owners;
                   6238:     }
1.773     raeburn  6239:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6240:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6241:     return $response;
                   6242: }
                   6243: 
1.679     raeburn  6244: # ------------------------------------------------------- Course Group routines
                   6245: 
                   6246: sub get_coursegroups {
1.809     raeburn  6247:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6248:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6249: }
                   6250: 
1.679     raeburn  6251: sub modify_coursegroup {
                   6252:     my ($cdom,$cnum,$groupsettings) = @_;
                   6253:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6254: }
                   6255: 
1.809     raeburn  6256: sub toggle_coursegroup_status {
                   6257:     my ($cdom,$cnum,$group,$action) = @_;
                   6258:     my ($from_namespace,$to_namespace);
                   6259:     if ($action eq 'delete') {
                   6260:         $from_namespace = 'coursegroups';
                   6261:         $to_namespace = 'deleted_groups';
                   6262:     } else {
                   6263:         $from_namespace = 'deleted_groups';
                   6264:         $to_namespace = 'coursegroups';
                   6265:     }
                   6266:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6267:     if (my $tmp = &error(%curr_group)) {
                   6268:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6269:         return ('read error',$tmp);
                   6270:     } else {
                   6271:         my %savedsettings = %curr_group; 
1.809     raeburn  6272:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6273:         my $deloutcome;
                   6274:         if ($result eq 'ok') {
1.809     raeburn  6275:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6276:         } else {
                   6277:             return ('write error',$result);
                   6278:         }
                   6279:         if ($deloutcome eq 'ok') {
                   6280:             return 'ok';
                   6281:         } else {
                   6282:             return ('delete error',$deloutcome);
                   6283:         }
                   6284:     }
                   6285: }
                   6286: 
1.679     raeburn  6287: sub modify_group_roles {
1.957     raeburn  6288:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6289:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6290:     my $role = 'gr/'.&escape($userprivs);
                   6291:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6292:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6293:     if ($result eq 'ok') {
                   6294:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6295:     }
1.679     raeburn  6296:     return $result;
                   6297: }
                   6298: 
                   6299: sub modify_coursegroup_membership {
                   6300:     my ($cdom,$cnum,$membership) = @_;
                   6301:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6302:     return $result;
                   6303: }
                   6304: 
1.682     raeburn  6305: sub get_active_groups {
                   6306:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6307:     my $now = time;
                   6308:     my %groups = ();
                   6309:     foreach my $key (keys(%env)) {
1.811     albertel 6310:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6311:             my ($start,$end) = split(/\./,$env{$key});
                   6312:             if (($end!=0) && ($end<$now)) { next; }
                   6313:             if (($start!=0) && ($start>$now)) { next; }
                   6314:             if ($1 eq $cdom && $2 eq $cnum) {
                   6315:                 $groups{$3} = $env{$key} ;
                   6316:             }
                   6317:         }
                   6318:     }
                   6319:     return %groups;
                   6320: }
                   6321: 
1.683     raeburn  6322: sub get_group_membership {
                   6323:     my ($cdom,$cnum,$group) = @_;
                   6324:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6325: }
                   6326: 
                   6327: sub get_users_groups {
                   6328:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6329:     my @usersgroups;
1.683     raeburn  6330:     my $cachetime=1800;
                   6331: 
                   6332:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6333:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6334:     if (defined($cached)) {
1.734     albertel 6335:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6336:     } else {  
                   6337:         $grouplist = '';
1.816     raeburn  6338:         my $courseurl = &courseid_to_courseurl($courseid);
                   6339:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  6340:         my $access_end = $env{'course.'.$courseid.
                   6341:                               '.default_enrollment_end_date'};
                   6342:         my $now = time;
                   6343:         foreach my $key (keys(%roleshash)) {
                   6344:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6345:                 my $group = $1;
                   6346:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6347:                     my $start = $2;
                   6348:                     my $end = $1;
                   6349:                     if ($start == -1) { next; } # deleted from group
                   6350:                     if (($start!=0) && ($start>$now)) { next; }
                   6351:                     if (($end!=0) && ($end<$now)) {
                   6352:                         if ($access_end && $access_end < $now) {
                   6353:                             if ($access_end - $end < 86400) {
                   6354:                                 push(@usersgroups,$group);
1.733     raeburn  6355:                             }
                   6356:                         }
1.817     raeburn  6357:                         next;
1.733     raeburn  6358:                     }
1.817     raeburn  6359:                     push(@usersgroups,$group);
1.683     raeburn  6360:                 }
                   6361:             }
                   6362:         }
1.817     raeburn  6363:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6364:         $grouplist = join(':',@usersgroups);
                   6365:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6366:     }
1.733     raeburn  6367:     return @usersgroups;
1.683     raeburn  6368: }
                   6369: 
                   6370: sub devalidate_getgroups_cache {
                   6371:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6372:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6373: 
1.683     raeburn  6374:     my $hashid="$udom:$uname:$courseid";
                   6375:     &devalidate_cache_new('getgroups',$hashid);
                   6376: }
                   6377: 
1.12      www      6378: # ------------------------------------------------------------------ Plain Text
                   6379: 
                   6380: sub plaintext {
1.988     raeburn  6381:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6382:     if ($short =~ m{^cr/}) {
1.758     albertel 6383: 	return (split('/',$short))[-1];
                   6384:     }
1.742     raeburn  6385:     if (!defined($cid)) {
                   6386:         $cid = $env{'request.course.id'};
                   6387:     }
                   6388:     my %rolenames = (
1.1008    raeburn  6389:                       Course    => 'std',
                   6390:                       Community => 'alt1',
1.742     raeburn  6391:                     );
1.1037    raeburn  6392:     if ($cid ne '') {
                   6393:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6394:             unless ($forcedefault) {
                   6395:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6396:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6397:                 return &Apache::lonlocal::mt($roletext);
                   6398:             }
                   6399:         }
                   6400:     }
                   6401:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6402:         (defined($rolenames{$type})) && 
                   6403:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6404:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6405:     } elsif ($cid ne '') {
                   6406:         my $crstype = $env{'course.'.$cid.'.type'};
                   6407:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6408:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6409:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6410:         }
1.742     raeburn  6411:     }
1.1037    raeburn  6412:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6413: }
                   6414: 
                   6415: # ----------------------------------------------------------------- Assign Role
                   6416: 
                   6417: sub assignrole {
1.957     raeburn  6418:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6419:         $context)=@_;
1.21      www      6420:     my $mrole;
                   6421:     if ($role =~ /^cr\//) {
1.393     www      6422:         my $cwosec=$url;
1.811     albertel 6423:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6424: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6425:            my $refused = 1;
                   6426:            if ($context eq 'requestcourses') {
                   6427:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6428:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6429:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6430:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6431:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6432:                            if ($crsenv{'internal.courseowner'} eq
                   6433:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6434:                                $refused = '';
                   6435:                            }
                   6436:                        }
                   6437:                    }
                   6438:                }
                   6439:            }
                   6440:            if ($refused) {
                   6441:                &logthis('Refused custom assignrole: '.
                   6442:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6443:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6444:                return 'refused';
                   6445:            }
1.104     www      6446:         }
1.21      www      6447:         $mrole='cr';
1.678     raeburn  6448:     } elsif ($role =~ /^gr\//) {
                   6449:         my $cwogrp=$url;
1.811     albertel 6450:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6451:         unless (&allowed('mdg',$cwogrp)) {
                   6452:             &logthis('Refused group assignrole: '.
                   6453:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6454:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6455:             return 'refused';
                   6456:         }
                   6457:         $mrole='gr';
1.21      www      6458:     } else {
1.82      www      6459:         my $cwosec=$url;
1.811     albertel 6460:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6461:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6462:             my $refused;
                   6463:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6464:                 if (!(&allowed('c'.$role,$url))) {
                   6465:                     $refused = 1;
                   6466:                 }
                   6467:             } else {
                   6468:                 $refused = 1;
                   6469:             }
1.947     raeburn  6470:             if ($refused) {
1.1045    raeburn  6471:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6472:                 if (!$selfenroll && $context eq 'course') {
                   6473:                     my %crsenv;
                   6474:                     if ($role eq 'cc' || $role eq 'co') {
                   6475:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6476:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6477:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6478:                                 if ($crsenv{'internal.courseowner'} eq 
                   6479:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6480:                                     $refused = '';
                   6481:                                 }
                   6482:                             }
                   6483:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6484:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6485:                                 if ($crsenv{'internal.courseowner'} eq 
                   6486:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6487:                                     $refused = '';
                   6488:                                 }
                   6489:                             }
                   6490:                         }
                   6491:                     }
                   6492:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6493:                     $refused = '';
1.1017    raeburn  6494:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6495:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6496:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6497:                         my $wrongcc;
                   6498:                         if ($cnum =~ /^$match_community$/) {
                   6499:                             $wrongcc = 1 if ($role eq 'cc');
                   6500:                         } else {
                   6501:                             $wrongcc = 1 if ($role eq 'co');
                   6502:                         }
                   6503:                         unless ($wrongcc) {
                   6504:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6505:                             if ($crsenv{'internal.courseowner'} eq 
                   6506:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6507:                                 $refused = '';
                   6508:                             }
1.1017    raeburn  6509:                         }
                   6510:                     }
                   6511:                 }
                   6512:                 if ($refused) {
1.947     raeburn  6513:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6514:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6515: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6516:                     return 'refused';
                   6517:                 }
1.932     raeburn  6518:             }
1.104     www      6519:         }
1.21      www      6520:         $mrole=$role;
                   6521:     }
1.620     albertel 6522:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6523:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6524:     if ($end) { $command.='_'.$end; }
1.21      www      6525:     if ($start) {
                   6526: 	if ($end) { 
1.81      www      6527:            $command.='_'.$start; 
1.21      www      6528:         } else {
1.81      www      6529:            $command.='_0_'.$start;
1.21      www      6530:         }
                   6531:     }
1.739     raeburn  6532:     my $origstart = $start;
                   6533:     my $origend = $end;
1.957     raeburn  6534:     my $delflag;
1.357     www      6535: # actually delete
                   6536:     if ($deleteflag) {
1.373     www      6537: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6538: # modify command to delete the role
1.620     albertel 6539:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6540:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6541: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6542: # set start and finish to negative values for userrolelog
                   6543:            $start=-1;
                   6544:            $end=-1;
1.957     raeburn  6545:            $delflag = 1;
1.357     www      6546:         }
                   6547:     }
                   6548: # send command
1.349     www      6549:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6550: # log new user role if status is ok
1.349     www      6551:     if ($answer eq 'ok') {
1.663     raeburn  6552: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6553: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6554:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6555:         unless ($role =~ /^gr/) {
                   6556:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6557:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6558:         }
1.1053    raeburn  6559:         if ($role eq 'cc') {
                   6560:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6561:         }
1.349     www      6562:     }
                   6563:     return $answer;
1.169     harris41 6564: }
                   6565: 
1.1053    raeburn  6566: sub autoupdate_coowners {
                   6567:     my ($url,$end,$start,$uname,$udom) = @_;
                   6568:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6569:     if (($cdom ne '') && ($cnum ne '')) {
                   6570:         my $now = time;
                   6571:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6572:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6573:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6574:             my $instcode = $coursehash{'internal.coursecode'};
                   6575:             if ($instcode ne '') {
1.1056    raeburn  6576:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6577:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6578:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6579:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6580:                         if ($result eq 'valid') {
                   6581:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6582:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6583:                                     push(@newcoowners,$coowner);
                   6584:                                 }
                   6585:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6586:                                     push(@newcoowners,$uname.':'.$udom);
                   6587:                                 }
                   6588:                                 @newcoowners = sort(@newcoowners);
                   6589:                             } else {
                   6590:                                 push(@newcoowners,$uname.':'.$udom);
                   6591:                             }
                   6592:                         } else {
                   6593:                             if ($coursehash{'internal.co-owners'}) {
                   6594:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6595:                                     unless ($coowner eq $uname.':'.$udom) {
                   6596:                                         push(@newcoowners,$coowner);
                   6597:                                     }
                   6598:                                 }
                   6599:                                 unless (@newcoowners > 0) {
                   6600:                                     $delcoowners = 1;
                   6601:                                     $coowners = '';
                   6602:                                 }
                   6603:                             }
                   6604:                         }
                   6605:                         if (@newcoowners || $delcoowners) {
                   6606:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6607:                                             $delcoowners,@newcoowners);
                   6608:                         }
                   6609:                     }
                   6610:                 }
                   6611:             }
                   6612:         }
                   6613:     }
                   6614: }
                   6615: 
                   6616: sub store_coowners {
                   6617:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6618:     my $cid = $cdom.'_'.$cnum;
                   6619:     my ($coowners,$delresult,$putresult);
                   6620:     if (@newcoowners) {
                   6621:         $coowners = join(',',@newcoowners);
                   6622:         my %coownershash = (
                   6623:                             'internal.co-owners' => $coowners,
                   6624:                            );
                   6625:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6626:         if ($putresult eq 'ok') {
                   6627:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6628:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6629:             }
                   6630:         }
                   6631:     }
                   6632:     if ($delcoowners) {
                   6633:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6634:         if ($delresult eq 'ok') {
                   6635:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6636:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6637:             }
                   6638:         }
                   6639:     }
                   6640:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6641:         my %crsinfo =
                   6642:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6643:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6644:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6645:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6646:         }
                   6647:     }
                   6648: }
                   6649: 
1.169     harris41 6650: # -------------------------------------------------- Modify user authentication
1.197     www      6651: # Overrides without validation
                   6652: 
1.169     harris41 6653: sub modifyuserauth {
                   6654:     my ($udom,$uname,$umode,$upass)=@_;
                   6655:     my $uhome=&homeserver($uname,$udom);
1.197     www      6656:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6657:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6658:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6659:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6660:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6661: 		     &escape($upass),$uhome);
1.620     albertel 6662:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6663:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6664:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6665:     &log($udom,,$uname,$uhome,
1.620     albertel 6666:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6667:                                      $env{'user.name'}.', '.$umode.
1.197     www      6668:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6669:     unless ($reply eq 'ok') {
1.197     www      6670:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6671: 	return 'error: '.$reply;
                   6672:     }   
1.170     harris41 6673:     return 'ok';
1.80      www      6674: }
                   6675: 
1.81      www      6676: # --------------------------------------------------------------- Modify a user
1.80      www      6677: 
1.81      www      6678: sub modifyuser {
1.206     matthew  6679:     my ($udom,    $uname, $uid,
                   6680:         $umode,   $upass, $first,
                   6681:         $middle,  $last,  $gene,
1.1058    raeburn  6682:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6683:     $udom= &LONCAPA::clean_domain($udom);
                   6684:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6685:     my $showcandelete = 'none';
                   6686:     if (ref($candelete) eq 'ARRAY') {
                   6687:         if (@{$candelete} > 0) {
                   6688:             $showcandelete = join(', ',@{$candelete});
                   6689:         }
                   6690:     }
1.81      www      6691:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6692:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6693: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6694:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6695:                                      ' desiredhome not specified'). 
1.620     albertel 6696:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6697:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6698:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6699:     my $newuser;
                   6700:     if ($uhome eq 'no_host') {
                   6701:         $newuser = 1;
                   6702:     }
1.80      www      6703: # ----------------------------------------------------------------- Create User
1.406     albertel 6704:     if (($uhome eq 'no_host') && 
                   6705: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6706:         my $unhome='';
1.844     albertel 6707:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6708:             $unhome = $desiredhome;
1.620     albertel 6709: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6710: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6711:         } else { # load balancing routine for determining $unhome
1.81      www      6712:             my $loadm=10000000;
1.841     albertel 6713: 	    my %servers = &get_servers($udom,'library');
                   6714: 	    foreach my $tryserver (keys(%servers)) {
                   6715: 		my $answer=reply('load',$tryserver);
                   6716: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6717: 		    $loadm=$answer;
                   6718: 		    $unhome=$tryserver;
                   6719: 		}
1.80      www      6720: 	    }
                   6721:         }
                   6722:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6723: 	    return 'error: unable to find a home server for '.$uname.
                   6724:                    ' in domain '.$udom;
1.80      www      6725:         }
                   6726:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6727:                          &escape($upass),$unhome);
                   6728: 	unless ($reply eq 'ok') {
                   6729:             return 'error: '.$reply;
                   6730:         }   
1.230     stredwic 6731:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6732:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6733: 	    return 'error: unable verify users home machine.';
1.80      www      6734:         }
1.209     matthew  6735:     }   # End of creation of new user
1.80      www      6736: # ---------------------------------------------------------------------- Add ID
                   6737:     if ($uid) {
                   6738:        $uid=~tr/A-Z/a-z/;
                   6739:        my %uidhash=&idrget($udom,$uname);
1.196     www      6740:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6741:          && (!$forceid)) {
1.80      www      6742: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6743: 	      return 'error: user id "'.$uid.'" does not match '.
                   6744:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6745:           }
                   6746:        } else {
                   6747: 	  &idput($udom,($uname => $uid));
                   6748:        }
                   6749:     }
                   6750: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6751:     my @tmp=&get('environment',
1.899     raeburn  6752: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6753:                     'permanentemail','inststatus'],
1.134     albertel 6754: 		   $udom,$uname);
1.1075    raeburn  6755:     my (%names,%oldnames);
1.313     matthew  6756:     if ($tmp[0] =~ m/^error:.*/) { 
                   6757:         %names=(); 
                   6758:     } else {
                   6759:         %names = @tmp;
1.1075    raeburn  6760:         %oldnames = %names;
1.313     matthew  6761:     }
1.388     www      6762: #
1.1058    raeburn  6763: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6764: # of users did not contain them), do not overwrite existing values
                   6765: # unless field is in $candelete array ref.  
                   6766: #
                   6767: 
                   6768:     my @fields = ('firstname','middlename','lastname','generation',
                   6769:                   'permanentemail','id');
                   6770:     my %newvalues;
                   6771:     if (ref($candelete) eq 'ARRAY') {
                   6772:         foreach my $field (@fields) {
                   6773:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6774:                 if ($field eq 'firstname') {
                   6775:                     $names{$field} = $first;
                   6776:                 } elsif ($field eq 'middlename') {
                   6777:                     $names{$field} = $middle;
                   6778:                 } elsif ($field eq 'lastname') {
                   6779:                     $names{$field} = $last;
                   6780:                 } elsif ($field eq 'generation') { 
                   6781:                     $names{$field} = $gene;
                   6782:                 } elsif ($field eq 'permanentemail') {
                   6783:                     $names{$field} = $email;
                   6784:                 } elsif ($field eq 'id') {
                   6785:                     $names{$field}  = $uid;
                   6786:                 }
                   6787:             }
                   6788:         }
                   6789:     }
1.388     www      6790:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6791:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6792:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6793:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6794:     if ($email) {
                   6795:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6796:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6797:     }
1.899     raeburn  6798:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6799:     if (defined($inststatus)) {
                   6800:         $names{'inststatus'} = '';
                   6801:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6802:         if (ref($usertypes) eq 'HASH') {
                   6803:             my @okstatuses; 
                   6804:             foreach my $item (split(/:/,$inststatus)) {
                   6805:                 if (defined($usertypes->{$item})) {
                   6806:                     push(@okstatuses,$item);  
                   6807:                 }
                   6808:             }
                   6809:             if (@okstatuses) {
                   6810:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6811:             }
                   6812:         }
                   6813:     }
1.1075    raeburn  6814:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6815:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  6816:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6817:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6818:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6819:     } else {
                   6820:         $logmsg .= ' during self creation';
                   6821:     }
1.1075    raeburn  6822:     my $changed;
                   6823:     if ($newuser) {
                   6824:         $changed = 1;
                   6825:     } else {
                   6826:         foreach my $field (@fields) {
                   6827:             if ($names{$field} ne $oldnames{$field}) {
                   6828:                 $changed = 1;
                   6829:                 last;
                   6830:             }
                   6831:         }
                   6832:     }
                   6833:     unless ($changed) {
                   6834:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6835:         &logthis($logmsg);
                   6836:         return 'ok';
                   6837:     }
                   6838:     my $reply = &put('environment', \%names, $udom,$uname);
                   6839:     if ($reply ne 'ok') { 
                   6840:         return 'error: '.$reply;
                   6841:     }
                   6842:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6843:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6844:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6845:     &logthis($logmsg);
1.134     albertel 6846:     return 'ok';
1.80      www      6847: }
                   6848: 
1.81      www      6849: # -------------------------------------------------------------- Modify student
1.80      www      6850: 
1.81      www      6851: sub modifystudent {
                   6852:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6853:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6854:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6855:     if (!$cid) {
1.620     albertel 6856: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6857: 	    return 'not_in_class';
                   6858: 	}
1.80      www      6859:     }
                   6860: # --------------------------------------------------------------- Make the user
1.81      www      6861:     my $reply=&modifyuser
1.209     matthew  6862: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6863:          $desiredhome,$email,$inststatus);
1.80      www      6864:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6865:     # This will cause &modify_student_enrollment to get the uid from the
                   6866:     # students environment
                   6867:     $uid = undef if (!$forceid);
1.455     albertel 6868:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6869: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6870:     return $reply;
                   6871: }
                   6872: 
                   6873: sub modify_student_enrollment {
1.957     raeburn  6874:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6875:     my ($cdom,$cnum,$chome);
                   6876:     if (!$cid) {
1.620     albertel 6877: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6878: 	    return 'not_in_class';
                   6879: 	}
1.620     albertel 6880: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6881: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6882:     } else {
                   6883: 	($cdom,$cnum)=split(/_/,$cid);
                   6884:     }
1.620     albertel 6885:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6886:     if (!$chome) {
1.457     raeburn  6887: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6888:     }
1.455     albertel 6889:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6890:     # Make sure the user exists
1.81      www      6891:     my $uhome=&homeserver($uname,$udom);
                   6892:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6893: 	return 'error: no such user';
                   6894:     }
1.297     matthew  6895:     # Get student data if we were not given enough information
                   6896:     if (!defined($first)  || $first  eq '' || 
                   6897:         !defined($last)   || $last   eq '' || 
                   6898:         !defined($uid)    || $uid    eq '' || 
                   6899:         !defined($middle) || $middle eq '' || 
                   6900:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6901:         # They did not supply us with enough data to enroll the student, so
                   6902:         # we need to pick up more information.
1.297     matthew  6903:         my %tmp = &get('environment',
1.294     matthew  6904:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6905:                        ,$udom,$uname);
                   6906: 
1.800     albertel 6907:         #foreach my $key (keys(%tmp)) {
                   6908:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6909:         #}
1.294     matthew  6910:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6911:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6912:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6913:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6914:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6915:     }
1.556     albertel 6916:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6917:     my $reply=cput('classlist',
                   6918: 		   {"$uname:$udom" => 
1.515     raeburn  6919: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6920: 		   $cdom,$cnum);
1.81      www      6921:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6922: 	return 'error: '.$reply;
1.652     albertel 6923:     } else {
                   6924: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6925:     }
1.297     matthew  6926:     # Add student role to user
1.83      www      6927:     my $uurl='/'.$cid;
1.81      www      6928:     $uurl=~s/\_/\//g;
                   6929:     if ($usec) {
                   6930: 	$uurl.='/'.$usec;
                   6931:     }
1.957     raeburn  6932:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6933: }
                   6934: 
1.556     albertel 6935: sub format_name {
                   6936:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6937:     my $name;
                   6938:     if ($first ne 'lastname') {
                   6939: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6940:     } else {
                   6941: 	if ($lastname=~/\S/) {
                   6942: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6943: 	    $name=~s/\s+,/,/;
                   6944: 	} else {
                   6945: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6946: 	}
                   6947:     }
                   6948:     $name=~s/^\s+//;
                   6949:     $name=~s/\s+$//;
                   6950:     $name=~s/\s+/ /g;
                   6951:     return $name;
                   6952: }
                   6953: 
1.84      www      6954: # ------------------------------------------------- Write to course preferences
                   6955: 
                   6956: sub writecoursepref {
                   6957:     my ($courseid,%prefs)=@_;
                   6958:     $courseid=~s/^\///;
                   6959:     $courseid=~s/\_/\//g;
                   6960:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6961:     my $chome=homeserver($cnum,$cdomain);
                   6962:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6963: 	return 'error: no such course';
                   6964:     }
                   6965:     my $cstring='';
1.800     albertel 6966:     foreach my $pref (keys(%prefs)) {
                   6967: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6968:     }
1.84      www      6969:     $cstring=~s/\&$//;
                   6970:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6971: }
                   6972: 
                   6973: # ---------------------------------------------------------- Make/modify course
                   6974: 
                   6975: sub createcourse {
1.741     raeburn  6976:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  6977:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      6978:     $url=&declutter($url);
                   6979:     my $cid='';
1.1028    raeburn  6980:     if ($context eq 'requestcourses') {
                   6981:         my $can_create = 0;
                   6982:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   6983:         if ($udom eq $ownerdom) {
                   6984:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   6985:                                   $context)) {
                   6986:                 $can_create = 1;
                   6987:             }
                   6988:         } else {
                   6989:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   6990:                                            $category);
                   6991:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   6992:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   6993:                 if (@curr > 0) {
                   6994:                     my @options = qw(approval validate autolimit);
                   6995:                     my $optregex = join('|',@options);
                   6996:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   6997:                         $can_create = 1;
                   6998:                     }
                   6999:                 }
                   7000:             }
                   7001:         }
                   7002:         if ($can_create) {
                   7003:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7004:                 unless (&allowed('ccc',$udom)) {
                   7005:                     return 'refused'; 
                   7006:                 }
1.1017    raeburn  7007:             }
                   7008:         } else {
                   7009:             return 'refused';
                   7010:         }
1.1028    raeburn  7011:     } elsif (!&allowed('ccc',$udom)) {
                   7012:         return 'refused';
1.84      www      7013:     }
1.1011    raeburn  7014: # --------------------------------------------------------------- Get Unique ID
                   7015:     my $uname;
                   7016:     if ($cnum =~ /^$match_courseid$/) {
                   7017:         my $chome=&homeserver($cnum,$udom,'true');
                   7018:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7019:             $uname = $cnum;
                   7020:         } else {
1.1038    raeburn  7021:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7022:         }
                   7023:     } else {
1.1038    raeburn  7024:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7025:     }
                   7026:     return $uname if ($uname =~ /^error/);
                   7027: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7028:     if (!defined($course_server)) {
                   7029:         if (defined(&domain($udom,'primary'))) {
                   7030:             $course_server = &domain($udom,'primary');
                   7031:         } else {
                   7032:             $course_server = $env{'user.home'}; 
                   7033:         }
                   7034:     }
                   7035:     my %host_servers =
                   7036:         &Apache::lonnet::get_servers($udom,'library');
                   7037:     unless ($host_servers{$course_server}) {
                   7038:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7039:     }
1.84      www      7040: # ------------------------------------------------------------- Make the course
                   7041:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7042:                       $course_server);
1.84      www      7043:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7044:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7045:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7046: 	return 'error: no such course';
                   7047:     }
1.271     www      7048: # ----------------------------------------------------------------- Course made
1.516     raeburn  7049: # log existence
1.1029    raeburn  7050:     my $now = time;
1.918     raeburn  7051:     my $newcourse = {
                   7052:                     $udom.'_'.$uname => {
1.921     raeburn  7053:                                      description => $description,
                   7054:                                      inst_code   => $inst_code,
                   7055:                                      owner       => $course_owner,
                   7056:                                      type        => $crstype,
1.1029    raeburn  7057:                                      creator     => $env{'user.name'}.':'.
                   7058:                                                     $env{'user.domain'},
                   7059:                                      created     => $now,
                   7060:                                      context     => $context,
1.918     raeburn  7061:                                                 },
                   7062:                     };
1.921     raeburn  7063:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7064: # set toplevel url
1.271     www      7065:     my $topurl=$url;
                   7066:     unless ($nonstandard) {
                   7067: # ------------------------------------------ For standard courses, make top url
                   7068:         my $mapurl=&clutter($url);
1.278     www      7069:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7070:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7071: <map>
                   7072: <resource id="1" type="start"></resource>
                   7073: <resource id="2" src="$mapurl"></resource>
                   7074: <resource id="3" type="finish"></resource>
                   7075: <link index="1" from="1" to="2"></link>
                   7076: <link index="2" from="2" to="3"></link>
                   7077: </map>
                   7078: ENDINITMAP
                   7079:         $topurl=&declutter(
1.638     albertel 7080:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7081:                           );
                   7082:     }
                   7083: # ----------------------------------------------------------- Write preferences
1.84      www      7084:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7085:                      ('description'              => $description,
                   7086:                       'url'                      => $topurl,
                   7087:                       'internal.creator'         => $env{'user.name'}.':'.
                   7088:                                                     $env{'user.domain'},
                   7089:                       'internal.created'         => $now,
                   7090:                       'internal.creationcontext' => $context)
                   7091:                     );
1.84      www      7092:     return '/'.$udom.'/'.$uname;
                   7093: }
                   7094: 
1.1011    raeburn  7095: # ------------------------------------------------------------------- Create ID
                   7096: sub generate_coursenum {
1.1038    raeburn  7097:     my ($udom,$crstype) = @_;
1.1011    raeburn  7098:     my $domdesc = &domain($udom);
                   7099:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7100:     my $first;
                   7101:     if ($crstype eq 'Community') {
                   7102:         $first = '0';
                   7103:     } else {
                   7104:         $first = int(1+rand(9)); 
                   7105:     } 
                   7106:     my $uname=$first.
1.1011    raeburn  7107:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7108:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7109:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7110: # ----------------------------------------------- Make sure that does not exist
                   7111:     my $uhome=&homeserver($uname,$udom,'true');
                   7112:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7113:         if ($crstype eq 'Community') {
                   7114:             $first = '0';
                   7115:         } else {
                   7116:             $first = int(1+rand(9));
                   7117:         }
                   7118:         $uname=$first.
1.1011    raeburn  7119:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7120:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7121:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7122:         $uhome=&homeserver($uname,$udom,'true');
                   7123:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7124:             return 'error: unable to generate unique course-ID';
                   7125:         }
                   7126:     }
                   7127:     return $uname;
                   7128: }
                   7129: 
1.813     albertel 7130: sub is_course {
                   7131:     my ($cdom,$cnum) = @_;
                   7132:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7133: 				undef,'.');
1.813     albertel 7134:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7135:         return 1;
                   7136:     }
                   7137:     return 0;
                   7138: }
                   7139: 
1.1015    raeburn  7140: sub store_userdata {
                   7141:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7142:     my $result;
1.1016    raeburn  7143:     if ($datakey ne '') {
1.1013    raeburn  7144:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7145:             if ($udom eq '' || $uname eq '') {
                   7146:                 $udom = $env{'user.domain'};
                   7147:                 $uname = $env{'user.name'};
                   7148:             }
                   7149:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7150:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7151:                 $result = 'error: no_host';
                   7152:             } else {
                   7153:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7154:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7155: 
                   7156:                 my $namevalue='';
                   7157:                 foreach my $key (keys(%{$storehash})) {
                   7158:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7159:                 }
                   7160:                 $namevalue=~s/\&$//;
                   7161:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7162:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7163:             }
                   7164:         } else {
                   7165:             $result = 'error: data to store was not a hash reference'; 
                   7166:         }
                   7167:     } else {
                   7168:         $result= 'error: invalid requestkey'; 
                   7169:     }
                   7170:     return $result;
                   7171: }
                   7172: 
1.21      www      7173: # ---------------------------------------------------------- Assign Custom Role
                   7174: 
                   7175: sub assigncustomrole {
1.957     raeburn  7176:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7177:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7178:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7179: }
                   7180: 
                   7181: # ----------------------------------------------------------------- Revoke Role
                   7182: 
                   7183: sub revokerole {
1.957     raeburn  7184:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7185:     my $now=time;
1.965     raeburn  7186:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7187: }
                   7188: 
                   7189: # ---------------------------------------------------------- Revoke Custom Role
                   7190: 
                   7191: sub revokecustomrole {
1.957     raeburn  7192:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7193:     my $now=time;
1.357     www      7194:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7195:            $deleteflag,$selfenroll,$context);
1.17      www      7196: }
                   7197: 
1.533     banghart 7198: # ------------------------------------------------------------ Disk usage
1.535     albertel 7199: sub diskusage {
1.955     raeburn  7200:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7201:     $directorypath =~ s/\/$//;
                   7202:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7203:                        .&escape($getpropath).':'.&escape($uname).':'
                   7204:                        .&escape($udom),homeserver($uname,$udom));
                   7205:     if ($listing eq 'unknown_cmd') {
                   7206:         if ($getpropath) {
                   7207:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7208:         }
                   7209:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7210:     }
1.514     albertel 7211:     return $listing;
1.512     banghart 7212: }
                   7213: 
1.566     banghart 7214: sub is_locked {
                   7215:     my ($file_name, $domain, $user) = @_;
                   7216:     my @check;
                   7217:     my $is_locked;
                   7218:     push @check, $file_name;
1.613     albertel 7219:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7220: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7221:     my ($tmp)=keys(%locked);
                   7222:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7223:     
1.566     banghart 7224:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7225:         $is_locked = 'false';
                   7226:         foreach my $entry (@{$locked{$file_name}}) {
                   7227:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7228:                $is_locked = 'true';
                   7229:                last;
1.745     raeburn  7230:            }
                   7231:        }
1.566     banghart 7232:     } else {
                   7233:         $is_locked = 'false';
                   7234:     }
                   7235: }
                   7236: 
1.759     albertel 7237: sub declutter_portfile {
                   7238:     my ($file) = @_;
1.833     albertel 7239:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7240:     return $file;
                   7241: }
                   7242: 
1.559     banghart 7243: # ------------------------------------------------------------- Mark as Read Only
                   7244: 
                   7245: sub mark_as_readonly {
                   7246:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7247:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7248:     my ($tmp)=keys(%current_permissions);
                   7249:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7250:     foreach my $file (@{$files}) {
1.759     albertel 7251: 	$file = &declutter_portfile($file);
1.561     banghart 7252:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7253:     }
1.613     albertel 7254:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7255:     return;
                   7256: }
                   7257: 
1.572     banghart 7258: # ------------------------------------------------------------Save Selected Files
                   7259: 
                   7260: sub save_selected_files {
                   7261:     my ($user, $path, @files) = @_;
                   7262:     my $filename = $user."savedfiles";
1.573     banghart 7263:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7264:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7265:     foreach my $file (@files) {
1.620     albertel 7266:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7267:     }
                   7268:     foreach my $file (@other_files) {
1.574     banghart 7269:         print (OUT $file."\n");
1.572     banghart 7270:     }
1.574     banghart 7271:     close (OUT);
1.572     banghart 7272:     return 'ok';
                   7273: }
                   7274: 
1.574     banghart 7275: sub clear_selected_files {
                   7276:     my ($user) = @_;
                   7277:     my $filename = $user."savedfiles";
                   7278:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7279:     print (OUT undef);
                   7280:     close (OUT);
                   7281:     return ("ok");    
                   7282: }
                   7283: 
1.572     banghart 7284: sub files_in_path {
                   7285:     my ($user, $path) = @_;
                   7286:     my $filename = $user."savedfiles";
                   7287:     my %return_files;
1.574     banghart 7288:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7289:     while (my $line_in = <IN>) {
1.574     banghart 7290:         chomp ($line_in);
                   7291:         my @paths_and_file = split (m!/!, $line_in);
                   7292:         my $file_part = pop (@paths_and_file);
                   7293:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7294:         $path_part.='/';
                   7295:         my $path_and_file = $path_part.$file_part;
                   7296:         if ($path_part eq $path) {
                   7297:             $return_files{$file_part}= 'selected';
                   7298:         }
                   7299:     }
1.574     banghart 7300:     close (IN);
                   7301:     return (\%return_files);
1.572     banghart 7302: }
                   7303: 
                   7304: # called in portfolio select mode, to show files selected NOT in current directory
                   7305: sub files_not_in_path {
                   7306:     my ($user, $path) = @_;
                   7307:     my $filename = $user."savedfiles";
                   7308:     my @return_files;
                   7309:     my $path_part;
1.800     albertel 7310:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7311:     while (my $line = <IN>) {
1.572     banghart 7312:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7313:         my @paths_and_file = split(m|/|, $line);
                   7314:         my $file_part = pop(@paths_and_file);
                   7315:         chomp($file_part);
                   7316:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7317:         $path_part .= '/';
                   7318:         my $path_and_file = $path_part.$file_part;
                   7319:         if ($path_part ne $path) {
1.800     albertel 7320:             push(@return_files, ($path_and_file));
1.572     banghart 7321:         }
                   7322:     }
1.800     albertel 7323:     close(OUT);
1.574     banghart 7324:     return (@return_files);
1.572     banghart 7325: }
                   7326: 
1.745     raeburn  7327: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7328: 
1.745     raeburn  7329: sub get_portfile_permissions {
                   7330:     my ($domain,$user) = @_;
1.613     albertel 7331:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7332:     my ($tmp)=keys(%current_permissions);
                   7333:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7334:     return \%current_permissions;
                   7335: }
                   7336: 
                   7337: #---------------------------------------------Get portfolio file access controls
                   7338: 
1.749     raeburn  7339: sub get_access_controls {
1.745     raeburn  7340:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7341:     my %access;
                   7342:     my $real_file = $file;
                   7343:     $file =~ s/\.meta$//;
1.745     raeburn  7344:     if (defined($file)) {
1.749     raeburn  7345:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7346:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7347:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7348:             }
                   7349:         }
1.745     raeburn  7350:     } else {
1.749     raeburn  7351:         foreach my $key (keys(%{$current_permissions})) {
                   7352:             if ($key =~ /\0accesscontrol$/) {
                   7353:                 if (defined($group)) {
                   7354:                     if ($key !~ m-^\Q$group\E/-) {
                   7355:                         next;
                   7356:                     }
                   7357:                 }
                   7358:                 my ($fullpath) = split(/\0/,$key);
                   7359:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7360:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7361:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7362:                     }
                   7363:                 }
                   7364:             }
                   7365:         }
                   7366:     }
                   7367:     return %access;
                   7368: }
                   7369: 
                   7370: sub modify_access_controls {
                   7371:     my ($file_name,$changes,$domain,$user)=@_;
                   7372:     my ($outcome,$deloutcome);
                   7373:     my %store_permissions;
                   7374:     my %new_values;
                   7375:     my %new_control;
                   7376:     my %translation;
                   7377:     my @deletions = ();
                   7378:     my $now = time;
                   7379:     if (exists($$changes{'activate'})) {
                   7380:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7381:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7382:             my $numnew = scalar(@newitems);
                   7383:             for (my $i=0; $i<$numnew; $i++) {
                   7384:                 my $newkey = $newitems[$i];
                   7385:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7386:                 if ($newkey =~ /^\d+:/) { 
                   7387:                     $newkey =~ s/^(\d+)/$newid/;
                   7388:                     $translation{$1} = $newid;
                   7389:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7390:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7391:                     $translation{$1} = $newid;
                   7392:                 }
1.749     raeburn  7393:                 $new_values{$file_name."\0".$newkey} = 
                   7394:                                           $$changes{'activate'}{$newitems[$i]};
                   7395:                 $new_control{$newkey} = $now;
                   7396:             }
                   7397:         }
                   7398:     }
                   7399:     my %todelete;
                   7400:     my %changed_items;
                   7401:     foreach my $action ('delete','update') {
                   7402:         if (exists($$changes{$action})) {
                   7403:             if (ref($$changes{$action}) eq 'HASH') {
                   7404:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7405:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7406:                     if ($action eq 'delete') { 
                   7407:                         $todelete{$itemnum} = 1;
                   7408:                     } else {
                   7409:                         $changed_items{$itemnum} = $key;
                   7410:                     }
                   7411:                 }
1.745     raeburn  7412:             }
                   7413:         }
1.749     raeburn  7414:     }
                   7415:     # get lock on access controls for file.
                   7416:     my $lockhash = {
                   7417:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7418:                                                        ':'.$env{'user.domain'},
                   7419:                    }; 
                   7420:     my $tries = 0;
                   7421:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7422:    
                   7423:     while (($gotlock ne 'ok') && $tries <3) {
                   7424:         $tries ++;
                   7425:         sleep 1;
                   7426:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7427:     }
                   7428:     if ($gotlock eq 'ok') {
                   7429:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7430:         my ($tmp)=keys(%curr_permissions);
                   7431:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7432:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7433:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7434:             if (ref($curr_controls) eq 'HASH') {
                   7435:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7436:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7437:                     if (defined($todelete{$itemnum})) {
                   7438:                         push(@deletions,$file_name."\0".$control_item);
                   7439:                     } else {
                   7440:                         if (defined($changed_items{$itemnum})) {
                   7441:                             $new_control{$changed_items{$itemnum}} = $now;
                   7442:                             push(@deletions,$file_name."\0".$control_item);
                   7443:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7444:                         } else {
                   7445:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7446:                         }
                   7447:                     }
1.745     raeburn  7448:                 }
                   7449:             }
                   7450:         }
1.970     raeburn  7451:         my ($group);
                   7452:         if (&is_course($domain,$user)) {
                   7453:             ($group,my $file) = split(/\//,$file_name,2);
                   7454:         }
1.749     raeburn  7455:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7456:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7457:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7458:         #  remove lock
                   7459:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7460:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7461:         my $sqlresult =
1.970     raeburn  7462:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7463:                                     $group);
1.749     raeburn  7464:     } else {
                   7465:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7466:     }
1.749     raeburn  7467:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7468: }
                   7469: 
1.827     raeburn  7470: sub make_public_indefinitely {
                   7471:     my ($requrl) = @_;
                   7472:     my $now = time;
                   7473:     my $action = 'activate';
                   7474:     my $aclnum = 0;
                   7475:     if (&is_portfolio_url($requrl)) {
                   7476:         my (undef,$udom,$unum,$file_name,$group) =
                   7477:             &parse_portfolio_url($requrl);
                   7478:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7479:         my %access_controls = &get_access_controls($current_perms,
                   7480:                                                    $group,$file_name);
                   7481:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7482:             my ($num,$scope,$end,$start) = 
                   7483:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7484:             if ($scope eq 'public') {
                   7485:                 if ($start <= $now && $end == 0) {
                   7486:                     $action = 'none';
                   7487:                 } else {
                   7488:                     $action = 'update';
                   7489:                     $aclnum = $num;
                   7490:                 }
                   7491:                 last;
                   7492:             }
                   7493:         }
                   7494:         if ($action eq 'none') {
                   7495:              return 'ok';
                   7496:         } else {
                   7497:             my %changes;
                   7498:             my $newend = 0;
                   7499:             my $newstart = $now;
                   7500:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7501:             $changes{$action}{$newkey} = {
                   7502:                 type => 'public',
                   7503:                 time => {
                   7504:                     start => $newstart,
                   7505:                     end   => $newend,
                   7506:                 },
                   7507:             };
                   7508:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7509:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7510:             return $outcome;
                   7511:         }
                   7512:     } else {
                   7513:         return 'invalid';
                   7514:     }
                   7515: }
                   7516: 
1.745     raeburn  7517: #------------------------------------------------------Get Marked as Read Only
                   7518: 
                   7519: sub get_marked_as_readonly {
                   7520:     my ($domain,$user,$what,$group) = @_;
                   7521:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7522:     my @readonly_files;
1.629     banghart 7523:     my $cmp1=$what;
                   7524:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7525:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7526:         if (defined($group)) {
                   7527:             if ($file_name !~ m-^\Q$group\E/-) {
                   7528:                 next;
                   7529:             }
                   7530:         }
1.561     banghart 7531:         if (ref($value) eq "ARRAY"){
                   7532:             foreach my $stored_what (@{$value}) {
1.629     banghart 7533:                 my $cmp2=$stored_what;
1.759     albertel 7534:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7535:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7536:                 }
1.629     banghart 7537:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7538:                     push(@readonly_files, $file_name);
1.745     raeburn  7539:                     last;
1.563     banghart 7540:                 } elsif (!defined($what)) {
                   7541:                     push(@readonly_files, $file_name);
1.745     raeburn  7542:                     last;
1.561     banghart 7543:                 }
                   7544:             }
1.745     raeburn  7545:         }
1.561     banghart 7546:     }
                   7547:     return @readonly_files;
                   7548: }
1.577     banghart 7549: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7550: 
1.577     banghart 7551: sub get_marked_as_readonly_hash {
1.745     raeburn  7552:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7553:     my %readonly_files;
1.745     raeburn  7554:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7555:         if (defined($group)) {
                   7556:             if ($file_name !~ m-^\Q$group\E/-) {
                   7557:                 next;
                   7558:             }
                   7559:         }
1.577     banghart 7560:         if (ref($value) eq "ARRAY"){
                   7561:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7562:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7563:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7564:                         if ($lock_descriptor eq 'graded') {
                   7565:                             $readonly_files{$file_name} = 'graded';
                   7566:                         } elsif ($lock_descriptor eq 'handback') {
                   7567:                             $readonly_files{$file_name} = 'handback';
                   7568:                         } else {
                   7569:                             if (!exists($readonly_files{$file_name})) {
                   7570:                                 $readonly_files{$file_name} = 'locked';
                   7571:                             }
                   7572:                         }
1.745     raeburn  7573:                     }
1.750     banghart 7574:                 } 
1.577     banghart 7575:             }
                   7576:         } 
                   7577:     }
                   7578:     return %readonly_files;
                   7579: }
1.559     banghart 7580: # ------------------------------------------------------------ Unmark as Read Only
                   7581: 
                   7582: sub unmark_as_readonly {
1.629     banghart 7583:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7584:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7585:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7586:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7587:     my $symb_crs = $what;
                   7588:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7589:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7590:     my ($tmp)=keys(%current_permissions);
                   7591:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7592:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7593:     foreach my $file (@readonly_files) {
1.759     albertel 7594: 	my $clean_file = &declutter_portfile($file);
                   7595: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7596: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7597:         my @new_locks;
                   7598:         my @del_keys;
                   7599:         if (ref($current_locks) eq "ARRAY"){
                   7600:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7601:                 my $compare=$locker;
1.749     raeburn  7602:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7603:                     $compare=join('',@{$locker});
1.746     raeburn  7604:                     if ($compare ne $symb_crs) {
                   7605:                         push(@new_locks, $locker);
                   7606:                     }
1.563     banghart 7607:                 }
                   7608:             }
1.650     albertel 7609:             if (scalar(@new_locks) > 0) {
1.563     banghart 7610:                 $current_permissions{$file} = \@new_locks;
                   7611:             } else {
                   7612:                 push(@del_keys, $file);
1.613     albertel 7613:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7614:                 delete($current_permissions{$file});
1.563     banghart 7615:             }
                   7616:         }
1.561     banghart 7617:     }
1.613     albertel 7618:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7619:     return;
                   7620: }
1.512     banghart 7621: 
1.17      www      7622: # ------------------------------------------------------------ Directory lister
                   7623: 
                   7624: sub dirlist {
1.955     raeburn  7625:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7626:     $uri=~s/^\///;
                   7627:     $uri=~s/\/$//;
1.253     stredwic 7628:     my ($udom, $uname);
1.955     raeburn  7629:     if ($getuserdir) {
1.253     stredwic 7630:         $udom = $userdomain;
                   7631:         $uname = $username;
1.955     raeburn  7632:     } else {
                   7633:         (undef,$udom,$uname)=split(/\//,$uri);
                   7634:         if(defined($userdomain)) {
                   7635:             $udom = $userdomain;
                   7636:         }
                   7637:         if(defined($username)) {
                   7638:             $uname = $username;
                   7639:         }
1.253     stredwic 7640:     }
1.955     raeburn  7641:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7642: 
1.955     raeburn  7643:     $dirRoot = $perlvar{'lonDocRoot'};
                   7644:     if (defined($getpropath)) {
                   7645:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7646:         $dirRoot =~ s/\/$//;
1.955     raeburn  7647:     } elsif (defined($getuserdir)) {
                   7648:         my $subdir=$uname.'__';
                   7649:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7650:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7651:                    ."/$udom/$subdir/$uname";
                   7652:     } elsif (defined($alternateRoot)) {
                   7653:         $dirRoot = $alternateRoot;
1.751     banghart 7654:     }
1.253     stredwic 7655: 
                   7656:     if($udom) {
                   7657:         if($uname) {
1.955     raeburn  7658:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7659:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7660:                               .':'.&escape($uname).':'.&escape($udom),
                   7661:                               &homeserver($uname,$udom));
                   7662:             if ($listing eq 'unknown_cmd') {
                   7663:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7664:                                   &homeserver($uname,$udom));
                   7665:             } else {
                   7666:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7667:             }
1.605     matthew  7668:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7669:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7670: 				  &homeserver($uname,$udom));
1.605     matthew  7671:                 @listing_results = split(/:/,$listing);
                   7672:             } else {
                   7673:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7674:             }
                   7675:             return @listing_results;
1.955     raeburn  7676:         } elsif(!$alternateRoot) {
1.800     albertel 7677:             my %allusers;
1.841     albertel 7678: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7679:  	    foreach my $tryserver (keys(%servers)) {
                   7680:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7681:                                   &escape($udom),$tryserver);
                   7682:                 if ($listing eq 'unknown_cmd') {
                   7683: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7684: 				      $udom, $tryserver);
                   7685:                 } else {
                   7686:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7687:                 }
1.841     albertel 7688: 		if ($listing eq 'unknown_cmd') {
                   7689: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7690: 				      $udom, $tryserver);
                   7691: 		    @listing_results = split(/:/,$listing);
                   7692: 		} else {
                   7693: 		    @listing_results =
                   7694: 			map { &unescape($_); } split(/:/,$listing);
                   7695: 		}
                   7696: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7697: 		    $listing_results[0] ne 'empty'       &&
                   7698: 		    $listing_results[0] ne 'con_lost') {
                   7699: 		    foreach my $line (@listing_results) {
                   7700: 			my ($entry) = split(/&/,$line,2);
                   7701: 			$allusers{$entry} = 1;
                   7702: 		    }
                   7703: 		}
1.253     stredwic 7704:             }
                   7705:             my $alluserstr='';
1.800     albertel 7706:             foreach my $user (sort(keys(%allusers))) {
                   7707:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7708:             }
                   7709:             $alluserstr=~s/:$//;
                   7710:             return split(/:/,$alluserstr);
                   7711:         } else {
1.800     albertel 7712:             return ('missing user name');
1.253     stredwic 7713:         }
1.955     raeburn  7714:     } elsif(!defined($getpropath)) {
1.841     albertel 7715:         my @all_domains = sort(&all_domains());
1.955     raeburn  7716:         foreach my $domain (@all_domains) {
                   7717:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7718:         }
                   7719:         return @all_domains;
                   7720:     } else {
1.800     albertel 7721:         return ('missing domain');
1.275     stredwic 7722:     }
                   7723: }
                   7724: 
                   7725: # --------------------------------------------- GetFileTimestamp
                   7726: # This function utilizes dirlist and returns the date stamp for
                   7727: # when it was last modified.  It will also return an error of -1
                   7728: # if an error occurs
                   7729: 
                   7730: sub GetFileTimestamp {
1.955     raeburn  7731:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7732:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7733:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7734:     my ($fileStat) = 
                   7735:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7736:                                  undef,$getuserdir);
1.275     stredwic 7737:     my @stats = split('&', $fileStat);
                   7738:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7739:         # @stats contains first the filename, then the stat output
                   7740:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7741:     } else {
                   7742:         return -1;
1.253     stredwic 7743:     }
1.26      www      7744: }
                   7745: 
1.712     albertel 7746: sub stat_file {
                   7747:     my ($uri) = @_;
1.787     albertel 7748:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7749: 
1.955     raeburn  7750:     my ($udom,$uname,$file);
1.712     albertel 7751:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7752: 	($udom,$uname,$file) =
1.811     albertel 7753: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7754: 	$file = 'userfiles/'.$file;
                   7755:     }
                   7756:     if ($uri =~ m-^/res/-) {
                   7757: 	($udom,$uname) = 
1.807     albertel 7758: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7759: 	$file = $uri;
                   7760:     }
                   7761: 
                   7762:     if (!$udom || !$uname || !$file) {
                   7763: 	# unable to handle the uri
                   7764: 	return ();
                   7765:     }
1.956     raeburn  7766:     my $getpropath;
                   7767:     if ($file =~ /^userfiles\//) {
                   7768:         $getpropath = 1;
                   7769:     }
1.955     raeburn  7770:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7771:     my @stats = split('&', $result);
1.721     banghart 7772:     
1.712     albertel 7773:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7774: 	shift(@stats); #filename is first
                   7775: 	return @stats;
                   7776:     }
                   7777:     return ();
                   7778: }
                   7779: 
1.26      www      7780: # -------------------------------------------------------- Value of a Condition
                   7781: 
1.713     albertel 7782: # gets the value of a specific preevaluated condition
                   7783: #    stored in the string  $env{user.state.<cid>}
                   7784: # or looks up a condition reference in the bighash and if if hasn't
                   7785: # already been evaluated recurses into docondval to get the value of
                   7786: # the condition, then memoizing it to 
                   7787: #   $env{user.state.<cid>.<condition>}
1.40      www      7788: sub directcondval {
                   7789:     my $number=shift;
1.620     albertel 7790:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7791: 	&Apache::lonuserstate::evalstate();
                   7792:     }
1.713     albertel 7793:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7794: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7795:     } elsif ($number =~ /^_/) {
                   7796: 	my $sub_condition;
                   7797: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7798: 		&GDBM_READER(),0640)) {
                   7799: 	    $sub_condition=$bighash{'conditions'.$number};
                   7800: 	    untie(%bighash);
                   7801: 	}
                   7802: 	my $value = &docondval($sub_condition);
1.949     raeburn  7803: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7804: 	return $value;
                   7805:     }
1.620     albertel 7806:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7807:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7808:     } else {
                   7809:        return 2;
                   7810:     }
                   7811: }
                   7812: 
1.713     albertel 7813: # get the collection of conditions for this resource
1.26      www      7814: sub condval {
                   7815:     my $condidx=shift;
1.54      www      7816:     my $allpathcond='';
1.713     albertel 7817:     foreach my $cond (split(/\|/,$condidx)) {
                   7818: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7819: 	    $allpathcond.=
                   7820: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7821: 	}
1.191     harris41 7822:     }
1.54      www      7823:     $allpathcond=~s/\|$//;
1.713     albertel 7824:     return &docondval($allpathcond);
                   7825: }
                   7826: 
                   7827: #evaluates an expression of conditions
                   7828: sub docondval {
                   7829:     my ($allpathcond) = @_;
                   7830:     my $result=0;
                   7831:     if ($env{'request.course.id'}
                   7832: 	&& defined($allpathcond)) {
                   7833: 	my $operand='|';
                   7834: 	my @stack;
                   7835: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7836: 	    if ($chunk eq '(') {
                   7837: 		push @stack,($operand,$result);
                   7838: 	    } elsif ($chunk eq ')') {
                   7839: 		my $before=pop @stack;
                   7840: 		if (pop @stack eq '&') {
                   7841: 		    $result=$result>$before?$before:$result;
                   7842: 		} else {
                   7843: 		    $result=$result>$before?$result:$before;
                   7844: 		}
                   7845: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7846: 		$operand=$chunk;
                   7847: 	    } else {
                   7848: 		my $new=directcondval($chunk);
                   7849: 		if ($operand eq '&') {
                   7850: 		    $result=$result>$new?$new:$result;
                   7851: 		} else {
                   7852: 		    $result=$result>$new?$result:$new;
                   7853: 		}
                   7854: 	    }
                   7855: 	}
1.26      www      7856:     }
                   7857:     return $result;
1.421     albertel 7858: }
                   7859: 
                   7860: # ---------------------------------------------------- Devalidate courseresdata
                   7861: 
                   7862: sub devalidatecourseresdata {
                   7863:     my ($coursenum,$coursedomain)=@_;
                   7864:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7865:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7866: }
                   7867: 
1.763     www      7868: 
1.200     www      7869: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7870: #
                   7871: #  Parameters:
                   7872: #      $coursenum    - Number of the course.
                   7873: #      $coursedomain - Domain at which the course was created.
                   7874: #  Returns:
                   7875: #     A hash of the course parameters along (I think) with timestamps
                   7876: #     and version info.
1.877     foxr     7877: 
1.624     albertel 7878: sub get_courseresdata {
                   7879:     my ($coursenum,$coursedomain)=@_;
1.200     www      7880:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7881:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7882:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7883:     my %dumpreply;
1.417     albertel 7884:     unless (defined($cached)) {
1.624     albertel 7885: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7886: 	$result=\%dumpreply;
1.251     albertel 7887: 	my ($tmp) = keys(%dumpreply);
                   7888: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7889: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7890: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7891: 	    return $tmp;
1.416     albertel 7892: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7893: 	    $result=undef;
1.599     albertel 7894: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7895: 	}
                   7896:     }
1.624     albertel 7897:     return $result;
                   7898: }
                   7899: 
1.633     albertel 7900: sub devalidateuserresdata {
                   7901:     my ($uname,$udom)=@_;
                   7902:     my $hashid="$udom:$uname";
                   7903:     &devalidate_cache_new('userres',$hashid);
                   7904: }
                   7905: 
1.624     albertel 7906: sub get_userresdata {
                   7907:     my ($uname,$udom)=@_;
                   7908:     #most student don\'t have any data set, check if there is some data
                   7909:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7910: 
                   7911:     my $hashid="$udom:$uname";
                   7912:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7913:     if (!defined($cached)) {
                   7914: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7915: 	$result=\%resourcedata;
                   7916: 	&do_cache_new('userres',$hashid,$result,600);
                   7917:     }
                   7918:     my ($tmp)=keys(%$result);
                   7919:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7920: 	return $result;
                   7921:     }
                   7922:     #error 2 occurs when the .db doesn't exist
                   7923:     if ($tmp!~/error: 2 /) {
1.672     albertel 7924: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7925: 		 " Trying to get resource data for ".
                   7926: 		 $uname." at ".$udom.": ".
                   7927: 		 $tmp."</font>");
                   7928:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7929: 	#&EXT_cache_set($udom,$uname);
                   7930: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7931: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7932:     }
                   7933:     return $tmp;
                   7934: }
1.879     foxr     7935: #----------------------------------------------- resdata - return resource data
                   7936: #  Purpose:
                   7937: #    Return resource data for either users or for a course.
                   7938: #  Parameters:
                   7939: #     $name      - Course/user name.
                   7940: #     $domain    - Name of the domain the user/course is registered on.
                   7941: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7942: #     @which     - Array of names of resources desired.
                   7943: #  Returns:
                   7944: #     The value of the first reasource in @which that is found in the
                   7945: #     resource hash.
                   7946: #  Exceptional Conditions:
                   7947: #     If the $type passed in is not valid (not the string 'course' or 
                   7948: #     'user', an undefined  reference is returned.
                   7949: #     If none of the resources are found, an undef is returned
1.624     albertel 7950: sub resdata {
                   7951:     my ($name,$domain,$type,@which)=@_;
                   7952:     my $result;
                   7953:     if ($type eq 'course') {
                   7954: 	$result=&get_courseresdata($name,$domain);
                   7955:     } elsif ($type eq 'user') {
                   7956: 	$result=&get_userresdata($name,$domain);
                   7957:     }
                   7958:     if (!ref($result)) { return $result; }    
1.251     albertel 7959:     foreach my $item (@which) {
1.927     albertel 7960: 	if (defined($result->{$item->[0]})) {
                   7961: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7962: 	}
1.250     albertel 7963:     }
1.291     albertel 7964:     return undef;
1.200     www      7965: }
                   7966: 
1.379     matthew  7967: #
                   7968: # EXT resource caching routines
                   7969: #
                   7970: 
                   7971: sub clear_EXT_cache_status {
1.383     albertel 7972:     &delenv('cache.EXT.');
1.379     matthew  7973: }
                   7974: 
                   7975: sub EXT_cache_status {
                   7976:     my ($target_domain,$target_user) = @_;
1.383     albertel 7977:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7978:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7979:         # We know already the user has no data
                   7980:         return 1;
                   7981:     } else {
                   7982:         return 0;
                   7983:     }
                   7984: }
                   7985: 
                   7986: sub EXT_cache_set {
                   7987:     my ($target_domain,$target_user) = @_;
1.383     albertel 7988:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7989:     #&appenv({$cachename => time});
1.379     matthew  7990: }
                   7991: 
1.28      www      7992: # --------------------------------------------------------- Value of a Variable
1.58      www      7993: sub EXT {
1.715     albertel 7994: 
1.395     albertel 7995:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7996:     unless ($varname) { return ''; }
1.218     albertel 7997:     #get real user name/domain, courseid and symb
                   7998:     my $courseid;
1.359     albertel 7999:     my $publicuser;
1.427     www      8000:     if ($symbparm) {
                   8001: 	$symbparm=&get_symb_from_alias($symbparm);
                   8002:     }
1.218     albertel 8003:     if (!($uname && $udom)) {
1.790     albertel 8004:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8005:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8006:     } else {
1.620     albertel 8007: 	$courseid=$env{'request.course.id'};
1.218     albertel 8008:     }
1.48      www      8009:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8010:     my $rest;
1.320     albertel 8011:     if (defined($therest[0])) {
1.48      www      8012:        $rest=join('.',@therest);
                   8013:     } else {
                   8014:        $rest='';
                   8015:     }
1.320     albertel 8016: 
1.57      www      8017:     my $qualifierrest=$qualifier;
                   8018:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8019:     my $spacequalifierrest=$space;
                   8020:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8021:     if ($realm eq 'user') {
1.48      www      8022: # --------------------------------------------------------------- user.resource
                   8023: 	if ($space eq 'resource') {
1.651     albertel 8024: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8025: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8026: 		 &&
1.744     albertel 8027: 		 ($symbparm eq &symbread()) ) {	
                   8028: 		# if we are in the middle of processing the resource the
                   8029: 		# get the value we are planning on committing
                   8030:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8031:                     return $Apache::lonhomework::results{$qualifierrest};
                   8032:                 } else {
                   8033:                     return $Apache::lonhomework::history{$qualifierrest};
                   8034:                 }
1.335     albertel 8035: 	    } else {
1.359     albertel 8036: 		my %restored;
1.620     albertel 8037: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8038: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8039: 		} else {
                   8040: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8041: 		}
1.335     albertel 8042: 		return $restored{$qualifierrest};
                   8043: 	    }
1.48      www      8044: # ----------------------------------------------------------------- user.access
                   8045:         } elsif ($space eq 'access') {
1.218     albertel 8046: 	    # FIXME - not supporting calls for a specific user
1.48      www      8047:             return &allowed($qualifier,$rest);
                   8048: # ------------------------------------------ user.preferences, user.environment
                   8049:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8050: 	    if (($uname eq $env{'user.name'}) &&
                   8051: 		($udom eq $env{'user.domain'})) {
                   8052: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8053: 	    } else {
1.359     albertel 8054: 		my %returnhash;
                   8055: 		if (!$publicuser) {
                   8056: 		    %returnhash=&userenvironment($udom,$uname,
                   8057: 						 $qualifierrest);
                   8058: 		}
1.218     albertel 8059: 		return $returnhash{$qualifierrest};
                   8060: 	    }
1.48      www      8061: # ----------------------------------------------------------------- user.course
                   8062:         } elsif ($space eq 'course') {
1.218     albertel 8063: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8064:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8065: # ------------------------------------------------------------------- user.role
                   8066:         } elsif ($space eq 'role') {
1.218     albertel 8067: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8068:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8069:             if ($qualifier eq 'value') {
                   8070: 		return $role;
                   8071:             } elsif ($qualifier eq 'extent') {
                   8072:                 return $where;
                   8073:             }
                   8074: # ----------------------------------------------------------------- user.domain
                   8075:         } elsif ($space eq 'domain') {
1.218     albertel 8076:             return $udom;
1.48      www      8077: # ------------------------------------------------------------------- user.name
                   8078:         } elsif ($space eq 'name') {
1.218     albertel 8079:             return $uname;
1.48      www      8080: # ---------------------------------------------------- Any other user namespace
1.29      www      8081:         } else {
1.359     albertel 8082: 	    my %reply;
                   8083: 	    if (!$publicuser) {
                   8084: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8085: 	    }
                   8086: 	    return $reply{$qualifierrest};
1.48      www      8087:         }
1.236     www      8088:     } elsif ($realm eq 'query') {
                   8089: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8090:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8091: 						[$spacequalifierrest]);
1.620     albertel 8092: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8093:    } elsif ($realm eq 'request') {
1.48      www      8094: # ------------------------------------------------------------- request.browser
                   8095:         if ($space eq 'browser') {
1.430     www      8096: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8097: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8098: 		    return 1;
                   8099: 		} else {
                   8100: 		    return 0;
                   8101: 		}
                   8102: 	    } else {
1.620     albertel 8103: 		return $env{'browser.'.$qualifier};
1.430     www      8104: 	    }
1.57      www      8105: # ------------------------------------------------------------ request.filename
                   8106:         } else {
1.620     albertel 8107:             return $env{'request.'.$spacequalifierrest};
1.29      www      8108:         }
1.28      www      8109:     } elsif ($realm eq 'course') {
1.48      www      8110: # ---------------------------------------------------------- course.description
1.620     albertel 8111:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8112:     } elsif ($realm eq 'resource') {
1.165     www      8113: 
1.620     albertel 8114: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8115: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8116: 	}
1.693     albertel 8117: 
                   8118: 	if ($space eq 'title') {
                   8119: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8120: 	    return &gettitle($symbparm);
                   8121: 	}
                   8122: 	
                   8123: 	if ($space eq 'map') {
                   8124: 	    my ($map) = &decode_symb($symbparm);
                   8125: 	    return &symbread($map);
                   8126: 	}
1.905     albertel 8127: 	if ($space eq 'filename') {
                   8128: 	    if ($symbparm) {
                   8129: 		return &clutter((&decode_symb($symbparm))[2]);
                   8130: 	    }
                   8131: 	    return &hreflocation('',$env{'request.filename'});
                   8132: 	}
1.693     albertel 8133: 
                   8134: 	my ($section, $group, @groups);
1.593     albertel 8135: 	my ($courselevelm,$courselevel);
1.539     albertel 8136: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8137: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8138: 
1.218     albertel 8139: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8140: 
1.60      www      8141: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8142: 	    my $symbp=$symbparm;
1.735     albertel 8143: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8144: 
                   8145: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8146: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8147: 
1.620     albertel 8148: 	    if (($env{'user.name'} eq $uname) &&
                   8149: 		($env{'user.domain'} eq $udom)) {
                   8150: 		$section=$env{'request.course.sec'};
1.733     raeburn  8151:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8152:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8153: 	    } else {
1.539     albertel 8154: 		if (! defined($usection)) {
1.551     albertel 8155: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8156: 		} else {
                   8157: 		    $section = $usection;
                   8158: 		}
1.733     raeburn  8159:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8160: 	    }
                   8161: 
                   8162: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8163: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8164: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8165: 
1.593     albertel 8166: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8167: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8168: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8169: 
1.60      www      8170: # ----------------------------------------------------------- first, check user
1.624     albertel 8171: 
                   8172: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8173: 				       ([$courselevelr,'resource'],
                   8174: 					[$courselevelm,'map'     ],
                   8175: 					[$courselevel, 'course'  ]));
1.931     albertel 8176: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8177: 
1.594     albertel 8178: # ------------------------------------------------ second, check some of course
1.684     raeburn  8179:             my $coursereply;
1.691     raeburn  8180:             if (@groups > 0) {
                   8181:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8182:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8183:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8184:             }
1.96      www      8185: 
1.684     raeburn  8186: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8187: 				  $env{'course.'.$courseid.'.domain'},
                   8188: 				  'course',
                   8189: 				  ([$seclevelr,   'resource'],
                   8190: 				   [$seclevelm,   'map'     ],
                   8191: 				   [$seclevel,    'course'  ],
                   8192: 				   [$courselevelr,'resource']));
                   8193: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8194: 
1.60      www      8195: # ------------------------------------------------------ third, check map parms
1.218     albertel 8196: 	    my %parmhash=();
                   8197: 	    my $thisparm='';
                   8198: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8199: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8200: 		    &GDBM_READER(),0640)) {
1.218     albertel 8201: 		$thisparm=$parmhash{$symbparm};
                   8202: 		untie(%parmhash);
                   8203: 	    }
1.927     albertel 8204: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8205: 	}
1.594     albertel 8206: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8207: 
1.218     albertel 8208: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8209: 	my $filename;
                   8210: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8211: 	if ($symbparm) {
1.409     www      8212: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8213: 	} else {
1.620     albertel 8214: 	    $filename=$env{'request.filename'};
1.282     albertel 8215: 	}
                   8216: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8217: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8218: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8219: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8220: 
1.927     albertel 8221: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8222: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8223: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8224: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8225: 				     $env{'course.'.$courseid.'.domain'},
                   8226: 				     'course',
1.927     albertel 8227: 				     ([$courselevelm,'map'   ],
                   8228: 				      [$courselevel, 'course']));
                   8229: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8230: 	}
1.145     www      8231: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8232: 	unless ($space eq '0') {
1.336     albertel 8233: 	    my @parts=split(/_/,$space);
                   8234: 	    my $id=pop(@parts);
                   8235: 	    my $part=join('_',@parts);
                   8236: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8237: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8238: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8239: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8240: 	}
1.395     albertel 8241: 	if ($recurse) { return undef; }
                   8242: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8243: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8244: # ---------------------------------------------------- Any other user namespace
                   8245:     } elsif ($realm eq 'environment') {
                   8246: # ----------------------------------------------------------------- environment
1.620     albertel 8247: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8248: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8249: 	} else {
1.770     albertel 8250: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8251: 		return '';
                   8252: 	    }
1.219     albertel 8253: 	    my %returnhash=&userenvironment($udom,$uname,
                   8254: 					    $spacequalifierrest);
                   8255: 	    return $returnhash{$spacequalifierrest};
                   8256: 	}
1.28      www      8257:     } elsif ($realm eq 'system') {
1.48      www      8258: # ----------------------------------------------------------------- system.time
                   8259: 	if ($space eq 'time') {
                   8260: 	    return time;
                   8261:         }
1.696     albertel 8262:     } elsif ($realm eq 'server') {
                   8263: # ----------------------------------------------------------------- system.time
                   8264: 	if ($space eq 'name') {
                   8265: 	    return $ENV{'SERVER_NAME'};
                   8266:         }
1.28      www      8267:     }
1.48      www      8268:     return '';
1.61      www      8269: }
                   8270: 
1.927     albertel 8271: sub get_reply {
                   8272:     my ($reply_value) = @_;
1.940     raeburn  8273:     if (ref($reply_value) eq 'ARRAY') {
                   8274:         if (wantarray) {
                   8275: 	    return @$reply_value;
                   8276:         }
                   8277:         return $reply_value->[0];
                   8278:     } else {
                   8279:         return $reply_value;
1.927     albertel 8280:     }
                   8281: }
                   8282: 
1.691     raeburn  8283: sub check_group_parms {
                   8284:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8285:     my @groupitems = ();
                   8286:     my $resultitem;
1.927     albertel 8287:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8288:     foreach my $group (@{$groups}) {
                   8289:         foreach my $level (@levels) {
1.927     albertel 8290:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8291:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8292:         }
                   8293:     }
                   8294:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8295:                             $env{'course.'.$courseid.'.domain'},
                   8296:                                      'course',@groupitems);
                   8297:     return $coursereply;
                   8298: }
                   8299: 
                   8300: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8301:     my ($courseid,@groups) = @_;
                   8302:     @groups = sort(@groups);
1.691     raeburn  8303:     return @groups;
                   8304: }
                   8305: 
1.395     albertel 8306: sub packages_tab_default {
                   8307:     my ($uri,$varname)=@_;
                   8308:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8309: 
                   8310:     my (@extension,@specifics,$do_default);
                   8311:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8312: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8313: 	if ($pack_type eq 'default') {
                   8314: 	    $do_default=1;
                   8315: 	} elsif ($pack_type eq 'extension') {
                   8316: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8317: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8318: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8319: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8320: 	}
                   8321:     }
                   8322:     # first look for a package that matches the requested part id
                   8323:     foreach my $package (@specifics) {
                   8324: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8325: 	next if ($pack_part ne $part);
                   8326: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8327: 	    return $packagetab{"$pack_type&$name&default"};
                   8328: 	}
                   8329:     }
                   8330:     # look for any possible matching non extension_ package
                   8331:     foreach my $package (@specifics) {
                   8332: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8333: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8334: 	    return $packagetab{"$pack_type&$name&default"};
                   8335: 	}
1.585     albertel 8336: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8337: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8338: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8339: 	}
                   8340:     }
1.738     albertel 8341:     # look for any posible extension_ match
                   8342:     foreach my $package (@extension) {
                   8343: 	my ($package,$pack_type)=@{$package};
                   8344: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8345: 	    return $packagetab{"$pack_type&$name&default"};
                   8346: 	}
                   8347: 	if (defined($packagetab{$package."&$name&default"})) {
                   8348: 	    return $packagetab{$package."&$name&default"};
                   8349: 	}
                   8350:     }
                   8351:     # look for a global default setting
                   8352:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8353: 	return $packagetab{"default&$name&default"};
                   8354:     }
1.395     albertel 8355:     return undef;
                   8356: }
                   8357: 
1.334     albertel 8358: sub add_prefix_and_part {
                   8359:     my ($prefix,$part)=@_;
                   8360:     my $keyroot;
                   8361:     if (defined($prefix) && $prefix !~ /^__/) {
                   8362: 	# prefix that has a part already
                   8363: 	$keyroot=$prefix;
                   8364:     } elsif (defined($prefix)) {
                   8365: 	# prefix that is missing a part
                   8366: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8367:     } else {
                   8368: 	# no prefix at all
                   8369: 	if (defined($part)) { $keyroot='_'.$part; }
                   8370:     }
                   8371:     return $keyroot;
                   8372: }
                   8373: 
1.71      www      8374: # ---------------------------------------------------------------- Get metadata
                   8375: 
1.599     albertel 8376: my %metaentry;
1.1070    www      8377: my %importedpartids;
1.71      www      8378: sub metadata {
1.176     www      8379:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8380:     $uri=&declutter($uri);
1.288     albertel 8381:     # if it is a non metadata possible uri return quickly
1.529     albertel 8382:     if (($uri eq '') || 
                   8383: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8384: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8385:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8386: 	return undef;
                   8387:     }
                   8388:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8389: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8390: 	return undef;
1.288     albertel 8391:     }
1.73      www      8392:     my $filename=$uri;
                   8393:     $uri=~s/\.meta$//;
1.172     www      8394: #
                   8395: # Is the metadata already cached?
1.177     www      8396: # Look at timestamp of caching
1.172     www      8397: # Everything is cached by the main uri, libraries are never directly cached
                   8398: #
1.428     albertel 8399:     if (!defined($liburi)) {
1.599     albertel 8400: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8401: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8402:     }
                   8403:     {
1.1069    www      8404: # Imported parts would go here
1.1070    www      8405:         my %importedids=();
                   8406:         my @origfileimportpartids=();
1.1069    www      8407:         my $importedparts=0;
1.172     www      8408: #
                   8409: # Is this a recursive call for a library?
                   8410: #
1.599     albertel 8411: #	if (! exists($metacache{$uri})) {
                   8412: #	    $metacache{$uri}={};
                   8413: #	}
1.924     albertel 8414: 	my $cachetime = 60*60;
1.171     www      8415:         if ($liburi) {
                   8416: 	    $liburi=&declutter($liburi);
                   8417:             $filename=$liburi;
1.401     bowersj2 8418:         } else {
1.599     albertel 8419: 	    &devalidate_cache_new('meta',$uri);
                   8420: 	    undef(%metaentry);
1.401     bowersj2 8421: 	}
1.140     www      8422:         my %metathesekeys=();
1.73      www      8423:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8424: 	my $metastring;
1.924     albertel 8425: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8426: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8427: 	    $metastring = 
1.929     albertel 8428: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8429: 					  ('grade_target' => 'meta'));
                   8430: 	    $cachetime = 1; # only want this cached in the child not long term
                   8431: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8432: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8433: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8434: 	    $metastring=&getfile($file);
1.489     albertel 8435: 	}
1.208     albertel 8436:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8437:         my $token;
1.140     www      8438:         undef %metathesekeys;
1.71      www      8439:         while ($token=$parser->get_token) {
1.339     albertel 8440: 	    if ($token->[0] eq 'S') {
                   8441: 		if (defined($token->[2]->{'package'})) {
1.172     www      8442: #
                   8443: # This is a package - get package info
                   8444: #
1.339     albertel 8445: 		    my $package=$token->[2]->{'package'};
                   8446: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8447: 		    if (defined($token->[2]->{'id'})) { 
                   8448: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8449: 		    }
1.599     albertel 8450: 		    if ($metaentry{':packages'}) {
                   8451: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8452: 		    } else {
1.599     albertel 8453: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8454: 		    }
1.736     albertel 8455: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8456: 			my $part=$keyroot;
                   8457: 			$part=~s/^\_//;
1.736     albertel 8458: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8459: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8460: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8461: 			    # ignore package.tab specified default values
                   8462:                             # here &package_tab_default() will fetch those
                   8463: 			    if ($subp eq 'default') { next; }
1.736     albertel 8464: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8465: 			    my $unikey;
                   8466: 			    if ($pack =~ /_0$/) {
                   8467: 				$unikey='parameter_0_'.$name;
                   8468: 				$part=0;
                   8469: 			    } else {
                   8470: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8471: 			    }
1.339     albertel 8472: 			    if ($subp eq 'display') {
                   8473: 				$value.=' [Part: '.$part.']';
                   8474: 			    }
1.599     albertel 8475: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8476: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8477: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8478: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8479: 			    }
1.599     albertel 8480: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8481: 				$metaentry{':'.$unikey}=
                   8482: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8483: 			    }
1.339     albertel 8484: 			}
                   8485: 		    }
                   8486: 		} else {
1.172     www      8487: #
                   8488: # This is not a package - some other kind of start tag
1.339     albertel 8489: #
                   8490: 		    my $entry=$token->[1];
1.1068    www      8491: 		    my $unikey='';
1.175     www      8492: 
1.339     albertel 8493: 		    if ($entry eq 'import') {
1.175     www      8494: #
                   8495: # Importing a library here
1.339     albertel 8496: #
1.1067    www      8497:                         my $location=$parser->get_text('/import');
                   8498:                         my $dir=$filename;
                   8499:                         $dir=~s|[^/]*$||;
                   8500:                         $location=&filelocation($dir,$location);
1.1069    www      8501:                        
1.1068    www      8502:                         my $importmode=$token->[2]->{'importmode'};
                   8503:                         if ($importmode eq 'problem') {
1.1069    www      8504: # Import as problem/response
1.1068    www      8505:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8506:                         } elsif ($importmode eq 'part') {
                   8507: # Import as part(s)
1.1069    www      8508:                            $importedparts=1;
                   8509: # We need to get the original file and the imported file to get the part order correct
                   8510: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8511: # Load and inspect original file
1.1070    www      8512:                            if ($#origfileimportpartids<0) {
                   8513:                               undef(%importedpartids);
                   8514:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8515:                               my $origfile=&getfile($origfilelocation);
                   8516:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8517:                            }
                   8518: 
1.1069    www      8519: # Load and inspect imported file
                   8520:                            my $impfile=&getfile($location);
                   8521:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8522:                            if ($#impfilepartids>=0) {
                   8523: # This problem had parts
1.1070    www      8524:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8525:                            } else {
                   8526: # Importing by turning a single problem into a problem part
                   8527: # It gets the import-tags ID as part-ID
                   8528:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8529:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8530:                            }
1.1068    www      8531:                         } else {
                   8532: # Normal import
                   8533:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8534:                            if (defined($token->[2]->{'id'})) {
                   8535:                               $unikey.='_'.$token->[2]->{'id'};
                   8536:                            }
1.1067    www      8537:                         }
                   8538: 
1.339     albertel 8539: 			if ($depthcount<20) {
1.736     albertel 8540: 			    my $metadata = 
                   8541: 				&metadata($uri,'keys', $location,$unikey,
                   8542: 					  $depthcount+1);
                   8543: 			    foreach my $meta (split(',',$metadata)) {
                   8544: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8545: 				$metathesekeys{$meta}=1;
1.339     albertel 8546: 			    }
1.1068    www      8547: 			
                   8548:                         }
1.1067    www      8549: 		    } else {
                   8550: #
                   8551: # Not importing, some other kind of non-package, non-library start tag
                   8552: # 
                   8553:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8554:                         if (defined($token->[2]->{'id'})) {
                   8555:                             $unikey.='_'.$token->[2]->{'id'};
                   8556:                         }
1.339     albertel 8557: 			if (defined($token->[2]->{'name'})) { 
                   8558: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8559: 			}
                   8560: 			$metathesekeys{$unikey}=1;
1.736     albertel 8561: 			foreach my $param (@{$token->[3]}) {
                   8562: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8563: 				$token->[2]->{$param};
1.339     albertel 8564: 			}
                   8565: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8566: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8567: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8568: 		 # only ws inside the tag, and not in default, so use default
                   8569: 		 # as value
1.599     albertel 8570: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8571: 			} elsif ( $internaltext =~ /\S/ ) {
                   8572: 		  # something interesting inside the tag
                   8573: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8574: 			} else {
1.908     albertel 8575: 		  # no interesting values, don't set a default
1.339     albertel 8576: 			}
1.172     www      8577: # end of not-a-package not-a-library import
1.339     albertel 8578: 		    }
1.172     www      8579: # end of not-a-package start tag
1.339     albertel 8580: 		}
1.172     www      8581: # the next is the end of "start tag"
1.339     albertel 8582: 	    }
                   8583: 	}
1.483     albertel 8584: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8585: 	$extension = lc($extension);
                   8586: 	if ($extension eq 'htm') { $extension='html'; }
                   8587: 
1.737     albertel 8588: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8589: 	    #no specific packages #how's our extension
                   8590: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8591: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8592: 					 \%metathesekeys);
                   8593: 	}
1.883     albertel 8594: 
                   8595: 	if (!exists($metaentry{':packages'})
                   8596: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8597: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8598: 		#no specific packages well let's get default then
                   8599: 		if ($key!~/^default&/) { next; }
1.488     albertel 8600: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8601: 					     \%metathesekeys);
                   8602: 	    }
                   8603: 	}
1.338     www      8604: # are there custom rights to evaluate
1.599     albertel 8605: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8606: 
1.338     www      8607:     #
                   8608:     # Importing a rights file here
1.339     albertel 8609:     #
                   8610: 	    unless ($depthcount) {
1.599     albertel 8611: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8612: 		my $dir=$filename;
                   8613: 		$dir=~s|[^/]*$||;
                   8614: 		$location=&filelocation($dir,$location);
1.736     albertel 8615: 		my $rights_metadata =
                   8616: 		    &metadata($uri,'keys',$location,'_rights',
                   8617: 			      $depthcount+1);
                   8618: 		foreach my $rights (split(',',$rights_metadata)) {
                   8619: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8620: 		    $metathesekeys{$rights}=1;
1.339     albertel 8621: 		}
                   8622: 	    }
                   8623: 	}
1.737     albertel 8624: 	# uniqifiy package listing
                   8625: 	my %seen;
                   8626: 	my @uniq_packages =
                   8627: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8628: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8629: 
1.1070    www      8630:         if ($importedparts) {
                   8631: # We had imported parts and need to rebuild partorder
                   8632:            $metaentry{':partorder'}='';
                   8633:            $metathesekeys{'partorder'}=1;
                   8634:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8635:                if ($origfileimportpartids[$index] eq 'part') {
                   8636: # original part, part of the problem
                   8637:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8638:                } else {
                   8639: # we have imported parts at this position
                   8640:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8641:                }
                   8642:            }
                   8643:            $metaentry{':partorder'}=~s/^\,//;
                   8644:         }
                   8645: 
1.737     albertel 8646: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8647: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8648: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8649: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8650: # this is the end of "was not already recently cached
1.71      www      8651:     }
1.599     albertel 8652:     return $metaentry{':'.$what};
1.261     albertel 8653: }
                   8654: 
1.488     albertel 8655: sub metadata_create_package_def {
1.483     albertel 8656:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8657:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8658:     if ($subp eq 'default') { next; }
                   8659:     
1.599     albertel 8660:     if (defined($metaentry{':packages'})) {
                   8661: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8662:     } else {
1.599     albertel 8663: 	$metaentry{':packages'}=$package;
1.483     albertel 8664:     }
                   8665:     my $value=$packagetab{$key};
                   8666:     my $unikey;
                   8667:     $unikey='parameter_0_'.$name;
1.599     albertel 8668:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8669:     $$metathesekeys{$unikey}=1;
1.599     albertel 8670:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8671: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8672:     }
1.599     albertel 8673:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8674: 	$metaentry{':'.$unikey}=
                   8675: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8676:     }
                   8677: }
                   8678: 
1.261     albertel 8679: sub metadata_generate_part0 {
                   8680:     my ($metadata,$metacache,$uri) = @_;
                   8681:     my %allnames;
1.737     albertel 8682:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8683: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8684: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8685: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8686: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8687: 	    $allnames{$name}=$part;
                   8688: 	  }
                   8689: 	}
                   8690:     }
                   8691:     foreach my $name (keys(%allnames)) {
                   8692:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8693:       my $key=":parameter_0_$name";
1.261     albertel 8694:       $$metacache{"$key.part"}='0';
                   8695:       $$metacache{"$key.name"}=$name;
1.428     albertel 8696:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8697: 					   $allnames{$name}.'_'.$name.
                   8698: 					   '.type'};
1.428     albertel 8699:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8700: 			     '.display'};
1.644     www      8701:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8702:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8703:       $$metacache{"$key.display"}=$olddis;
                   8704:     }
1.71      www      8705: }
                   8706: 
1.764     albertel 8707: # ------------------------------------------------------ Devalidate title cache
                   8708: 
                   8709: sub devalidate_title_cache {
                   8710:     my ($url)=@_;
                   8711:     if (!$env{'request.course.id'}) { return; }
                   8712:     my $symb=&symbread($url);
                   8713:     if (!$symb) { return; }
                   8714:     my $key=$env{'request.course.id'}."\0".$symb;
                   8715:     &devalidate_cache_new('title',$key);
                   8716: }
                   8717: 
1.1014    droeschl 8718: # ------------------------------------------------- Get the title of a course
                   8719: 
                   8720: sub current_course_title {
                   8721:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8722: }
1.301     www      8723: # ------------------------------------------------- Get the title of a resource
                   8724: 
                   8725: sub gettitle {
                   8726:     my $urlsymb=shift;
                   8727:     my $symb=&symbread($urlsymb);
1.534     albertel 8728:     if ($symb) {
1.620     albertel 8729: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8730: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8731: 	if (defined($cached)) { 
                   8732: 	    return $result;
                   8733: 	}
1.534     albertel 8734: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8735: 	my $title='';
1.907     albertel 8736: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8737: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8738: 	} else {
                   8739: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8740: 		    &GDBM_READER(),0640)) {
                   8741: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8742: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8743: 		untie(%bighash);
                   8744: 	    }
1.534     albertel 8745: 	}
                   8746: 	$title=~s/\&colon\;/\:/gs;
                   8747: 	if ($title) {
1.599     albertel 8748: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8749: 	}
                   8750: 	$urlsymb=$url;
                   8751:     }
                   8752:     my $title=&metadata($urlsymb,'title');
                   8753:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8754:     return $title;
1.301     www      8755: }
1.613     albertel 8756: 
1.614     albertel 8757: sub get_slot {
                   8758:     my ($which,$cnum,$cdom)=@_;
                   8759:     if (!$cnum || !$cdom) {
1.790     albertel 8760: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8761: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8762: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8763:     }
1.703     albertel 8764:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8765:     my %slotinfo;
                   8766:     if (exists($remembered{$key})) {
                   8767: 	$slotinfo{$which} = $remembered{$key};
                   8768:     } else {
                   8769: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8770: 	&Apache::lonhomework::showhash(%slotinfo);
                   8771: 	my ($tmp)=keys(%slotinfo);
                   8772: 	if ($tmp=~/^error:/) { return (); }
                   8773: 	$remembered{$key} = $slotinfo{$which};
                   8774:     }
1.616     albertel 8775:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8776: 	return %{$slotinfo{$which}};
                   8777:     }
                   8778:     return $slotinfo{$which};
1.614     albertel 8779: }
1.31      www      8780: # ------------------------------------------------- Update symbolic store links
                   8781: 
                   8782: sub symblist {
                   8783:     my ($mapname,%newhash)=@_;
1.438     www      8784:     $mapname=&deversion(&declutter($mapname));
1.31      www      8785:     my %hash;
1.620     albertel 8786:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8787:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8788:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8789: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8790: 		next if ($url eq 'last_known'
                   8791: 			 && $env{'form.no_update_last_known'});
                   8792: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8793: 						    $newhash{$url}->[1],
                   8794: 						    $newhash{$url}->[0]);
1.191     harris41 8795:             }
1.31      www      8796:             if (untie(%hash)) {
                   8797: 		return 'ok';
                   8798:             }
                   8799:         }
                   8800:     }
                   8801:     return 'error';
1.212     www      8802: }
                   8803: 
                   8804: # --------------------------------------------------------------- Verify a symb
                   8805: 
                   8806: sub symbverify {
1.510     www      8807:     my ($symb,$thisurl)=@_;
                   8808:     my $thisfn=$thisurl;
1.439     www      8809:     $thisfn=&declutter($thisfn);
1.215     www      8810: # direct jump to resource in page or to a sequence - will construct own symbs
                   8811:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8812: # check URL part
1.409     www      8813:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8814: 
1.431     www      8815:     unless ($url eq $thisfn) { return 0; }
1.213     www      8816: 
1.216     www      8817:     $symb=&symbclean($symb);
1.510     www      8818:     $thisurl=&deversion($thisurl);
1.439     www      8819:     $thisfn=&deversion($thisfn);
1.213     www      8820: 
                   8821:     my %bighash;
                   8822:     my $okay=0;
1.431     www      8823: 
1.620     albertel 8824:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8825:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8826:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8827:             $thisurl =~ s/\?.+$//;
                   8828:         }
1.510     www      8829:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8830:         unless ($ids) { 
1.510     www      8831:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8832:         }
                   8833:         if ($ids) {
                   8834: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8835: 	    foreach my $id (split(/\,/,$ids)) {
                   8836: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8837:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8838:                    $symb =~ s/\?.+$//;
                   8839:                }
1.216     www      8840:                if (
                   8841:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8842:    eq $symb) { 
1.620     albertel 8843: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8844: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8845: 		       $okay=1; 
                   8846: 		   }
                   8847: 	       }
1.216     www      8848: 	   }
                   8849:         }
1.213     www      8850: 	untie(%bighash);
                   8851:     }
                   8852:     return $okay;
1.31      www      8853: }
                   8854: 
1.210     www      8855: # --------------------------------------------------------------- Clean-up symb
                   8856: 
                   8857: sub symbclean {
                   8858:     my $symb=shift;
1.568     albertel 8859:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8860: # remove version from map
                   8861:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8862: 
1.210     www      8863: # remove version from URL
                   8864:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8865: 
1.507     www      8866: # remove wrapper
                   8867: 
1.510     www      8868:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8869:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8870:     return $symb;
1.409     www      8871: }
                   8872: 
                   8873: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8874: 
                   8875: sub encode_symb {
                   8876:     my ($map,$resid,$url)=@_;
                   8877:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8878: }
1.409     www      8879: 
                   8880: sub decode_symb {
1.568     albertel 8881:     my $symb=shift;
                   8882:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8883:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8884:     return (&fixversion($map),$resid,&fixversion($url));
                   8885: }
                   8886: 
                   8887: sub fixversion {
                   8888:     my $fn=shift;
1.609     banghart 8889:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8890:     my %bighash;
                   8891:     my $uri=&clutter($fn);
1.620     albertel 8892:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8893: # is this cached?
1.599     albertel 8894:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8895:     if (defined($cached)) { return $result; }
                   8896: # unfortunately not cached, or expired
1.620     albertel 8897:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8898: 	    &GDBM_READER(),0640)) {
                   8899:  	if ($bighash{'version_'.$uri}) {
                   8900:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8901:  	    unless (($version eq 'mostrecent') || 
                   8902: 		    ($version==&getversion($uri))) {
1.440     www      8903:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8904:  	    }
                   8905:  	}
                   8906:  	untie %bighash;
1.413     www      8907:     }
1.599     albertel 8908:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8909: }
                   8910: 
                   8911: sub deversion {
                   8912:     my $url=shift;
                   8913:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8914:     return $url;
1.210     www      8915: }
                   8916: 
1.31      www      8917: # ------------------------------------------------------ Return symb list entry
                   8918: 
                   8919: sub symbread {
1.249     www      8920:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8921:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8922:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8923: # no filename provided? try from environment
1.44      www      8924:     unless ($thisfn) {
1.620     albertel 8925:         if ($env{'request.symb'}) {
                   8926: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8927: 	}
1.620     albertel 8928: 	$thisfn=$env{'request.filename'};
1.44      www      8929:     }
1.569     albertel 8930:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8931: # is that filename actually a symb? Verify, clean, and return
                   8932:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8933: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8934: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8935: 	}
1.242     www      8936:     }
1.44      www      8937:     $thisfn=declutter($thisfn);
1.31      www      8938:     my %hash;
1.37      www      8939:     my %bighash;
                   8940:     my $syval='';
1.620     albertel 8941:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8942:         my $targetfn = $thisfn;
1.609     banghart 8943:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8944:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8945:         }
1.687     albertel 8946: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8947: 	    $targetfn=$1;
                   8948: 	}
1.620     albertel 8949:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8950:                       &GDBM_READER(),0640)) {
1.481     raeburn  8951: 	    $syval=$hash{$targetfn};
1.37      www      8952:             untie(%hash);
                   8953:         }
                   8954: # ---------------------------------------------------------- There was an entry
                   8955:         if ($syval) {
1.601     albertel 8956: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8957: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8958: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8959: 		    #return $env{$cache_str}='';
1.601     albertel 8960: 		#}    
                   8961: 		#$syval.=$1;
                   8962: 	    #}
1.37      www      8963:         } else {
                   8964: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8965:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8966:                             &GDBM_READER(),0640)) {
1.37      www      8967: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8968:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8969:               unless ($ids) { 
                   8970:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8971:               }
                   8972:               unless ($ids) {
                   8973: # alias?
                   8974: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8975:               }
1.37      www      8976:               if ($ids) {
                   8977: # ------------------------------------------------------------------- Has ID(s)
                   8978:                  my @possibilities=split(/\,/,$ids);
1.39      www      8979:                  if ($#possibilities==0) {
                   8980: # ----------------------------------------------- There is only one possibility
1.37      www      8981: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8982: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8983: 						    $resid,$thisfn);
1.249     www      8984:                  } elsif (!$donotrecurse) {
1.39      www      8985: # ------------------------------------------ There is more than one possibility
                   8986:                      my $realpossible=0;
1.800     albertel 8987:                      foreach my $id (@possibilities) {
                   8988: 			 my $file=$bighash{'src_'.$id};
1.39      www      8989:                          if (&allowed('bre',$file)) {
1.800     albertel 8990:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8991:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8992: 				$realpossible++;
1.626     albertel 8993:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8994: 						    $resid,$thisfn);
1.39      www      8995:                             }
                   8996: 			 }
1.191     harris41 8997:                      }
1.39      www      8998: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8999:                  } else {
                   9000:                      $syval='';
1.37      www      9001:                  }
                   9002: 	      }
                   9003:               untie(%bighash)
1.481     raeburn  9004:            }
1.31      www      9005:         }
1.62      www      9006:         if ($syval) {
1.620     albertel 9007: 	    return $env{$cache_str}=$syval;
1.62      www      9008:         }
1.31      www      9009:     }
1.949     raeburn  9010:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9011:     return $env{$cache_str}='';
1.31      www      9012: }
                   9013: 
                   9014: # ---------------------------------------------------------- Return random seed
                   9015: 
1.32      www      9016: sub numval {
                   9017:     my $txt=shift;
                   9018:     $txt=~tr/A-J/0-9/;
                   9019:     $txt=~tr/a-j/0-9/;
                   9020:     $txt=~tr/K-T/0-9/;
                   9021:     $txt=~tr/k-t/0-9/;
                   9022:     $txt=~tr/U-Z/0-5/;
                   9023:     $txt=~tr/u-z/0-5/;
                   9024:     $txt=~s/\D//g;
1.564     albertel 9025:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9026:     return int($txt);
1.368     albertel 9027: }
                   9028: 
1.484     albertel 9029: sub numval2 {
                   9030:     my $txt=shift;
                   9031:     $txt=~tr/A-J/0-9/;
                   9032:     $txt=~tr/a-j/0-9/;
                   9033:     $txt=~tr/K-T/0-9/;
                   9034:     $txt=~tr/k-t/0-9/;
                   9035:     $txt=~tr/U-Z/0-5/;
                   9036:     $txt=~tr/u-z/0-5/;
                   9037:     $txt=~s/\D//g;
                   9038:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9039:     my $total;
                   9040:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9041:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9042:     return int($total);
                   9043: }
                   9044: 
1.575     albertel 9045: sub numval3 {
                   9046:     use integer;
                   9047:     my $txt=shift;
                   9048:     $txt=~tr/A-J/0-9/;
                   9049:     $txt=~tr/a-j/0-9/;
                   9050:     $txt=~tr/K-T/0-9/;
                   9051:     $txt=~tr/k-t/0-9/;
                   9052:     $txt=~tr/U-Z/0-5/;
                   9053:     $txt=~tr/u-z/0-5/;
                   9054:     $txt=~s/\D//g;
                   9055:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9056:     my $total;
                   9057:     foreach my $val (@txts) { $total+=$val; }
                   9058:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9059:     return $total;
                   9060: }
                   9061: 
1.675     albertel 9062: sub digest {
                   9063:     my ($data)=@_;
                   9064:     my $digest=&Digest::MD5::md5($data);
                   9065:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9066:     my ($e,$f);
                   9067:     {
                   9068:         use integer;
                   9069:         $e=($a+$b);
                   9070:         $f=($c+$d);
                   9071:         if ($_64bit) {
                   9072:             $e=(($e<<32)>>32);
                   9073:             $f=(($f<<32)>>32);
                   9074:         }
                   9075:     }
                   9076:     if (wantarray) {
                   9077: 	return ($e,$f);
                   9078:     } else {
                   9079: 	my $g;
                   9080: 	{
                   9081: 	    use integer;
                   9082: 	    $g=($e+$f);
                   9083: 	    if ($_64bit) {
                   9084: 		$g=(($g<<32)>>32);
                   9085: 	    }
                   9086: 	}
                   9087: 	return $g;
                   9088:     }
                   9089: }
                   9090: 
1.368     albertel 9091: sub latest_rnd_algorithm_id {
1.675     albertel 9092:     return '64bit5';
1.366     albertel 9093: }
1.32      www      9094: 
1.503     albertel 9095: sub get_rand_alg {
                   9096:     my ($courseid)=@_;
1.790     albertel 9097:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9098:     if ($courseid) {
1.620     albertel 9099: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9100:     }
                   9101:     return &latest_rnd_algorithm_id();
                   9102: }
                   9103: 
1.562     albertel 9104: sub validCODE {
                   9105:     my ($CODE)=@_;
                   9106:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9107:     return 0;
                   9108: }
                   9109: 
1.491     albertel 9110: sub getCODE {
1.620     albertel 9111:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9112:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9113: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9114: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9115: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9116:     }
                   9117:     return undef;
                   9118: }
                   9119: 
1.31      www      9120: sub rndseed {
1.155     albertel 9121:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9122:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9123:     if (!defined($symb)) {
1.366     albertel 9124: 	unless ($symb=$wsymb) { return time; }
                   9125:     }
                   9126:     if (!$courseid) { $courseid=$wcourseid; }
                   9127:     if (!$domain) { $domain=$wdomain; }
                   9128:     if (!$username) { $username=$wusername }
1.503     albertel 9129:     my $which=&get_rand_alg();
1.803     albertel 9130: 
1.491     albertel 9131:     if (defined(&getCODE())) {
1.675     albertel 9132: 	if ($which eq '64bit5') {
                   9133: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9134: 	} elsif ($which eq '64bit4') {
1.575     albertel 9135: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9136: 	} else {
                   9137: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9138: 	}
1.675     albertel 9139:     } elsif ($which eq '64bit5') {
                   9140: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9141:     } elsif ($which eq '64bit4') {
                   9142: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9143:     } elsif ($which eq '64bit3') {
                   9144: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9145:     } elsif ($which eq '64bit2') {
                   9146: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9147:     } elsif ($which eq '64bit') {
                   9148: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9149:     }
                   9150:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9151: }
                   9152: 
                   9153: sub rndseed_32bit {
                   9154:     my ($symb,$courseid,$domain,$username)=@_;
                   9155:     {
                   9156: 	use integer;
                   9157: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9158: 	my $symbseed=numval($symb) << 22;
                   9159: 	my $namechck=unpack("%32C*",$username) << 17;
                   9160: 	my $nameseed=numval($username) << 12;
                   9161: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9162: 	my $courseseed=unpack("%32C*",$courseid);
                   9163: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9164: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9165: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9166: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9167: 	return $num;
                   9168:     }
                   9169: }
                   9170: 
                   9171: sub rndseed_64bit {
                   9172:     my ($symb,$courseid,$domain,$username)=@_;
                   9173:     {
                   9174: 	use integer;
                   9175: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9176: 	my $symbseed=numval($symb) << 10;
                   9177: 	my $namechck=unpack("%32S*",$username);
                   9178: 	
                   9179: 	my $nameseed=numval($username) << 21;
                   9180: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9181: 	my $courseseed=unpack("%32S*",$courseid);
                   9182: 	
                   9183: 	my $num1=$symbchck+$symbseed+$namechck;
                   9184: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9185: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9186: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9187: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9188: 	return "$num1,$num2";
1.155     albertel 9189:     }
1.366     albertel 9190: }
                   9191: 
1.443     albertel 9192: sub rndseed_64bit2 {
                   9193:     my ($symb,$courseid,$domain,$username)=@_;
                   9194:     {
                   9195: 	use integer;
                   9196: 	# strings need to be an even # of cahracters long, it it is odd the
                   9197:         # last characters gets thrown away
                   9198: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9199: 	my $symbseed=numval($symb) << 10;
                   9200: 	my $namechck=unpack("%32S*",$username.' ');
                   9201: 	
                   9202: 	my $nameseed=numval($username) << 21;
1.501     albertel 9203: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9204: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9205: 	
                   9206: 	my $num1=$symbchck+$symbseed+$namechck;
                   9207: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9208: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9209: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9210: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9211: 	return "$num1,$num2";
                   9212:     }
                   9213: }
                   9214: 
                   9215: sub rndseed_64bit3 {
                   9216:     my ($symb,$courseid,$domain,$username)=@_;
                   9217:     {
                   9218: 	use integer;
                   9219: 	# strings need to be an even # of cahracters long, it it is odd the
                   9220:         # last characters gets thrown away
                   9221: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9222: 	my $symbseed=numval2($symb) << 10;
                   9223: 	my $namechck=unpack("%32S*",$username.' ');
                   9224: 	
                   9225: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9226: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9227: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9228: 	
                   9229: 	my $num1=$symbchck+$symbseed+$namechck;
                   9230: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9231: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9232: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9233: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9234: 	
1.503     albertel 9235: 	return "$num1:$num2";
1.443     albertel 9236:     }
                   9237: }
                   9238: 
1.575     albertel 9239: sub rndseed_64bit4 {
                   9240:     my ($symb,$courseid,$domain,$username)=@_;
                   9241:     {
                   9242: 	use integer;
                   9243: 	# strings need to be an even # of cahracters long, it it is odd the
                   9244:         # last characters gets thrown away
                   9245: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9246: 	my $symbseed=numval3($symb) << 10;
                   9247: 	my $namechck=unpack("%32S*",$username.' ');
                   9248: 	
                   9249: 	my $nameseed=numval3($username) << 21;
                   9250: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9251: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9252: 	
                   9253: 	my $num1=$symbchck+$symbseed+$namechck;
                   9254: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9255: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9256: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9257: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9258: 	
                   9259: 	return "$num1:$num2";
                   9260:     }
                   9261: }
                   9262: 
1.675     albertel 9263: sub rndseed_64bit5 {
                   9264:     my ($symb,$courseid,$domain,$username)=@_;
                   9265:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9266:     return "$num1:$num2";
                   9267: }
                   9268: 
1.366     albertel 9269: sub rndseed_CODE_64bit {
                   9270:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9271:     {
1.366     albertel 9272: 	use integer;
1.443     albertel 9273: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9274: 	my $symbseed=numval2($symb);
1.491     albertel 9275: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9276: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9277: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9278: 	my $num1=$symbseed+$CODEchck;
                   9279: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9280: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9281: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9282: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9283: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9284: 	return "$num1:$num2";
1.366     albertel 9285:     }
                   9286: }
                   9287: 
1.575     albertel 9288: sub rndseed_CODE_64bit4 {
                   9289:     my ($symb,$courseid,$domain,$username)=@_;
                   9290:     {
                   9291: 	use integer;
                   9292: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9293: 	my $symbseed=numval3($symb);
                   9294: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9295: 	my $CODEseed=numval3(&getCODE());
                   9296: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   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.575     albertel 9301: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9302: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9303: 	return "$num1:$num2";
                   9304:     }
                   9305: }
                   9306: 
1.675     albertel 9307: sub rndseed_CODE_64bit5 {
                   9308:     my ($symb,$courseid,$domain,$username)=@_;
                   9309:     my $code = &getCODE();
                   9310:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9311:     return "$num1:$num2";
                   9312: }
                   9313: 
1.366     albertel 9314: sub setup_random_from_rndseed {
                   9315:     my ($rndseed)=@_;
1.503     albertel 9316:     if ($rndseed =~/([,:])/) {
                   9317: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9318: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9319:     } else {
                   9320: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9321:     }
1.36      albertel 9322: }
                   9323: 
1.474     albertel 9324: sub latest_receipt_algorithm_id {
1.835     albertel 9325:     return 'receipt3';
1.474     albertel 9326: }
                   9327: 
1.480     www      9328: sub recunique {
                   9329:     my $fucourseid=shift;
                   9330:     my $unique;
1.835     albertel 9331:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9332: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9333: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9334:     } else {
                   9335: 	$unique=$perlvar{'lonReceipt'};
                   9336:     }
                   9337:     return unpack("%32C*",$unique);
                   9338: }
                   9339: 
                   9340: sub recprefix {
                   9341:     my $fucourseid=shift;
                   9342:     my $prefix;
1.835     albertel 9343:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9344: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9345: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9346:     } else {
                   9347: 	$prefix=$perlvar{'lonHostID'};
                   9348:     }
                   9349:     return unpack("%32C*",$prefix);
                   9350: }
                   9351: 
1.76      www      9352: sub ireceipt {
1.474     albertel 9353:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9354: 
                   9355:     my $return =&recprefix($fucourseid).'-';
                   9356: 
                   9357:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9358: 	$env{'request.state'} eq 'construct') {
                   9359: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9360: 	return $return;
                   9361:     }
                   9362: 
1.76      www      9363:     my $cuname=unpack("%32C*",$funame);
                   9364:     my $cudom=unpack("%32C*",$fudom);
                   9365:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9366:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9367:     my $cunique=&recunique($fucourseid);
1.474     albertel 9368:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9369:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9370: 
1.790     albertel 9371: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9372: 			       
                   9373: 	$return.= ($cunique%$cuname+
                   9374: 		   $cunique%$cudom+
                   9375: 		   $cusymb%$cuname+
                   9376: 		   $cusymb%$cudom+
                   9377: 		   $cucourseid%$cuname+
                   9378: 		   $cucourseid%$cudom+
                   9379: 		   $cpart%$cuname+
                   9380: 		   $cpart%$cudom);
                   9381:     } else {
                   9382: 	$return.= ($cunique%$cuname+
                   9383: 		   $cunique%$cudom+
                   9384: 		   $cusymb%$cuname+
                   9385: 		   $cusymb%$cudom+
                   9386: 		   $cucourseid%$cuname+
                   9387: 		   $cucourseid%$cudom);
                   9388:     }
                   9389:     return $return;
1.76      www      9390: }
                   9391: 
                   9392: sub receipt {
1.474     albertel 9393:     my ($part)=@_;
1.790     albertel 9394:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9395:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9396: }
1.260     ng       9397: 
1.790     albertel 9398: sub whichuser {
                   9399:     my ($passedsymb)=@_;
                   9400:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9401:     if (defined($env{'form.grade_symb'})) {
                   9402: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9403: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9404: 	if (!$allowed &&
                   9405: 	    exists($env{'request.course.sec'}) &&
                   9406: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9407: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9408: 			      '/'.$env{'request.course.sec'});
                   9409: 	}
                   9410: 	if ($allowed) {
                   9411: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9412: 	    $courseid=$tmp_courseid;
                   9413: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9414: 	    ($name)=&get_env_multiple('form.grade_username');
                   9415: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9416: 	}
                   9417:     }
                   9418:     if (!$passedsymb) {
                   9419: 	$symb=&symbread();
                   9420:     } else {
                   9421: 	$symb=$passedsymb;
                   9422:     }
                   9423:     $courseid=$env{'request.course.id'};
                   9424:     $domain=$env{'user.domain'};
                   9425:     $name=$env{'user.name'};
                   9426:     if ($name eq 'public' && $domain eq 'public') {
                   9427: 	if (!defined($env{'form.username'})) {
                   9428: 	    $env{'form.username'}.=time.rand(10000000);
                   9429: 	}
                   9430: 	$name.=$env{'form.username'};
                   9431:     }
                   9432:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9433: 
                   9434: }
                   9435: 
1.36      albertel 9436: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9437: # returns either the contents of the file or 
                   9438: # -1 if the file doesn't exist
1.481     raeburn  9439: #
                   9440: # if the target is a file that was uploaded via DOCS, 
                   9441: # a check will be made to see if a current copy exists on the local server,
                   9442: # if it does this will be served, otherwise a copy will be retrieved from
                   9443: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9444: # the local server.   
1.472     albertel 9445: 
1.36      albertel 9446: sub getfile {
1.538     albertel 9447:     my ($file) = @_;
1.609     banghart 9448:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9449:     &repcopy($file);
                   9450:     return &readfile($file);
                   9451: }
                   9452: 
                   9453: sub repcopy_userfile {
                   9454:     my ($file)=@_;
1.609     banghart 9455:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9456:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9457:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9458: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9459:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9460:     if (-e "$file") {
1.828     www      9461: # we already have a local copy, check it out
1.538     albertel 9462: 	my @fileinfo = stat($file);
1.828     www      9463: 	my $rtncode;
                   9464: 	my $info;
1.538     albertel 9465: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9466: 	if ($lwpresp ne 'ok') {
1.828     www      9467: # there is no such file anymore, even though we had a local copy
1.482     albertel 9468: 	    if ($rtncode eq '404') {
1.538     albertel 9469: 		unlink($file);
1.482     albertel 9470: 	    }
                   9471: 	    return -1;
                   9472: 	}
                   9473: 	if ($info < $fileinfo[9]) {
1.828     www      9474: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9475: 	    return 'ok';
1.828     www      9476: 	} else {
                   9477: # the file is outdated, get rid of it
                   9478: 	    unlink($file);
1.482     albertel 9479: 	}
1.828     www      9480:     }
                   9481: # one way or the other, at this point, we don't have the file
                   9482: # construct the correct path for the file
                   9483:     my @parts = ($cdom,$cnum); 
                   9484:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9485: 	push @parts, split(/\//,$1);
                   9486:     }
                   9487:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9488:     foreach my $part (@parts) {
                   9489: 	$path .= '/'.$part;
                   9490: 	if (!-e $path) {
                   9491: 	    mkdir($path,0770);
1.482     albertel 9492: 	}
                   9493:     }
1.828     www      9494: # now the path exists for sure
                   9495: # get a user agent
                   9496:     my $ua=new LWP::UserAgent;
                   9497:     my $transferfile=$file.'.in.transfer';
                   9498: # FIXME: this should flock
                   9499:     if (-e $transferfile) { return 'ok'; }
                   9500:     my $request;
                   9501:     $uri=~s/^\///;
1.980     raeburn  9502:     my $homeserver = &homeserver($cnum,$cdom);
                   9503:     my $protocol = $protocol{$homeserver};
                   9504:     $protocol = 'http' if ($protocol ne 'https');
                   9505:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9506:     my $response=$ua->request($request,$transferfile);
                   9507: # did it work?
                   9508:     if ($response->is_error()) {
                   9509: 	unlink($transferfile);
                   9510: 	&logthis("Userfile repcopy failed for $uri");
                   9511: 	return -1;
                   9512:     }
                   9513: # worked, rename the transfer file
                   9514:     rename($transferfile,$file);
1.607     raeburn  9515:     return 'ok';
1.481     raeburn  9516: }
                   9517: 
1.517     albertel 9518: sub tokenwrapper {
                   9519:     my $uri=shift;
1.980     raeburn  9520:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9521:     $uri=~s|^/||;
1.620     albertel 9522:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9523:     my $token=$1;
1.552     albertel 9524:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9525:     if ($udom && $uname && $file) {
                   9526: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9527:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9528:         my $homeserver = &homeserver($uname,$udom);
                   9529:         my $protocol = $protocol{$homeserver};
                   9530:         $protocol = 'http' if ($protocol ne 'https');
                   9531:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9532:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9533:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9534:     } else {
                   9535:         return '/adm/notfound.html';
                   9536:     }
                   9537: }
                   9538: 
1.828     www      9539: # call with reqtype HEAD: get last modification time
                   9540: # call with reqtype GET: get the file contents
                   9541: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9542: #
1.481     raeburn  9543: sub getuploaded {
                   9544:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9545:     $uri=~s/^\///;
1.980     raeburn  9546:     my $homeserver = &homeserver($cnum,$cdom);
                   9547:     my $protocol = $protocol{$homeserver};
                   9548:     $protocol = 'http' if ($protocol ne 'https');
                   9549:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9550:     my $ua=new LWP::UserAgent;
                   9551:     my $request=new HTTP::Request($reqtype,$uri);
                   9552:     my $response=$ua->request($request);
                   9553:     $$rtncode = $response->code;
1.482     albertel 9554:     if (! $response->is_success()) {
                   9555: 	return 'failed';
                   9556:     }      
                   9557:     if ($reqtype eq 'HEAD') {
1.486     www      9558: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9559:     } elsif ($reqtype eq 'GET') {
                   9560: 	$$info = $response->content;
1.472     albertel 9561:     }
1.482     albertel 9562:     return 'ok';
1.36      albertel 9563: }
                   9564: 
1.481     raeburn  9565: sub readfile {
                   9566:     my $file = shift;
                   9567:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9568:     my $fh;
                   9569:     open($fh,"<$file");
                   9570:     my $a='';
1.800     albertel 9571:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9572:     return $a;
                   9573: }
                   9574: 
1.36      albertel 9575: sub filelocation {
1.590     banghart 9576:     my ($dir,$file) = @_;
                   9577:     my $location;
                   9578:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9579: 
                   9580:     if ($file =~ m-^/adm/-) {
                   9581: 	$file=~s-^/adm/wrapper/-/-;
                   9582: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9583:     }
1.882     albertel 9584: 
1.590     banghart 9585:     if ($file=~m:^/~:) { # is a contruction space reference
                   9586:         $location = $file;
                   9587:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9588:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9589: 	# is a correct contruction space reference
                   9590:         $location = $file;
1.956     raeburn  9591:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9592:         $location = $file;
1.609     banghart 9593:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9594:         my ($udom,$uname,$filename)=
1.811     albertel 9595:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9596:         my $home=&homeserver($uname,$udom);
                   9597:         my $is_me=0;
                   9598:         my @ids=&current_machine_ids();
                   9599:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9600:         if ($is_me) {
1.955     raeburn  9601:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9602:         } else {
                   9603:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9604:   	      $udom.'/'.$uname.'/'.$filename;
                   9605:         }
1.882     albertel 9606:     } elsif ($file =~ m-^/adm/-) {
                   9607: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9608:     } else {
                   9609:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9610:         $file=~s:^/res/:/:;
                   9611:         if ( !( $file =~ m:^/:) ) {
                   9612:             $location = $dir. '/'.$file;
                   9613:         } else {
                   9614:             $location = '/home/httpd/html/res'.$file;
                   9615:         }
1.59      albertel 9616:     }
1.590     banghart 9617:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9618:     while ($location=~m{/\.\./}) {
                   9619: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9620: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9621: 	} else {
                   9622: 	    $location=~ s{/\.\./}{/}g;
                   9623: 	}
                   9624:     } #remove dir/..
1.590     banghart 9625:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9626:     return $location;
1.46      www      9627: }
1.36      albertel 9628: 
1.46      www      9629: sub hreflocation {
                   9630:     my ($dir,$file)=@_;
1.980     raeburn  9631:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9632: 	$file=filelocation($dir,$file);
1.700     albertel 9633:     } elsif ($file=~m-^/adm/-) {
                   9634: 	$file=~s-^/adm/wrapper/-/-;
                   9635: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9636:     }
                   9637:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9638: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9639:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9640: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9641:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9642: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9643: 	    -/uploaded/$1/$2/-x;
1.46      www      9644:     }
1.913     albertel 9645:     if ($file=~ m{^/userfiles/}) {
                   9646: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9647:     }
1.462     albertel 9648:     return $file;
1.465     albertel 9649: }
                   9650: 
                   9651: sub current_machine_domains {
1.853     albertel 9652:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9653: }
                   9654: 
                   9655: sub machine_domains {
                   9656:     my ($hostname) = @_;
1.465     albertel 9657:     my @domains;
1.838     albertel 9658:     my %hostname = &all_hostnames();
1.465     albertel 9659:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9660: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9661: 	if ($hostname eq $name) {
1.844     albertel 9662: 	    push(@domains,&host_domain($id));
1.465     albertel 9663: 	}
                   9664:     }
                   9665:     return @domains;
                   9666: }
                   9667: 
                   9668: sub current_machine_ids {
1.853     albertel 9669:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9670: }
                   9671: 
                   9672: sub machine_ids {
                   9673:     my ($hostname) = @_;
                   9674:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9675:     my @ids;
1.888     albertel 9676:     my %name_to_host = &all_names();
1.889     albertel 9677:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9678: 	return @{ $name_to_host{$hostname} };
                   9679:     }
                   9680:     return;
1.31      www      9681: }
                   9682: 
1.824     raeburn  9683: sub additional_machine_domains {
                   9684:     my @domains;
                   9685:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9686:     while( my $line = <$fh>) {
                   9687:         $line =~ s/\s//g;
                   9688:         push(@domains,$line);
                   9689:     }
                   9690:     return @domains;
                   9691: }
                   9692: 
                   9693: sub default_login_domain {
                   9694:     my $domain = $perlvar{'lonDefDomain'};
                   9695:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9696:     foreach my $posdom (&current_machine_domains(),
                   9697:                         &additional_machine_domains()) {
                   9698:         if (lc($posdom) eq lc($testdomain)) {
                   9699:             $domain=$posdom;
                   9700:             last;
                   9701:         }
                   9702:     }
                   9703:     return $domain;
                   9704: }
                   9705: 
1.31      www      9706: # ------------------------------------------------------------- Declutters URLs
                   9707: 
                   9708: sub declutter {
                   9709:     my $thisfn=shift;
1.569     albertel 9710:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9711:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9712:     $thisfn=~s/^\///;
1.697     albertel 9713:     $thisfn=~s|^adm/wrapper/||;
                   9714:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9715:     $thisfn=~s/^res\///;
1.1032    raeburn  9716:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9717:         $thisfn=~s/\?.+$//;
                   9718:     }
1.268     www      9719:     return $thisfn;
                   9720: }
                   9721: 
                   9722: # ------------------------------------------------------------- Clutter up URLs
                   9723: 
                   9724: sub clutter {
                   9725:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9726:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9727: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9728:        $thisfn='/res'.$thisfn; 
                   9729:     }
1.1031    raeburn  9730:     if ($thisfn !~m|^/adm|) {
                   9731: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9732: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9733: 	} else {
                   9734: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9735: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9736: 	    if ($embstyle eq 'ssi'
                   9737: 		|| ($embstyle eq 'hdn')
                   9738: 		|| ($embstyle eq 'rat')
                   9739: 		|| ($embstyle eq 'prv')
                   9740: 		|| ($embstyle eq 'ign')) {
                   9741: 		#do nothing with these
                   9742: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9743: 		|| ($embstyle eq 'emb')
                   9744: 		|| ($embstyle eq 'wrp')) {
                   9745: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9746: 	    } elsif ($embstyle eq 'unk'
                   9747: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9748: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9749: 	    } else {
1.718     www      9750: #		&logthis("Got a blank emb style");
1.695     albertel 9751: 	    }
1.694     albertel 9752: 	}
                   9753:     }
1.31      www      9754:     return $thisfn;
1.12      www      9755: }
                   9756: 
1.787     albertel 9757: sub clutter_with_no_wrapper {
                   9758:     my $uri = &clutter(shift);
                   9759:     if ($uri =~ m-^/adm/-) {
                   9760: 	$uri =~ s-^/adm/wrapper/-/-;
                   9761: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9762:     }
                   9763:     return $uri;
                   9764: }
                   9765: 
1.557     albertel 9766: sub freeze_escape {
                   9767:     my ($value)=@_;
                   9768:     if (ref($value)) {
                   9769: 	$value=&nfreeze($value);
                   9770: 	return '__FROZEN__'.&escape($value);
                   9771:     }
                   9772:     return &escape($value);
                   9773: }
                   9774: 
1.11      www      9775: 
1.557     albertel 9776: sub thaw_unescape {
                   9777:     my ($value)=@_;
                   9778:     if ($value =~ /^__FROZEN__/) {
                   9779: 	substr($value,0,10,undef);
                   9780: 	$value=&unescape($value);
                   9781: 	return &thaw($value);
                   9782:     }
                   9783:     return &unescape($value);
                   9784: }
                   9785: 
1.436     albertel 9786: sub correct_line_ends {
                   9787:     my ($result)=@_;
                   9788:     $$result =~s/\r\n/\n/mg;
                   9789:     $$result =~s/\r/\n/mg;
1.415     albertel 9790: }
1.1       albertel 9791: # ================================================================ Main Program
                   9792: 
1.184     www      9793: sub goodbye {
1.204     albertel 9794:    &logthis("Starting Shut down");
1.443     albertel 9795: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9796:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9797: #converted
1.599     albertel 9798: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9799:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9800: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9801: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9802: #1.1 only
1.870     albertel 9803: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9804: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9805: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9806: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9807:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9808:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9809:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9810:    &flushcourselogs();
                   9811:    &logthis("Shutting down");
                   9812: }
                   9813: 
1.852     albertel 9814: sub get_dns {
1.869     albertel 9815:     my ($url,$func,$ignore_cache) = @_;
                   9816:     if (!$ignore_cache) {
                   9817: 	my ($content,$cached)=
                   9818: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9819: 	if ($cached) {
                   9820: 	    &$func($content);
                   9821: 	    return;
                   9822: 	}
                   9823:     }
                   9824: 
                   9825:     my %alldns;
1.852     albertel 9826:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9827:     foreach my $dns (<$config>) {
                   9828: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9829:         my $line = $1;
                   9830:         my ($host,$protocol) = split(/:/,$line);
                   9831:         if ($protocol ne 'https') {
                   9832:             $protocol = 'http';
                   9833:         }
                   9834: 	$alldns{$host} = $protocol;
1.869     albertel 9835:     }
                   9836:     while (%alldns) {
                   9837: 	my ($dns) = keys(%alldns);
1.852     albertel 9838: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9839: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9840: 	my $response=$ua->request($request);
1.979     raeburn  9841:         delete($alldns{$dns});
1.852     albertel 9842: 	next if ($response->is_error());
                   9843: 	my @content = split("\n",$response->content);
1.869     albertel 9844: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9845: 	&$func(\@content);
1.869     albertel 9846: 	return;
1.852     albertel 9847:     }
                   9848:     close($config);
1.871     albertel 9849:     my $which = (split('/',$url))[3];
                   9850:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9851:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9852:     my @content = <$config>;
                   9853:     &$func(\@content);
                   9854:     return;
1.852     albertel 9855: }
1.327     albertel 9856: # ------------------------------------------------------------ Read domain file
                   9857: {
1.852     albertel 9858:     my $loaded;
1.846     albertel 9859:     my %domain;
                   9860: 
1.852     albertel 9861:     sub parse_domain_tab {
                   9862: 	my ($lines) = @_;
                   9863: 	foreach my $line (@$lines) {
                   9864: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9865: 
1.846     albertel 9866: 	    chomp($line);
1.852     albertel 9867: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9868: 	    my %this_domain;
                   9869: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9870: 			       'lang_def', 'city', 'longi', 'lati',
                   9871: 			       'primary') {
                   9872: 		$this_domain{$field} = shift(@elements);
                   9873: 	    }
                   9874: 	    $domain{$name} = \%this_domain;
1.852     albertel 9875: 	}
                   9876:     }
1.864     albertel 9877: 
                   9878:     sub reset_domain_info {
                   9879: 	undef($loaded);
                   9880: 	undef(%domain);
                   9881:     }
                   9882: 
1.852     albertel 9883:     sub load_domain_tab {
1.869     albertel 9884: 	my ($ignore_cache) = @_;
                   9885: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9886: 	my $fh;
                   9887: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9888: 	    my @lines = <$fh>;
                   9889: 	    &parse_domain_tab(\@lines);
1.448     albertel 9890: 	}
1.852     albertel 9891: 	close($fh);
                   9892: 	$loaded = 1;
1.327     albertel 9893:     }
1.846     albertel 9894: 
                   9895:     sub domain {
1.852     albertel 9896: 	&load_domain_tab() if (!$loaded);
                   9897: 
1.846     albertel 9898: 	my ($name,$what) = @_;
                   9899: 	return if ( !exists($domain{$name}) );
                   9900: 
                   9901: 	if (!$what) {
                   9902: 	    return $domain{$name}{'description'};
                   9903: 	}
                   9904: 	return $domain{$name}{$what};
                   9905:     }
1.974     raeburn  9906: 
                   9907:     sub domain_info {
                   9908:         &load_domain_tab() if (!$loaded);
                   9909:         return %domain;
                   9910:     }
                   9911: 
1.327     albertel 9912: }
                   9913: 
                   9914: 
1.1       albertel 9915: # ------------------------------------------------------------- Read hosts file
                   9916: {
1.838     albertel 9917:     my %hostname;
1.844     albertel 9918:     my %hostdom;
1.845     albertel 9919:     my %libserv;
1.852     albertel 9920:     my $loaded;
1.888     albertel 9921:     my %name_to_host;
1.1074    raeburn  9922:     my %internetdom;
1.852     albertel 9923: 
                   9924:     sub parse_hosts_tab {
                   9925: 	my ($file) = @_;
                   9926: 	foreach my $configline (@$file) {
                   9927: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9928: 	    next if ($configline =~ /^\^/);
                   9929: 	    chomp($configline);
1.1074    raeburn  9930: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 9931: 	    $name=~s/\s//g;
                   9932: 	    if ($id && $domain && $role && $name) {
                   9933: 		$hostname{$id}=$name;
1.888     albertel 9934: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9935: 		$hostdom{$id}=$domain;
                   9936: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9937:                 if (defined($protocol)) {
                   9938:                     if ($protocol eq 'https') {
                   9939:                         $protocol{$id} = $protocol;
                   9940:                     } else {
                   9941:                         $protocol{$id} = 'http'; 
                   9942:                     }
1.968     raeburn  9943:                 } else {
1.969     raeburn  9944:                     $protocol{$id} = 'http';
1.968     raeburn  9945:                 }
1.1074    raeburn  9946:                 if (defined($intdom)) {
                   9947:                     $internetdom{$id} = $intdom;
                   9948:                 }
1.852     albertel 9949: 	    }
                   9950: 	}
                   9951:     }
1.864     albertel 9952:     
                   9953:     sub reset_hosts_info {
1.897     albertel 9954: 	&purge_remembered();
1.864     albertel 9955: 	&reset_domain_info();
                   9956: 	&reset_hosts_ip_info();
1.892     albertel 9957: 	undef(%name_to_host);
1.864     albertel 9958: 	undef(%hostname);
                   9959: 	undef(%hostdom);
                   9960: 	undef(%libserv);
                   9961: 	undef($loaded);
                   9962:     }
1.1       albertel 9963: 
1.852     albertel 9964:     sub load_hosts_tab {
1.869     albertel 9965: 	my ($ignore_cache) = @_;
                   9966: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9967: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9968: 	my @config = <$config>;
                   9969: 	&parse_hosts_tab(\@config);
                   9970: 	close($config);
                   9971: 	$loaded=1;
1.1       albertel 9972:     }
1.852     albertel 9973: 
1.838     albertel 9974:     sub hostname {
1.852     albertel 9975: 	&load_hosts_tab() if (!$loaded);
                   9976: 
1.838     albertel 9977: 	my ($lonid) = @_;
                   9978: 	return $hostname{$lonid};
                   9979:     }
1.845     albertel 9980: 
1.838     albertel 9981:     sub all_hostnames {
1.852     albertel 9982: 	&load_hosts_tab() if (!$loaded);
                   9983: 
1.838     albertel 9984: 	return %hostname;
                   9985:     }
1.845     albertel 9986: 
1.888     albertel 9987:     sub all_names {
                   9988: 	&load_hosts_tab() if (!$loaded);
                   9989: 
                   9990: 	return %name_to_host;
                   9991:     }
                   9992: 
1.974     raeburn  9993:     sub all_host_domain {
                   9994:         &load_hosts_tab() if (!$loaded);
                   9995:         return %hostdom;
                   9996:     }
                   9997: 
1.845     albertel 9998:     sub is_library {
1.852     albertel 9999: 	&load_hosts_tab() if (!$loaded);
                   10000: 
1.845     albertel 10001: 	return exists($libserv{$_[0]});
                   10002:     }
                   10003: 
                   10004:     sub all_library {
1.852     albertel 10005: 	&load_hosts_tab() if (!$loaded);
                   10006: 
1.845     albertel 10007: 	return %libserv;
                   10008:     }
                   10009: 
1.1062    droeschl 10010:     sub unique_library {
                   10011: 	#2x reverse removes all hostnames that appear more than once
                   10012:         my %unique = reverse &all_library();
                   10013:         return reverse %unique;
                   10014:     }
                   10015: 
1.841     albertel 10016:     sub get_servers {
1.852     albertel 10017: 	&load_hosts_tab() if (!$loaded);
                   10018: 
1.841     albertel 10019: 	my ($domain,$type) = @_;
                   10020: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10021: 	                                          : %hostname;
                   10022: 	my %result;
1.842     albertel 10023: 	if (ref($domain) eq 'ARRAY') {
                   10024: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10025: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10026: 		    $result{$host} = $hostname;
                   10027: 		}
                   10028: 	    }
                   10029: 	} else {
                   10030: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10031: 		if ($hostdom{$host} eq $domain) {
                   10032: 		    $result{$host} = $hostname;
                   10033: 		}
1.841     albertel 10034: 	    }
                   10035: 	}
                   10036: 	return %result;
                   10037:     }
1.845     albertel 10038: 
1.1062    droeschl 10039:     sub get_unique_servers {
                   10040:         my %unique = reverse &get_servers(@_);
                   10041: 	return reverse %unique;
                   10042:     }
                   10043: 
1.844     albertel 10044:     sub host_domain {
1.852     albertel 10045: 	&load_hosts_tab() if (!$loaded);
                   10046: 
1.844     albertel 10047: 	my ($lonid) = @_;
                   10048: 	return $hostdom{$lonid};
                   10049:     }
                   10050: 
1.841     albertel 10051:     sub all_domains {
1.852     albertel 10052: 	&load_hosts_tab() if (!$loaded);
                   10053: 
1.841     albertel 10054: 	my %seen;
                   10055: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10056: 	return @uniq;
                   10057:     }
1.1074    raeburn  10058: 
                   10059:     sub internet_dom {
                   10060:         &load_hosts_tab() if (!$loaded);
                   10061: 
                   10062:         my ($lonid) = @_;
                   10063:         return $internetdom{$lonid};
                   10064:     }
1.1       albertel 10065: }
                   10066: 
1.847     albertel 10067: { 
                   10068:     my %iphost;
1.856     albertel 10069:     my %name_to_ip;
                   10070:     my %lonid_to_ip;
1.869     albertel 10071: 
1.847     albertel 10072:     sub get_hosts_from_ip {
                   10073: 	my ($ip) = @_;
                   10074: 	my %iphosts = &get_iphost();
                   10075: 	if (ref($iphosts{$ip})) {
                   10076: 	    return @{$iphosts{$ip}};
                   10077: 	}
                   10078: 	return;
1.839     albertel 10079:     }
1.864     albertel 10080:     
                   10081:     sub reset_hosts_ip_info {
                   10082: 	undef(%iphost);
                   10083: 	undef(%name_to_ip);
                   10084: 	undef(%lonid_to_ip);
                   10085:     }
1.856     albertel 10086: 
                   10087:     sub get_host_ip {
                   10088: 	my ($lonid) = @_;
                   10089: 	if (exists($lonid_to_ip{$lonid})) {
                   10090: 	    return $lonid_to_ip{$lonid};
                   10091: 	}
                   10092: 	my $name=&hostname($lonid);
                   10093:    	my $ip = gethostbyname($name);
                   10094: 	return if (!$ip || length($ip) ne 4);
                   10095: 	$ip=inet_ntoa($ip);
                   10096: 	$name_to_ip{$name}   = $ip;
                   10097: 	$lonid_to_ip{$lonid} = $ip;
                   10098: 	return $ip;
                   10099:     }
1.847     albertel 10100:     
                   10101:     sub get_iphost {
1.869     albertel 10102: 	my ($ignore_cache) = @_;
1.894     albertel 10103: 
1.869     albertel 10104: 	if (!$ignore_cache) {
                   10105: 	    if (%iphost) {
                   10106: 		return %iphost;
                   10107: 	    }
                   10108: 	    my ($ip_info,$cached)=
                   10109: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10110: 	    if ($cached) {
                   10111: 		%iphost      = %{$ip_info->[0]};
                   10112: 		%name_to_ip  = %{$ip_info->[1]};
                   10113: 		%lonid_to_ip = %{$ip_info->[2]};
                   10114: 		return %iphost;
                   10115: 	    }
                   10116: 	}
1.894     albertel 10117: 
                   10118: 	# get yesterday's info for fallback
                   10119: 	my %old_name_to_ip;
                   10120: 	my ($ip_info,$cached)=
                   10121: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10122: 	if ($cached) {
                   10123: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10124: 	}
                   10125: 
1.888     albertel 10126: 	my %name_to_host = &all_names();
                   10127: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10128: 	    my $ip;
                   10129: 	    if (!exists($name_to_ip{$name})) {
                   10130: 		$ip = gethostbyname($name);
                   10131: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10132: 		    if (defined($old_name_to_ip{$name})) {
                   10133: 			$ip = $old_name_to_ip{$name};
                   10134: 			&logthis("Can't find $name defaulting to old $ip");
                   10135: 		    } else {
                   10136: 			&logthis("Name $name no IP found");
                   10137: 			next;
                   10138: 		    }
                   10139: 		} else {
                   10140: 		    $ip=inet_ntoa($ip);
1.847     albertel 10141: 		}
                   10142: 		$name_to_ip{$name} = $ip;
                   10143: 	    } else {
                   10144: 		$ip = $name_to_ip{$name};
1.653     albertel 10145: 	    }
1.888     albertel 10146: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10147: 		$lonid_to_ip{$id} = $ip;
                   10148: 	    }
                   10149: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10150: 	}
1.869     albertel 10151: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10152: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10153: 				      48*60*60);
1.869     albertel 10154: 
1.847     albertel 10155: 	return %iphost;
1.598     albertel 10156:     }
                   10157: 
1.992     raeburn  10158:     #
                   10159:     #  Given a DNS returns the loncapa host name for that DNS 
                   10160:     # 
                   10161:     sub host_from_dns {
                   10162:         my ($dns) = @_;
                   10163:         my @hosts;
                   10164:         my $ip;
                   10165: 
1.993     raeburn  10166:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10167:             $ip = $name_to_ip{$dns};
                   10168:         }
                   10169:         if (!$ip) {
                   10170:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10171:             if (length($ip) == 4) { 
                   10172: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10173:             }
                   10174:         }
                   10175:         if ($ip) {
                   10176: 	    @hosts = get_hosts_from_ip($ip);
                   10177: 	    return $hosts[0];
                   10178:         }
                   10179:         return undef;
1.986     foxr     10180:     }
1.992     raeburn  10181: 
1.1074    raeburn  10182:     sub get_internet_names {
                   10183:         my ($lonid) = @_;
                   10184:         return if ($lonid eq '');
                   10185:         my ($idnref,$cached)=
                   10186:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10187:         if ($cached) {
                   10188:             return $idnref;
                   10189:         }
                   10190:         my $ip = &get_host_ip($lonid);
                   10191:         my @hosts = &get_hosts_from_ip($ip);
                   10192:         my %iphost = &get_iphost();
                   10193:         my (@idns,%seen);
                   10194:         foreach my $id (@hosts) {
                   10195:             my $dom = &host_domain($id);
                   10196:             my $prim_id = &domain($dom,'primary');
                   10197:             my $prim_ip = &get_host_ip($prim_id);
                   10198:             next if ($seen{$prim_ip});
                   10199:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10200:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10201:                     my $intdom = &internet_dom($id);
                   10202:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10203:                         push(@idns,$intdom);
                   10204:                     }
                   10205:                 }
                   10206:             }
                   10207:             $seen{$prim_ip} = 1;
                   10208:         }
                   10209:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10210:     }
                   10211: 
1.986     foxr     10212: }
                   10213: 
1.1079    raeburn  10214: sub all_loncaparevs {
                   10215:     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);
                   10216: }
                   10217: 
1.862     albertel 10218: BEGIN {
                   10219: 
                   10220: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10221:     unless ($readit) {
                   10222: {
                   10223:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10224:     %perlvar = (%perlvar,%{$configvars});
                   10225: }
                   10226: 
                   10227: 
1.1       albertel 10228: # ------------------------------------------------------ Read spare server file
                   10229: {
1.448     albertel 10230:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10231: 
                   10232:     while (my $configline=<$config>) {
                   10233:        chomp($configline);
1.284     matthew  10234:        if ($configline) {
1.784     albertel 10235: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10236: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10237: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10238:        }
                   10239:     }
1.448     albertel 10240:     close($config);
1.1       albertel 10241: }
1.11      www      10242: # ------------------------------------------------------------ Read permissions
                   10243: {
1.448     albertel 10244:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10245: 
                   10246:     while (my $configline=<$config>) {
1.448     albertel 10247: 	chomp($configline);
                   10248: 	if ($configline) {
                   10249: 	    my ($role,$perm)=split(/ /,$configline);
                   10250: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10251: 	}
1.11      www      10252:     }
1.448     albertel 10253:     close($config);
1.11      www      10254: }
                   10255: 
                   10256: # -------------------------------------------- Read plain texts for permissions
                   10257: {
1.448     albertel 10258:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10259: 
                   10260:     while (my $configline=<$config>) {
1.448     albertel 10261: 	chomp($configline);
                   10262: 	if ($configline) {
1.742     raeburn  10263: 	    my ($short,@plain)=split(/:/,$configline);
                   10264:             %{$prp{$short}} = ();
                   10265: 	    if (@plain > 0) {
                   10266:                 $prp{$short}{'std'} = $plain[0];
                   10267:                 for (my $i=1; $i<@plain; $i++) {
                   10268:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10269:                 }
                   10270:             }
1.448     albertel 10271: 	}
1.135     www      10272:     }
1.448     albertel 10273:     close($config);
1.135     www      10274: }
                   10275: 
                   10276: # ---------------------------------------------------------- Read package table
                   10277: {
1.448     albertel 10278:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10279: 
                   10280:     while (my $configline=<$config>) {
1.483     albertel 10281: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10282: 	chomp($configline);
                   10283: 	my ($short,$plain)=split(/:/,$configline);
                   10284: 	my ($pack,$name)=split(/\&/,$short);
                   10285: 	if ($plain ne '') {
                   10286: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10287: 	    $packagetab{$short}=$plain; 
                   10288: 	}
1.11      www      10289:     }
1.448     albertel 10290:     close($config);
1.329     matthew  10291: }
                   10292: 
1.1073    raeburn  10293: # ---------------------------------------------------------- Read loncaparev table
                   10294: {
                   10295:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10296:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10297:             while (my $configline=<$config>) {
                   10298:                 chomp($configline);
                   10299:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10300:                 $loncaparevs{$hostid}=$loncaparev;
                   10301:             }
                   10302:             close($config);
                   10303:         }
                   10304:     }
                   10305: }
                   10306: 
1.1074    raeburn  10307: # ---------------------------------------------------------- Read serverhostID table
                   10308: {
                   10309:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10310:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10311:             while (my $configline=<$config>) {
                   10312:                 chomp($configline);
                   10313:                 my ($name,$id)=split(/:/,$configline);
                   10314:                 $serverhomeIDs{$name}=$id;
                   10315:             }
                   10316:             close($config);
                   10317:         }
                   10318:     }
                   10319: }
                   10320: 
1.1079    raeburn  10321: {
                   10322:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10323:     if (-e $file) {
                   10324:         my $parser = HTML::LCParser->new($file);
                   10325:         while (my $token = $parser->get_token()) {
                   10326:             if ($token->[0] eq 'S') {
                   10327:                 my $item = $token->[1];
                   10328:                 my $name = $token->[2]{'name'};
                   10329:                 my $value = $token->[2]{'value'};
                   10330:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10331:                     my $release = $parser->get_text();
                   10332:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10333:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10334:                 }
                   10335:             }
                   10336:         }
                   10337:     }
1.1073    raeburn  10338: }
                   10339: 
1.329     matthew  10340: # ------------- set up temporary directory
                   10341: {
                   10342:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10343: 
1.11      www      10344: }
                   10345: 
1.794     albertel 10346: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10347: 				'compress_threshold'=> 20_000,
                   10348:  			        });
1.185     www      10349: 
1.281     www      10350: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10351: $dumpcount=0;
1.958     www      10352: $locknum=0;
1.22      www      10353: 
1.163     harris41 10354: &logtouch();
1.672     albertel 10355: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10356: $readit=1;
1.564     albertel 10357:     {
                   10358: 	use integer;
                   10359: 	my $test=(2**32)+1;
1.568     albertel 10360: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10361: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10362:     }
1.195     www      10363: }
1.1       albertel 10364: }
1.179     www      10365: 
1.1       albertel 10366: 1;
1.191     harris41 10367: __END__
                   10368: 
1.243     albertel 10369: =pod
                   10370: 
1.191     harris41 10371: =head1 NAME
                   10372: 
1.243     albertel 10373: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10374: 
                   10375: =head1 SYNOPSIS
                   10376: 
1.243     albertel 10377: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10378: 
                   10379:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10380: 
1.243     albertel 10381: Common parameters:
                   10382: 
                   10383: =over 4
                   10384: 
                   10385: =item *
                   10386: 
                   10387: $uname : an internal username (if $cname expecting a course Id specifically)
                   10388: 
                   10389: =item *
                   10390: 
                   10391: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10392: 
                   10393: =item *
                   10394: 
                   10395: $symb : a resource instance identifier
                   10396: 
                   10397: =item *
                   10398: 
                   10399: $namespace : the name of a .db file that contains the data needed or
                   10400: being set.
                   10401: 
                   10402: =back
                   10403: 
1.394     bowersj2 10404: =head1 OVERVIEW
1.191     harris41 10405: 
1.394     bowersj2 10406: lonnet provides subroutines which interact with the
                   10407: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10408: about classes, users, and resources.
1.243     albertel 10409: 
                   10410: For many of these objects you can also use this to store data about
                   10411: them or modify them in various ways.
1.191     harris41 10412: 
1.394     bowersj2 10413: =head2 Symbs
1.191     harris41 10414: 
1.394     bowersj2 10415: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10416: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10417: map, the resource number of the resource in the map, and the URL of
                   10418: the resource itself. The latter is somewhat redundant, but might help
                   10419: if maps change.
                   10420: 
                   10421: An example is
                   10422: 
                   10423:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10424: 
                   10425: The respective map entry is
                   10426: 
                   10427:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10428:   title="Problem 2">
                   10429:  </resource>
                   10430: 
                   10431: Symbs are used by the random number generator, as well as to store and
                   10432: restore data specific to a certain instance of for example a problem.
                   10433: 
                   10434: =head2 Storing And Retrieving Data
                   10435: 
                   10436: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10437: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10438: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10439: is is the non-critical message twin of cstore. These functions are for
                   10440: handlers to store a perl hash to a user's permanent data space in an
                   10441: easy manner, and to retrieve it again on another call. It is expected
                   10442: that a handler would use this once at the beginning to retrieve data,
                   10443: and then again once at the end to send only the new data back.
                   10444: 
                   10445: The data is stored in the user's data directory on the user's
                   10446: homeserver under the ID of the course.
                   10447: 
                   10448: The hash that is returned by restore will have all of the previous
                   10449: value for all of the elements of the hash.
                   10450: 
                   10451: Example:
                   10452: 
                   10453:  #creating a hash
                   10454:  my %hash;
                   10455:  $hash{'foo'}='bar';
                   10456: 
                   10457:  #storing it
                   10458:  &Apache::lonnet::cstore(\%hash);
                   10459: 
                   10460:  #changing a value
                   10461:  $hash{'foo'}='notbar';
                   10462: 
                   10463:  #adding a new value
                   10464:  $hash{'bar'}='foo';
                   10465:  &Apache::lonnet::cstore(\%hash);
                   10466: 
                   10467:  #retrieving the hash
                   10468:  my %history=&Apache::lonnet::restore();
                   10469: 
                   10470:  #print the hash
                   10471:  foreach my $key (sort(keys(%history))) {
                   10472:    print("\%history{$key} = $history{$key}");
                   10473:  }
                   10474: 
                   10475: Will print out:
1.191     harris41 10476: 
1.394     bowersj2 10477:  %history{1:foo} = bar
                   10478:  %history{1:keys} = foo:timestamp
                   10479:  %history{1:timestamp} = 990455579
                   10480:  %history{2:bar} = foo
                   10481:  %history{2:foo} = notbar
                   10482:  %history{2:keys} = foo:bar:timestamp
                   10483:  %history{2:timestamp} = 990455580
                   10484:  %history{bar} = foo
                   10485:  %history{foo} = notbar
                   10486:  %history{timestamp} = 990455580
                   10487:  %history{version} = 2
                   10488: 
                   10489: Note that the special hash entries C<keys>, C<version> and
                   10490: C<timestamp> were added to the hash. C<version> will be equal to the
                   10491: total number of versions of the data that have been stored. The
                   10492: C<timestamp> attribute will be the UNIX time the hash was
                   10493: stored. C<keys> is available in every historical section to list which
                   10494: keys were added or changed at a specific historical revision of a
                   10495: hash.
                   10496: 
                   10497: B<Warning>: do not store the hash that restore returns directly. This
                   10498: will cause a mess since it will restore the historical keys as if the
                   10499: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10500: 
1.394     bowersj2 10501: Calling convention:
1.191     harris41 10502: 
1.394     bowersj2 10503:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10504:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10505: 
1.394     bowersj2 10506: For more detailed information, see lonnet specific documentation.
1.191     harris41 10507: 
1.394     bowersj2 10508: =head1 RETURN MESSAGES
1.191     harris41 10509: 
1.394     bowersj2 10510: =over 4
1.191     harris41 10511: 
1.394     bowersj2 10512: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10513: 
1.394     bowersj2 10514: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10515: when the connection is brought back up
1.191     harris41 10516: 
1.394     bowersj2 10517: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10518: for later delivery
1.191     harris41 10519: 
1.967     bisitz   10520: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10521: 
1.394     bowersj2 10522: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10523: that was requested
1.191     harris41 10524: 
1.243     albertel 10525: =back
1.191     harris41 10526: 
1.243     albertel 10527: =head1 PUBLIC SUBROUTINES
1.191     harris41 10528: 
1.243     albertel 10529: =head2 Session Environment Functions
1.191     harris41 10530: 
1.243     albertel 10531: =over 4
1.191     harris41 10532: 
1.394     bowersj2 10533: =item * 
                   10534: X<appenv()>
1.949     raeburn  10535: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10536: the user envirnoment file, and will be restored for each access this
1.620     albertel 10537: user makes during this session, also modifies the %env for the current
1.949     raeburn  10538: process. Optional rolesarrayref - if defined contains a reference to an array
                   10539: of roles which are exempt from the restriction on modifying user.role entries 
                   10540: in the user's environment.db and in %env.    
1.191     harris41 10541: 
                   10542: =item *
1.394     bowersj2 10543: X<delenv()>
1.987     raeburn  10544: B<delenv($delthis,$regexp)>: removes all items from the session
                   10545: environment file that begin with $delthis. If the 
                   10546: optional second arg - $regexp - is true, $delthis is treated as a 
                   10547: regular expression, otherwise \Q$delthis\E is used. 
                   10548: The values are also deleted from the current processes %env.
1.191     harris41 10549: 
1.795     albertel 10550: =item * get_env_multiple($name) 
                   10551: 
                   10552: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10553: values may be defined and end up as an array ref.
                   10554: 
                   10555: returns an array of values
                   10556: 
1.243     albertel 10557: =back
                   10558: 
                   10559: =head2 User Information
1.191     harris41 10560: 
1.243     albertel 10561: =over 4
1.191     harris41 10562: 
                   10563: =item *
1.394     bowersj2 10564: X<queryauthenticate()>
                   10565: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10566: authentication scheme
                   10567: 
                   10568: =item *
1.394     bowersj2 10569: X<authenticate()>
1.1073    raeburn  10570: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10571: authenticate user from domain's lib servers (first use the current
                   10572: one). C<$upass> should be the users password.
1.1073    raeburn  10573: $checkdefauth is optional (value is 1 if a check should be made to
                   10574:    authenticate user using default authentication method, and allow
                   10575:    account creation if username does not have account in the domain).
                   10576: $clientcancheckhost is optional (value is 1 if checking whether the
                   10577:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10578: 
                   10579: =item *
1.394     bowersj2 10580: X<homeserver()>
                   10581: B<homeserver($uname,$udom)>: find the server which has
                   10582: the user's directory and files (there must be only one), this caches
                   10583: the answer, and also caches if there is a borken connection.
1.191     harris41 10584: 
                   10585: =item *
1.394     bowersj2 10586: X<idget()>
                   10587: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10588: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10589: username, and only 1 username per ID in a specific domain) (returns
                   10590: hash: id=>name,id=>name)
1.191     harris41 10591: 
                   10592: =item *
1.394     bowersj2 10593: X<idrget()>
                   10594: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10595: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10596: 
                   10597: =item *
1.394     bowersj2 10598: X<idput()>
                   10599: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10600: 
                   10601: =item *
1.394     bowersj2 10602: X<rolesinit()>
                   10603: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10604: 
                   10605: =item *
1.551     albertel 10606: X<getsection()>
                   10607: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10608: course $cname, return section name/number or '' for "not in course"
                   10609: and '-1' for "no section"
                   10610: 
                   10611: =item *
1.394     bowersj2 10612: X<userenvironment()>
                   10613: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10614: passed in @what from the requested user's environment, returns a hash
                   10615: 
1.858     raeburn  10616: =item * 
                   10617: X<userlog_query()>
1.859     albertel 10618: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10619: activity.log file. %filters defines filters applied when parsing the
                   10620: log file. These can be start or end timestamps, or the type of action
                   10621: - log to look for Login or Logout events, check for Checkin or
                   10622: Checkout, role for role selection. The response is in the form
                   10623: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10624: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10625: 
1.243     albertel 10626: =back
                   10627: 
                   10628: =head2 User Roles
                   10629: 
                   10630: =over 4
                   10631: 
                   10632: =item *
                   10633: 
1.810     raeburn  10634: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10635:  F: full access
                   10636:  U,I,K: authentication modes (cxx only)
                   10637:  '': forbidden
                   10638:  1: user needs to choose course
                   10639:  2: browse allowed
1.766     albertel 10640:  A: passphrase authentication needed
1.243     albertel 10641: 
                   10642: =item *
                   10643: 
                   10644: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10645: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10646: and course level
                   10647: 
                   10648: =item *
                   10649: 
1.988     raeburn  10650: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10651: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10652: $type is Course (default) or Community.
1.988     raeburn  10653: If $forcedefault evaluates to true, text returned will be default 
                   10654: text for $type. Otherwise, if this is a course, the text returned 
                   10655: will be a custom name for the role (if defined in the course's 
                   10656: environment).  If no custom name is defined the default is returned.
                   10657:    
1.832     raeburn  10658: =item *
                   10659: 
1.935     raeburn  10660: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10661: All arguments are optional. Returns a hash of a roles, either for
                   10662: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10663: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10664: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10665: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10666: For each key, value is set to colon-separated start and end times for
                   10667: the role.  If no username and domain are specified, will default to
1.934     raeburn  10668: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10669: of role statuses (active, future or previous), roles 
                   10670: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10671: to restrict the list of roles reported. If no array ref is 
                   10672: provided for types, will default to return only active roles.
1.834     albertel 10673: 
1.243     albertel 10674: =back
                   10675: 
                   10676: =head2 User Modification
                   10677: 
                   10678: =over 4
                   10679: 
                   10680: =item *
                   10681: 
1.957     raeburn  10682: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10683: user for the level given by URL.  Optional start and end dates (leave empty
                   10684: string or zero for "no date")
1.191     harris41 10685: 
                   10686: =item *
                   10687: 
1.243     albertel 10688: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10689: change a users, password, possible return values are: ok,
                   10690: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10691: refused
1.191     harris41 10692: 
                   10693: =item *
                   10694: 
1.243     albertel 10695: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10696: 
                   10697: =item *
                   10698: 
1.1058    raeburn  10699: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10700:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10701: 
                   10702: will update user information (firstname,middlename,lastname,generation,
                   10703: permanentemail), and if forceid is true, student/employee ID also.
                   10704: A user's institutional affiliation(s) can also be updated.
                   10705: User information fields will not be overwritten with empty entries 
                   10706: unless the field is included in the $candelete array reference.
                   10707: This array is included when a single user is modified via "Manage Users",
                   10708: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10709: 
                   10710: =item *
                   10711: 
1.286     matthew  10712: modifystudent
                   10713: 
1.957     raeburn  10714: modify a student's enrollment and identification information.
1.286     matthew  10715: The course id is resolved based on the current users environment.  
                   10716: This means the envoking user must be a course coordinator or otherwise
                   10717: associated with a course.
                   10718: 
1.297     matthew  10719: This call is essentially a wrapper for lonnet::modifyuser and
                   10720: lonnet::modify_student_enrollment
1.286     matthew  10721: 
                   10722: Inputs: 
                   10723: 
                   10724: =over 4
                   10725: 
1.957     raeburn  10726: =item B<$udom> Student's loncapa domain
1.286     matthew  10727: 
1.957     raeburn  10728: =item B<$uname> Student's loncapa login name
1.286     matthew  10729: 
1.964     bisitz   10730: =item B<$uid> Student/Employee ID
1.286     matthew  10731: 
1.957     raeburn  10732: =item B<$umode> Student's authentication mode
1.286     matthew  10733: 
1.957     raeburn  10734: =item B<$upass> Student's password
1.286     matthew  10735: 
1.957     raeburn  10736: =item B<$first> Student's first name
1.286     matthew  10737: 
1.957     raeburn  10738: =item B<$middle> Student's middle name
1.286     matthew  10739: 
1.957     raeburn  10740: =item B<$last> Student's last name
1.286     matthew  10741: 
1.957     raeburn  10742: =item B<$gene> Student's generation
1.286     matthew  10743: 
1.957     raeburn  10744: =item B<$usec> Student's section in course
1.286     matthew  10745: 
                   10746: =item B<$end> Unix time of the roles expiration
                   10747: 
                   10748: =item B<$start> Unix time of the roles start date
                   10749: 
                   10750: =item B<$forceid> If defined, allow $uid to be changed
                   10751: 
                   10752: =item B<$desiredhome> server to use as home server for student
                   10753: 
1.957     raeburn  10754: =item B<$email> Student's permanent e-mail address
                   10755: 
                   10756: =item B<$type> Type of enrollment (auto or manual)
                   10757: 
1.963     raeburn  10758: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10759: 
                   10760: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10761: 
1.963     raeburn  10762: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10763: 
1.963     raeburn  10764: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10765: 
1.963     raeburn  10766: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10767: 
1.286     matthew  10768: =back
1.297     matthew  10769: 
                   10770: =item *
                   10771: 
                   10772: modify_student_enrollment
                   10773: 
                   10774: Change a students enrollment status in a class.  The environment variable
                   10775: 'role.request.course' must be defined for this function to proceed.
                   10776: 
                   10777: Inputs:
                   10778: 
                   10779: =over 4
                   10780: 
                   10781: =item $udom, students domain
                   10782: 
                   10783: =item $uname, students name
                   10784: 
                   10785: =item $uid, students user id
                   10786: 
                   10787: =item $first, students first name
                   10788: 
                   10789: =item $middle
                   10790: 
                   10791: =item $last
                   10792: 
                   10793: =item $gene
                   10794: 
                   10795: =item $usec
                   10796: 
                   10797: =item $end
                   10798: 
                   10799: =item $start
                   10800: 
1.957     raeburn  10801: =item $type
                   10802: 
                   10803: =item $locktype
                   10804: 
                   10805: =item $cid
                   10806: 
                   10807: =item $selfenroll
                   10808: 
                   10809: =item $context
                   10810: 
1.297     matthew  10811: =back
                   10812: 
1.191     harris41 10813: 
                   10814: =item *
                   10815: 
1.243     albertel 10816: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10817: custom role; give a custom role to a user for the level given by URL.  Specify
                   10818: name and domain of role author, and role name
1.191     harris41 10819: 
                   10820: =item *
                   10821: 
1.243     albertel 10822: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10823: 
                   10824: =item *
                   10825: 
1.243     albertel 10826: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10827: 
                   10828: =back
                   10829: 
                   10830: =head2 Course Infomation
                   10831: 
                   10832: =over 4
1.191     harris41 10833: 
                   10834: =item *
                   10835: 
1.631     albertel 10836: coursedescription($courseid) : returns a hash of information about the
                   10837: specified course id, including all environment settings for the
                   10838: course, the description of the course will be in the hash under the
                   10839: key 'description'
1.191     harris41 10840: 
                   10841: =item *
                   10842: 
1.624     albertel 10843: resdata($name,$domain,$type,@which) : request for current parameter
                   10844: setting for a specific $type, where $type is either 'course' or 'user',
                   10845: @what should be a list of parameters to ask about. This routine caches
                   10846: answers for 5 minutes.
1.243     albertel 10847: 
1.877     foxr     10848: =item *
                   10849: 
                   10850: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10851: data base, returning a hash that is keyed by the resource name and has
                   10852: values that are the resource value.  I believe that the timestamps and
                   10853: versions are also returned.
                   10854: 
                   10855: 
1.243     albertel 10856: =back
                   10857: 
                   10858: =head2 Course Modification
                   10859: 
                   10860: =over 4
1.191     harris41 10861: 
                   10862: =item *
                   10863: 
1.243     albertel 10864: writecoursepref($courseid,%prefs) : write preferences (environment
                   10865: database) for a course
1.191     harris41 10866: 
                   10867: =item *
                   10868: 
1.1011    raeburn  10869: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10870: 
                   10871: =item *
                   10872: 
1.1038    raeburn  10873: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10874: 
                   10875: =back
                   10876: 
                   10877: =head2 Resource Subroutines
                   10878: 
                   10879: =over 4
1.191     harris41 10880: 
                   10881: =item *
                   10882: 
1.243     albertel 10883: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10884: 
                   10885: =item *
                   10886: 
1.243     albertel 10887: repcopy($filename) : subscribes to the requested file, and attempts to
                   10888: replicate from the owning library server, Might return
1.607     raeburn  10889: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10890: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10891: resource. Expects the local filesystem pathname
                   10892: (/home/httpd/html/res/....)
                   10893: 
                   10894: =back
                   10895: 
                   10896: =head2 Resource Information
                   10897: 
                   10898: =over 4
1.191     harris41 10899: 
                   10900: =item *
                   10901: 
1.243     albertel 10902: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10903: a vairety of different possible values, $varname should be a request
                   10904: string, and the other parameters can be used to specify who and what
                   10905: one is asking about.
                   10906: 
                   10907: Possible values for $varname are environment.lastname (or other item
                   10908: from the envirnment hash), user.name (or someother aspect about the
                   10909: user), resource.0.maxtries (or some other part and parameter of a
                   10910: resource)
1.204     albertel 10911: 
                   10912: =item *
                   10913: 
1.243     albertel 10914: directcondval($number) : get current value of a condition; reads from a state
                   10915: string
1.204     albertel 10916: 
                   10917: =item *
                   10918: 
1.243     albertel 10919: condval($condidx) : value of condition index based on state
1.204     albertel 10920: 
                   10921: =item *
                   10922: 
1.243     albertel 10923: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10924: resource's metadata, $what should be either a specific key, or either
                   10925: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10926: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10927: 
                   10928: this function automatically caches all requests
1.191     harris41 10929: 
                   10930: =item *
                   10931: 
1.243     albertel 10932: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10933: network of library servers; returns file handle of where SQL and regex results
                   10934: will be stored for query
1.191     harris41 10935: 
                   10936: =item *
                   10937: 
1.243     albertel 10938: symbread($filename) : return symbolic list entry (filename argument optional);
                   10939: returns the data handle
1.191     harris41 10940: 
                   10941: =item *
                   10942: 
1.243     albertel 10943: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10944: a possible symb for the URL in $thisfn, and if is an encryypted
                   10945: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10946: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10947: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10948: 
1.191     harris41 10949: 
                   10950: =item *
                   10951: 
1.243     albertel 10952: symbclean($symb) : removes versions numbers from a symb, returns the
                   10953: cleaned symb
1.191     harris41 10954: 
                   10955: =item *
                   10956: 
1.243     albertel 10957: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10958: course map, user must be in a course for it to work.
1.191     harris41 10959: 
                   10960: =item *
                   10961: 
1.243     albertel 10962: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10963: 
                   10964: =item *
                   10965: 
1.243     albertel 10966: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10967: a random seed, all arguments are optional, if they aren't sent it uses the
                   10968: environment to derive them. Note: if symb isn't sent and it can't get one
                   10969: from &symbread it will use the current time as its return value
1.191     harris41 10970: 
                   10971: =item *
                   10972: 
1.243     albertel 10973: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10974: unfakeable, receipt
1.191     harris41 10975: 
                   10976: =item *
                   10977: 
1.620     albertel 10978: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10979: 
                   10980: =item *
                   10981: 
1.243     albertel 10982: countacc($url) : count the number of accesses to a given URL
1.191     harris41 10983: 
                   10984: =item *
                   10985: 
1.243     albertel 10986: 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 10987: 
                   10988: =item *
                   10989: 
1.243     albertel 10990: 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 10991: 
                   10992: =item *
                   10993: 
1.243     albertel 10994: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 10995: 
                   10996: =item *
                   10997: 
1.243     albertel 10998: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10999: forcing spreadsheet to reevaluate the resource scores next time.
                   11000: 
                   11001: =back
                   11002: 
                   11003: =head2 Storing/Retreiving Data
                   11004: 
                   11005: =over 4
1.191     harris41 11006: 
                   11007: =item *
                   11008: 
1.243     albertel 11009: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11010: for this url; hashref needs to be given and should be a \%hashname; the
                   11011: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11012: be derived from the env
1.191     harris41 11013: 
                   11014: =item *
                   11015: 
1.243     albertel 11016: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11017: uses critical subroutine
1.191     harris41 11018: 
                   11019: =item *
                   11020: 
1.243     albertel 11021: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11022: all args are optional
1.191     harris41 11023: 
                   11024: =item *
                   11025: 
1.717     albertel 11026: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11027: dumps the complete (or key matching regexp) namespace into a hash
                   11028: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11029: normally &store()ed into
                   11030: 
                   11031: $range should be either an integer '100' (give me the first 100
                   11032:                                            matching records)
                   11033:               or be  two integers sperated by a - with no spaces
                   11034:                  '30-50' (give me the 30th through the 50th matching
                   11035:                           records)
                   11036: 
                   11037: 
                   11038: =item *
                   11039: 
                   11040: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11041: replaces a &store() version of data with a replacement set of data
                   11042: for a particular resource in a namespace passed in the $storehash hash 
                   11043: reference
                   11044: 
                   11045: =item *
                   11046: 
1.243     albertel 11047: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11048: works very similar to store/cstore, but all data is stored in a
                   11049: temporary location and can be reset using tmpreset, $storehash should
                   11050: be a hash reference, returns nothing on success
1.191     harris41 11051: 
                   11052: =item *
                   11053: 
1.243     albertel 11054: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11055: similar to restore, but all data is stored in a temporary location and
                   11056: can be reset using tmpreset. Returns a hash of values on success,
                   11057: error string otherwise.
1.191     harris41 11058: 
                   11059: =item *
                   11060: 
1.243     albertel 11061: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11062: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11063: 
                   11064: =item *
                   11065: 
1.243     albertel 11066: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11067: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11068: 
                   11069: =item *
                   11070: 
1.243     albertel 11071: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11072: namesp ($udom and $uname are optional)
1.191     harris41 11073: 
                   11074: =item *
                   11075: 
1.702     albertel 11076: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11077: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11078: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11079: 
1.702     albertel 11080: $range should be either an integer '100' (give me the first 100
                   11081:                                            matching records)
                   11082:               or be  two integers sperated by a - with no spaces
                   11083:                  '30-50' (give me the 30th through the 50th matching
                   11084:                           records)
1.449     matthew  11085: =item *
                   11086: 
                   11087: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11088: $store can be a scalar, an array reference, or if the amount to be 
                   11089: incremented is > 1, a hash reference.
                   11090: 
                   11091: ($udom and $uname are optional)
1.191     harris41 11092: 
                   11093: =item *
                   11094: 
1.243     albertel 11095: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11096: ($udom and $uname are optional)
1.191     harris41 11097: 
                   11098: =item *
                   11099: 
1.243     albertel 11100: cput($namespace,$storehash,$udom,$uname) : critical put
                   11101: ($udom and $uname are optional)
1.191     harris41 11102: 
                   11103: =item *
                   11104: 
1.748     albertel 11105: newput($namespace,$storehash,$udom,$uname) :
                   11106: 
                   11107: Attempts to store the items in the $storehash, but only if they don't
                   11108: currently exist, if this succeeds you can be certain that you have 
                   11109: successfully created a new key value pair in the $namespace db.
                   11110: 
                   11111: 
                   11112: Args:
                   11113:  $namespace: name of database to store values to
                   11114:  $storehash: hashref to store to the db
                   11115:  $udom: (optional) domain of user containing the db
                   11116:  $uname: (optional) name of user caontaining the db
                   11117: 
                   11118: Returns:
                   11119:  'ok' -> succeeded in storing all keys of $storehash
                   11120:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11121:                         least <key> already existed in the db (other
                   11122:                         requested keys may also already exist)
1.967     bisitz   11123:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11124:  'con_lost' -> unable to contact request server
                   11125:  'refused' -> action was not allowed by remote machine
                   11126: 
                   11127: 
                   11128: =item *
                   11129: 
1.243     albertel 11130: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11131: reference filled in from namesp (encrypts the return communication)
                   11132: ($udom and $uname are optional)
1.191     harris41 11133: 
                   11134: =item *
                   11135: 
1.243     albertel 11136: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11137: critical subroutine
                   11138: 
1.806     raeburn  11139: =item *
                   11140: 
1.860     raeburn  11141: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11142: array reference filled in from namespace found in domain level on either
                   11143: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11144: 
                   11145: =item *
                   11146: 
1.860     raeburn  11147: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11148: domain level either on specified domain server ($uhome) or primary domain 
                   11149: server ($udom and $uhome are optional)
1.806     raeburn  11150: 
1.943     raeburn  11151: =item * 
                   11152: 
                   11153: get_domain_defaults($target_domain) : returns hash with defaults for
                   11154: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11155: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11156: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11157: Values are retrieved from cache (if current), or from domain's configuration.db
                   11158: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11159: or lonTabs/domain.tab. 
                   11160: 
                   11161: %domdefaults = &get_auth_defaults($target_domain);
                   11162: 
1.243     albertel 11163: =back
                   11164: 
                   11165: =head2 Network Status Functions
                   11166: 
                   11167: =over 4
1.191     harris41 11168: 
                   11169: =item *
                   11170: 
                   11171: dirlist($uri) : return directory list based on URI
                   11172: 
                   11173: =item *
                   11174: 
1.243     albertel 11175: spareserver() : find server with least workload from spare.tab
                   11176: 
1.986     foxr     11177: 
                   11178: =item *
                   11179: 
                   11180: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11181: if there is no corresponding loncapa host.
                   11182: 
1.243     albertel 11183: =back
                   11184: 
1.986     foxr     11185: 
1.243     albertel 11186: =head2 Apache Request
                   11187: 
                   11188: =over 4
1.191     harris41 11189: 
                   11190: =item *
                   11191: 
1.243     albertel 11192: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11193: localhost, posts hash
                   11194: 
                   11195: =back
                   11196: 
                   11197: =head2 Data to String to Data
                   11198: 
                   11199: =over 4
1.191     harris41 11200: 
                   11201: =item *
                   11202: 
1.243     albertel 11203: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11204: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11205: 
                   11206: =item *
                   11207: 
1.243     albertel 11208: hashref2str($hashref) : convert a hashref into a string complete with
                   11209: escaping and '=' and '&' separators, supports elements that are
                   11210: arrayrefs and hashrefs
1.191     harris41 11211: 
                   11212: =item *
                   11213: 
1.243     albertel 11214: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11215: with escaping and '&' separators, supports elements that are arrayrefs
                   11216: and hashrefs
1.191     harris41 11217: 
                   11218: =item *
                   11219: 
1.243     albertel 11220: str2hash($string) : convert string to hash using unescaping and
                   11221: splitting on '=' and '&', supports elements that are arrayrefs and
                   11222: hashrefs
1.191     harris41 11223: 
                   11224: =item *
                   11225: 
1.243     albertel 11226: str2array($string) : convert string to hash using unescaping and
                   11227: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11228: 
                   11229: =back
                   11230: 
                   11231: =head2 Logging Routines
                   11232: 
                   11233: =over 4
                   11234: 
                   11235: These routines allow one to make log messages in the lonnet.log and
                   11236: lonnet.perm logfiles.
1.191     harris41 11237: 
                   11238: =item *
                   11239: 
1.243     albertel 11240: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11241: 
                   11242: =item *
                   11243: 
1.243     albertel 11244: logthis() : append message to the normal lonnet.log file, it gets
                   11245: preiodically rolled over and deleted.
1.191     harris41 11246: 
                   11247: =item *
                   11248: 
1.243     albertel 11249: logperm() : append a permanent message to lonnet.perm.log, this log
                   11250: file never gets deleted by any automated portion of the system, only
                   11251: messages of critical importance should go in here.
                   11252: 
                   11253: =back
                   11254: 
                   11255: =head2 General File Helper Routines
                   11256: 
                   11257: =over 4
1.191     harris41 11258: 
                   11259: =item *
                   11260: 
1.481     raeburn  11261: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11262: (a) files in /uploaded
                   11263:   (i) If a local copy of the file exists - 
                   11264:       compares modification date of local copy with last-modified date for 
                   11265:       definitive version stored on home server for course. If local copy is 
                   11266:       stale, requests a new version from the home server and stores it. 
                   11267:       If the original has been removed from the home server, then local copy 
                   11268:       is unlinked.
                   11269:   (ii) If local copy does not exist -
                   11270:       requests the file from the home server and stores it. 
                   11271:   
                   11272:   If $caller is 'uploadrep':  
                   11273:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11274:     for request for files originally uploaded via DOCS. 
                   11275:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11276:   
                   11277:   Otherwise:
                   11278:      This indicates a call from the content generation phase of the request.
                   11279:      -  returns the entire contents of the file or -1.
                   11280:      
                   11281: (b) files in /res
                   11282:    - returns the entire contents of a file or -1; 
                   11283:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11284: 
1.712     albertel 11285: 
                   11286: =item *
                   11287: 
                   11288: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11289:                   reference
                   11290: 
                   11291: returns either a stat() list of data about the file or an empty list
                   11292: if the file doesn't exist or couldn't find out about it (connection
                   11293: problems or user unknown)
                   11294: 
1.191     harris41 11295: =item *
                   11296: 
1.243     albertel 11297: filelocation($dir,$file) : returns file system location of a file
                   11298: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11299: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11300: and a file of ../bob will become /a/bob)
1.191     harris41 11301: 
                   11302: =item *
                   11303: 
                   11304: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11305: filelocation except for hrefs
                   11306: 
                   11307: =item *
                   11308: 
                   11309: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11310: 
1.243     albertel 11311: =back
                   11312: 
1.608     albertel 11313: =head2 Usererfile file routines (/uploaded*)
                   11314: 
                   11315: =over 4
                   11316: 
                   11317: =item *
                   11318: 
                   11319: userfileupload(): main rotine for putting a file in a user or course's
                   11320:                   filespace, arguments are,
                   11321: 
1.620     albertel 11322:  formname - required - this is the name of the element in $env where the
1.608     albertel 11323:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11324:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11325:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 11326:  coursedoc - if true, store the file in the course of the active role
                   11327:              of the current user
                   11328:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11329:          if undefined, it will be placed in "unknown"
                   11330: 
                   11331:  (This routine calls clean_filename() to remove any dangerous
                   11332:  characters from the filename, and then calls finuserfileupload() to
                   11333:  complete the transaction)
                   11334: 
                   11335:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11336:  and /adm/notfound.html if unsuccessful
                   11337: 
                   11338: =item *
                   11339: 
                   11340: clean_filename(): routine for cleaing a filename up for storage in
                   11341:                  userfile space, argument is:
                   11342: 
                   11343:  filename - proposed filename
                   11344: 
                   11345: returns: the new clean filename
                   11346: 
                   11347: =item *
                   11348: 
                   11349: finishuserfileupload(): routine that creaes and sends the file to
                   11350: userspace, probably shouldn't be called directly
                   11351: 
                   11352:   docuname: username or courseid of destination for the file
                   11353:   docudom: domain of user/course of destination for the file
                   11354:   formname: same as for userfileupload()
                   11355:   fname: filename (inculding subdirectories) for the file
                   11356: 
                   11357:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11358:  and /adm/notfound.html if unsuccessful
                   11359: 
                   11360: =item *
                   11361: 
                   11362: renameuserfile(): renames an existing userfile to a new name
                   11363: 
                   11364:   Args:
                   11365:    docuname: username or courseid of destination for the file
                   11366:    docudom: domain of user/course of destination for the file
                   11367:    old: current file name (including any subdirs under userfiles)
                   11368:    new: desired file name (including any subdirs under userfiles)
                   11369: 
                   11370: =item *
                   11371: 
                   11372: mkdiruserfile(): creates a directory is a userfiles dir
                   11373: 
                   11374:   Args:
                   11375:    docuname: username or courseid of destination for the file
                   11376:    docudom: domain of user/course of destination for the file
                   11377:    dir: dir to create (including any subdirs under userfiles)
                   11378: 
                   11379: =item *
                   11380: 
                   11381: removeuserfile(): removes a file that exists in userfiles
                   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:    fname: filname to delete (including any subdirs under userfiles)
                   11387: 
                   11388: =item *
                   11389: 
                   11390: removeuploadedurl(): convience function for removeuserfile()
                   11391: 
                   11392:   Args:
                   11393:    url:  a full /uploaded/... url to delete
                   11394: 
1.747     albertel 11395: =item * 
                   11396: 
                   11397: get_portfile_permissions():
                   11398:   Args:
                   11399:     domain: domain of user or course contain the portfolio files
                   11400:     user: name of user or num of course contain the portfolio files
                   11401:   Returns:
                   11402:     hashref of a dump of the proper file_permissions.db
                   11403:    
                   11404: 
                   11405: =item * 
                   11406: 
                   11407: get_access_controls():
                   11408: 
                   11409: Args:
                   11410:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11411:   group: (optional) the group you want the files associated with
                   11412:   file: (optional) the file you want access info on
                   11413: 
                   11414: Returns:
1.749     raeburn  11415:     a hash (keys are file names) of hashes containing
                   11416:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11417:         values are XML containing access control settings (see below) 
1.747     albertel 11418: 
                   11419: Internal notes:
                   11420: 
1.749     raeburn  11421:  access controls are stored in file_permissions.db as key=value pairs.
                   11422:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11423:         where scope -> public,guest,course,group,domains or users.
                   11424:               end -> UNIX time for end of access (0 -> no end date)
                   11425:               start -> UNIX time for start of access
                   11426: 
                   11427:     value -> XML description of access control
                   11428:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11429:             <start></start>
                   11430:             <end></end>
                   11431: 
                   11432:             <password></password>  for scope type = guest
                   11433: 
                   11434:             <domain></domain>     for scope type = course or group
                   11435:             <number></number>
                   11436:             <roles id="">
                   11437:              <role></role>
                   11438:              <access></access>
                   11439:              <section></section>
                   11440:              <group></group>
                   11441:             </roles>
                   11442: 
                   11443:             <dom></dom>         for scope type = domains
                   11444: 
                   11445:             <users>             for scope type = users
                   11446:              <user>
                   11447:               <uname></uname>
                   11448:               <udom></udom>
                   11449:              </user>
                   11450:             </users>
                   11451:            </scope> 
                   11452:               
                   11453:  Access data is also aggregated for each file in an additional key=value pair:
                   11454:  key -> path to file/file_name\0accesscontrol 
                   11455:  value -> reference to hash
                   11456:           hash contains key = value pairs
                   11457:           where key = uniqueID:scope_end_start
                   11458:                 value = UNIX time record was last updated
                   11459: 
                   11460:           Used to improve speed of look-ups of access controls for each file.  
                   11461:  
                   11462:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11463: 
                   11464: modify_access_controls():
                   11465: 
                   11466: Modifies access controls for a portfolio file
                   11467: Args
                   11468: 1. file name
                   11469: 2. reference to hash of required changes,
                   11470: 3. domain
                   11471: 4. username
                   11472:   where domain,username are the domain of the portfolio owner 
                   11473:   (either a user or a course) 
                   11474: 
                   11475: Returns:
                   11476: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11477: 2. result of deletions ('ok' or 'error', with error message).
                   11478: 3. reference to hash of any new or updated access controls.
                   11479: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11480:    key = integer (inbound ID)
                   11481:    value = uniqueID  
1.747     albertel 11482: 
1.608     albertel 11483: =back
                   11484: 
1.243     albertel 11485: =head2 HTTP Helper Routines
                   11486: 
                   11487: =over 4
                   11488: 
1.191     harris41 11489: =item *
                   11490: 
                   11491: escape() : unpack non-word characters into CGI-compatible hex codes
                   11492: 
                   11493: =item *
                   11494: 
                   11495: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11496: 
1.243     albertel 11497: =back
                   11498: 
                   11499: =head1 PRIVATE SUBROUTINES
                   11500: 
                   11501: =head2 Underlying communication routines (Shouldn't call)
                   11502: 
                   11503: =over 4
                   11504: 
                   11505: =item *
                   11506: 
                   11507: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11508: 
                   11509: =item *
                   11510: 
                   11511: reply() : uses subreply to send a message to remote machine, logs all failures
                   11512: 
                   11513: =item *
                   11514: 
                   11515: critical() : passes a critical message to another server; if cannot
                   11516: get through then place message in connection buffer directory and
                   11517: returns con_delayed, if incapable of saving message, returns
                   11518: con_failed
                   11519: 
                   11520: =item *
                   11521: 
                   11522: reconlonc() : tries to reconnect lonc client processes.
                   11523: 
                   11524: =back
                   11525: 
                   11526: =head2 Resource Access Logging
                   11527: 
                   11528: =over 4
                   11529: 
                   11530: =item *
                   11531: 
                   11532: flushcourselogs() : flush (save) buffer logs and access logs
                   11533: 
                   11534: =item *
                   11535: 
                   11536: courselog($what) : save message for course in hash
                   11537: 
                   11538: =item *
                   11539: 
                   11540: courseacclog($what) : save message for course using &courselog().  Perform
                   11541: special processing for specific resource types (problems, exams, quizzes, etc).
                   11542: 
1.191     harris41 11543: =item *
                   11544: 
                   11545: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11546: as a PerlChildExitHandler
1.243     albertel 11547: 
                   11548: =back
                   11549: 
                   11550: =head2 Other
                   11551: 
                   11552: =over 4
                   11553: 
                   11554: =item *
                   11555: 
                   11556: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11557: 
                   11558: =back
                   11559: 
                   11560: =cut
1.877     foxr     11561: 

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