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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.5! raeburn     4: # $Id: lonnet.pm,v 1.1056.4.4 2010/08/17 01:33:18 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1056.4.5! raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.676     albertel   98: 
1.195     www        99: my $readit;
1.550     foxr      100: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  101: 
1.619     albertel  102: require Exporter;
                    103: 
                    104: our @ISA = qw (Exporter);
                    105: our @EXPORT = qw(%env);
                    106: 
1.449     matthew   107: 
1.1       albertel  108: # --------------------------------------------------------------------- Logging
1.729     www       109: {
                    110:     my $logid;
                    111:     sub instructor_log {
1.957     raeburn   112: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    113:         if (($cnum eq '') || ($cdom eq '')) {
                    114:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    115:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    116:         }
1.729     www       117: 	$logid++;
1.957     raeburn   118:         my $now = time();
                    119: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       120: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       121: 				    { $id => {
                    122: 					'exe_uname' => $env{'user.name'},
                    123: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   124: 					'exe_time'  => $now,
1.730     www       125: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    126: 					'delflag'   => $delflag,
                    127: 					'logentry'  => $storehash,
                    128: 					'uname'     => $uname,
                    129: 					'udom'      => $udom,
                    130: 				    }
1.957     raeburn   131: 				  },$cdom,$cnum);
1.729     www       132:     }
                    133: }
1.1       albertel  134: 
1.163     harris41  135: sub logtouch {
                    136:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  137:     unless (-e "$execdir/logs/lonnet.log") {	
                    138: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  139: 	close $fh;
                    140:     }
                    141:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    142:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    143: }
                    144: 
1.1       albertel  145: sub logthis {
                    146:     my $message=shift;
                    147:     my $execdir=$perlvar{'lonDaemons'};
                    148:     my $now=time;
                    149:     my $local=localtime($now);
1.448     albertel  150:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      151: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    152: 	print $fh $logstring;
1.448     albertel  153: 	close($fh);
                    154:     }
1.1       albertel  155:     return 1;
                    156: }
                    157: 
                    158: sub logperm {
                    159:     my $message=shift;
                    160:     my $execdir=$perlvar{'lonDaemons'};
                    161:     my $now=time;
                    162:     my $local=localtime($now);
1.448     albertel  163:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    164: 	print $fh "$now:$message:$local\n";
                    165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
1.850     albertel  170: sub create_connection {
1.853     albertel  171:     my ($hostname,$lonid) = @_;
1.851     albertel  172:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  173: 				     Type    => SOCK_STREAM,
                    174: 				     Timeout => 10);
                    175:     return 0 if (!$client);
1.890     albertel  176:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  177:     my $result = <$client>;
                    178:     chomp($result);
                    179:     return 1 if ($result eq 'done');
                    180:     return 0;
                    181: }
                    182: 
1.983     raeburn   183: sub get_server_timezone {
                    184:     my ($cnum,$cdom) = @_;
                    185:     my $home=&homeserver($cnum,$cdom);
                    186:     if ($home ne 'no_host') {
                    187:         my $cachetime = 24*3600;
                    188:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    189:         if (defined($cached)) {
                    190:             return $timezone;
                    191:         } else {
                    192:             my $timezone = &reply('servertimezone',$home);
                    193:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    194:         }
                    195:     }
                    196: }
1.850     albertel  197: 
1.993     raeburn   198: sub get_server_loncaparev {
1.1056.4.3  raeburn   199:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   200:     if (defined($lonhost)) {
                    201:         if (!defined(&hostname($lonhost))) {
                    202:             undef($lonhost);
                    203:         }
                    204:     }
                    205:     if (!defined($lonhost)) {
                    206:         if (defined(&domain($dom,'primary'))) {
                    207:             $lonhost=&domain($dom,'primary');
                    208:             if ($lonhost eq 'no_host') {
                    209:                 undef($lonhost);
                    210:             }
                    211:         }
                    212:     }
                    213:     if (defined($lonhost)) {
1.1056.4.3  raeburn   214:         my $cachetime = 12*3600;
                    215:         if (!$ignore_cache) {
                    216:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    217:             if (defined($cached)) {
                    218:                 return $loncaparev;
                    219:             }
                    220:         }
                    221:         my ($answer,$loncaparev);
                    222:         my @ids=&current_machine_ids();
                    223:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    224:             $answer = $perlvar{'lonVersion'};
                    225:             if ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
                    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;
                    233:                     $ua->timeout(20);
                    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;
                    241:                         if ($content =~ /<p>VERSION\:\s*([\d.\-]+)<\/p>/) {
                    242:                             $loncaparev = $1;
                    243:                         }
                    244:                     }
                    245:                 } else {
                    246:                     $loncaparev = $loncaparevs{$lonhost};
                    247:                 }
                    248:             } elsif ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
                    249:                 $loncaparev = $1;
                    250:             }
                    251:         }
                    252:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    253:     }
                    254: }
                    255: 
                    256: sub get_server_homeID {
                    257:     my ($hostname,$ignore_cache,$caller) = @_;
                    258:     unless ($ignore_cache) {
                    259:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993     raeburn   260:         if (defined($cached)) {
1.1056.4.3  raeburn   261:             return $serverhomeID;
                    262:         }
                    263:     }
                    264:     my $cachetime = 12*3600;
                    265:     my $serverhomeID;
                    266:     if ($caller eq 'loncron') {
                    267:         my @machine_ids = &machine_ids($hostname);
                    268:         foreach my $id (@machine_ids) {
                    269:             my $response = &reply('serverhomeID',$id);
                    270:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    271:                 $serverhomeID = $response;
                    272:                 last;
                    273:             }
1.993     raeburn   274:         }
1.1056.4.3  raeburn   275:         if ($serverhomeID eq '') {
                    276:             $serverhomeID = $machine_ids[-1];
                    277:         }
                    278:     } else {
                    279:         $serverhomeID = $serverhomeIDs{$hostname};
1.993     raeburn   280:     }
1.1056.4.3  raeburn   281:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993     raeburn   282: }
                    283: 
1.1       albertel  284: # -------------------------------------------------- Non-critical communication
                    285: sub subreply {
                    286:     my ($cmd,$server)=@_;
1.838     albertel  287:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      288:     #
                    289:     #  With loncnew process trimming, there's a timing hole between lonc server
                    290:     #  process exit and the master server picking up the listen on the AF_UNIX
                    291:     #  socket.  In that time interval, a lock file will exist:
                    292: 
                    293:     my $lockfile=$peerfile.".lock";
                    294:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    295: 	sleep(1);
                    296:     }
                    297:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      298:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      299:     #
1.550     foxr      300:     #   We'll give the connection a few tries before abandoning it.  If
                    301:     #   connection is not possible, we'll con_lost back to the client.
                    302:     #   
                    303:     my $client;
                    304:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    305: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    306: 				      Type    => SOCK_STREAM,
                    307: 				      Timeout => 10);
1.869     albertel  308: 	if ($client) {
1.550     foxr      309: 	    last;		# Connected!
1.850     albertel  310: 	} else {
1.853     albertel  311: 	    &create_connection(&hostname($server),$server);
1.550     foxr      312: 	}
1.850     albertel  313:         sleep(1);		# Try again later if failed connection.
1.550     foxr      314:     }
                    315:     my $answer;
                    316:     if ($client) {
1.704     albertel  317: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      318: 	$answer=<$client>;
                    319: 	if (!$answer) { $answer="con_lost"; }
                    320: 	chomp($answer);
                    321:     } else {
                    322: 	$answer = 'con_lost';	# Failed connection.
                    323:     }
1.1       albertel  324:     return $answer;
                    325: }
                    326: 
                    327: sub reply {
                    328:     my ($cmd,$server)=@_;
1.838     albertel  329:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  330:     my $answer=subreply($cmd,$server);
1.65      www       331:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  332:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       333:                 " $cmd to $server returned $answer</font>");
                    334:     }
1.1       albertel  335:     return $answer;
                    336: }
                    337: 
                    338: # ----------------------------------------------------------- Send USR1 to lonc
                    339: 
                    340: sub reconlonc {
1.891     albertel  341:     my ($lonid) = @_;
                    342:     my $hostname = &hostname($lonid);
                    343:     if ($lonid) {
                    344: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    345: 	if ($hostname && -e $peerfile) {
                    346: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    347: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    348: 					     Type    => SOCK_STREAM,
                    349: 					     Timeout => 10);
                    350: 	    if ($client) {
                    351: 		print $client ("reset_retries\n");
                    352: 		my $answer=<$client>;
                    353: 		#reset just this one.
                    354: 	    }
                    355: 	}
                    356: 	return;
                    357:     }
                    358: 
1.836     www       359:     &logthis("Trying to reconnect lonc");
1.1       albertel  360:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  361:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  362: 	my $loncpid=<$fh>;
                    363:         chomp($loncpid);
                    364:         if (kill 0 => $loncpid) {
                    365: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    366:             kill USR1 => $loncpid;
                    367:             sleep 1;
1.836     www       368:          } else {
1.12      www       369: 	    &logthis(
1.672     albertel  370:                "<font color=\"blue\">WARNING:".
1.12      www       371:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  372:         }
                    373:     } else {
1.836     www       374: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  375:     }
                    376: }
                    377: 
                    378: # ------------------------------------------------------ Critical communication
1.12      www       379: 
1.1       albertel  380: sub critical {
                    381:     my ($cmd,$server)=@_;
1.838     albertel  382:     unless (&hostname($server)) {
1.672     albertel  383:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       384:                " Critical message to unknown server ($server)</font>");
                    385:         return 'no_such_host';
                    386:     }
1.1       albertel  387:     my $answer=reply($cmd,$server);
                    388:     if ($answer eq 'con_lost') {
                    389: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  390: 	my $answer=reply($cmd,$server);
1.1       albertel  391:         if ($answer eq 'con_lost') {
                    392:             my $now=time;
                    393:             my $middlename=$cmd;
1.5       www       394:             $middlename=substr($middlename,0,16);
1.1       albertel  395:             $middlename=~s/\W//g;
                    396:             my $dfilename=
1.305     www       397:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    398:             $dumpcount++;
1.1       albertel  399:             {
1.448     albertel  400: 		my $dfh;
                    401: 		if (open($dfh,">$dfilename")) {
                    402: 		    print $dfh "$cmd\n"; 
                    403: 		    close($dfh);
                    404: 		}
1.1       albertel  405:             }
                    406:             sleep 2;
                    407:             my $wcmd='';
                    408:             {
1.448     albertel  409: 		my $dfh;
                    410: 		if (open($dfh,"<$dfilename")) {
                    411: 		    $wcmd=<$dfh>; 
                    412: 		    close($dfh);
                    413: 		}
1.1       albertel  414:             }
                    415:             chomp($wcmd);
1.7       www       416:             if ($wcmd eq $cmd) {
1.672     albertel  417: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       418:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  419:                 &logperm("D:$server:$cmd");
                    420: 	        return 'con_delayed';
                    421:             } else {
1.672     albertel  422:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       423:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  424:                 &logperm("F:$server:$cmd");
                    425:                 return 'con_failed';
                    426:             }
                    427:         }
                    428:     }
                    429:     return $answer;
1.405     albertel  430: }
                    431: 
1.755     albertel  432: # ------------------------------------------- check if return value is an error
                    433: 
                    434: sub error {
                    435:     my ($result) = @_;
1.756     albertel  436:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  437: 	if ($2 == 2) { return undef; }
                    438: 	return $1;
                    439:     }
                    440:     return undef;
                    441: }
                    442: 
1.783     albertel  443: sub convert_and_load_session_env {
                    444:     my ($lonidsdir,$handle)=@_;
                    445:     my @profile;
                    446:     {
1.917     albertel  447: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    448: 	if (!$opened) {
1.915     albertel  449: 	    return 0;
                    450: 	}
1.783     albertel  451: 	flock($idf,LOCK_SH);
                    452: 	@profile=<$idf>;
                    453: 	close($idf);
                    454:     }
                    455:     my %temp_env;
                    456:     foreach my $line (@profile) {
1.786     albertel  457: 	if ($line !~ m/=/) {
                    458: 	    return 0;
                    459: 	}
1.783     albertel  460: 	chomp($line);
                    461: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    462: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    463:     }
                    464:     unlink("$lonidsdir/$handle.id");
                    465:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    466: 	    0640)) {
                    467: 	%disk_env = %temp_env;
                    468: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    469: 	untie(%disk_env);
                    470:     }
1.786     albertel  471:     return 1;
1.783     albertel  472: }
                    473: 
1.374     www       474: # ------------------------------------------- Transfer profile into environment
1.780     albertel  475: my $env_loaded;
                    476: sub transfer_profile_to_env {
1.788     albertel  477:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    478:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       479: 
1.720     albertel  480:     if (!defined($lonidsdir)) {
                    481: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    482:     }
                    483:     if (!defined($handle)) {
                    484:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    485:     }
                    486: 
1.786     albertel  487:     my $convert;
                    488:     {
1.917     albertel  489:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    490: 	if (!$opened) {
1.915     albertel  491: 	    return;
                    492: 	}
1.786     albertel  493: 	flock($idf,LOCK_SH);
                    494: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    495: 		&GDBM_READER(),0640)) {
                    496: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    497: 	    untie(%disk_env);
                    498: 	} else {
                    499: 	    $convert = 1;
                    500: 	}
                    501:     }
                    502:     if ($convert) {
                    503: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    504: 	    &logthis("Failed to load session, or convert session.");
                    505: 	}
1.374     www       506:     }
1.783     albertel  507: 
1.786     albertel  508:     my %remove;
1.783     albertel  509:     while ( my $envname = each(%env) ) {
1.433     matthew   510:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    511:             if ($time < time-300) {
1.783     albertel  512:                 $remove{$key}++;
1.433     matthew   513:             }
                    514:         }
                    515:     }
1.783     albertel  516: 
1.619     albertel  517:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  518:     $env_loaded=1;
1.783     albertel  519:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   520:         &delenv($expired_key);
1.374     www       521:     }
1.1       albertel  522: }
                    523: 
1.916     albertel  524: # ---------------------------------------------------- Check for valid session 
                    525: sub check_for_valid_session {
                    526:     my ($r) = @_;
                    527:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    528:     my $lonid=$cookies{'lonID'};
                    529:     return undef if (!$lonid);
                    530: 
                    531:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    532:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    533:     return undef if (!-e "$lonidsdir/$handle.id");
                    534: 
1.917     albertel  535:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    536:     return undef if (!$opened);
1.916     albertel  537: 
                    538:     flock($idf,LOCK_SH);
                    539:     my %disk_env;
                    540:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    541: 	    &GDBM_READER(),0640)) {
                    542: 	return undef;	
                    543:     }
                    544: 
                    545:     if (!defined($disk_env{'user.name'})
                    546: 	|| !defined($disk_env{'user.domain'})) {
                    547: 	return undef;
                    548:     }
                    549:     return $handle;
                    550: }
                    551: 
1.830     albertel  552: sub timed_flock {
                    553:     my ($file,$lock_type) = @_;
                    554:     my $failed=0;
                    555:     eval {
                    556: 	local $SIG{__DIE__}='DEFAULT';
                    557: 	local $SIG{ALRM}=sub {
                    558: 	    $failed=1;
                    559: 	    die("failed lock");
                    560: 	};
                    561: 	alarm(13);
                    562: 	flock($file,$lock_type);
                    563: 	alarm(0);
                    564:     };
                    565:     if ($failed) {
                    566: 	return undef;
                    567:     } else {
                    568: 	return 1;
                    569:     }
                    570: }
                    571: 
1.5       www       572: # ---------------------------------------------------------- Append Environment
                    573: 
                    574: sub appenv {
1.949     raeburn   575:     my ($newenv,$roles) = @_;
                    576:     if (ref($newenv) eq 'HASH') {
                    577:         foreach my $key (keys(%{$newenv})) {
                    578:             my $refused = 0;
                    579: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    580:                 $refused = 1;
                    581:                 if (ref($roles) eq 'ARRAY') {
                    582:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    583:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    584:                         $refused = 0;
                    585:                     }
                    586:                 }
                    587:             }
                    588:             if ($refused) {
                    589:                 &logthis("<font color=\"blue\">WARNING: ".
                    590:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    591:                          .'</font>');
                    592: 	        delete($newenv->{$key});
                    593:             } else {
                    594:                 $env{$key}=$newenv->{$key};
                    595:             }
                    596:         }
                    597:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    598:         if ($opened
                    599: 	    && &timed_flock($env_file,LOCK_EX)
                    600: 	    &&
                    601: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    602: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    603: 	    while (my ($key,$value) = each(%{$newenv})) {
                    604: 	        $disk_env{$key} = $value;
                    605: 	    }
                    606: 	    untie(%disk_env);
1.35      www       607:         }
1.191     harris41  608:     }
1.56      www       609:     return 'ok';
                    610: }
                    611: # ----------------------------------------------------- Delete from Environment
                    612: 
                    613: sub delenv {
1.987     raeburn   614:     my ($delthis,$regexp) = @_;
1.56      www       615:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  616:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       617:                 "Attempt to delete from environment ".$delthis);
                    618:         return 'error';
                    619:     }
1.917     albertel  620:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    621:     if ($opened
1.915     albertel  622: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  623: 	&&
                    624: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    625: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  626: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   627: 	    if ($regexp) {
                    628:                 if ($key=~/^$delthis/) {
                    629:                     delete($env{$key});
                    630:                     delete($disk_env{$key});
                    631:                 } 
                    632:             } else {
                    633:                 if ($key=~/^\Q$delthis\E/) {
                    634: 		    delete($env{$key});
                    635: 		    delete($disk_env{$key});
                    636: 	        }
                    637:             }
1.448     albertel  638: 	}
1.783     albertel  639: 	untie(%disk_env);
1.5       www       640:     }
                    641:     return 'ok';
1.369     albertel  642: }
                    643: 
1.790     albertel  644: sub get_env_multiple {
                    645:     my ($name) = @_;
                    646:     my @values;
                    647:     if (defined($env{$name})) {
                    648:         # exists is it an array
                    649:         if (ref($env{$name})) {
                    650:             @values=@{ $env{$name} };
                    651:         } else {
                    652:             $values[0]=$env{$name};
                    653:         }
                    654:     }
                    655:     return(@values);
                    656: }
                    657: 
1.958     www       658: # ------------------------------------------------------------------- Locking
                    659: 
                    660: sub set_lock {
                    661:     my ($text)=@_;
                    662:     $locknum++;
                    663:     my $id=$$.'-'.$locknum;
                    664:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    665:              'session.lock.'.$id => $text});
                    666:     return $id;
                    667: }
                    668: 
                    669: sub get_locks {
                    670:     my $num=0;
                    671:     my %texts=();
                    672:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    673:        if ($lock=~/\w/) {
                    674:           $num++;
                    675:           $texts{$lock}=$env{'session.lock.'.$lock};
                    676:        }
                    677:    }
                    678:    return ($num,%texts);
                    679: }
                    680: 
                    681: sub remove_lock {
                    682:     my ($id)=@_;
                    683:     my $newlocks='';
                    684:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    685:        if (($lock=~/\w/) && ($lock ne $id)) {
                    686:           $newlocks.=','.$lock;
                    687:        }
                    688:     }
                    689:     &appenv({'session.locks' => $newlocks});
                    690:     &delenv('session.lock.'.$id);
                    691: }
                    692: 
                    693: sub remove_all_locks {
                    694:     my $activelocks=$env{'session.locks'};
                    695:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    696:        if ($lock=~/\w/) {
                    697:           &remove_lock($lock);
                    698:        }
                    699:     }
                    700: }
                    701: 
                    702: 
1.369     albertel  703: # ------------------------------------------ Find out current server userload
                    704: sub userload {
                    705:     my $numusers=0;
                    706:     {
                    707: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    708: 	my $filename;
                    709: 	my $curtime=time;
                    710: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  711: 	    next if ($filename eq '.' || $filename eq '..');
                    712: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  713: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  714: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  715: 	}
                    716: 	closedir(LONIDS);
                    717:     }
                    718:     my $userloadpercent=0;
                    719:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    720:     if ($maxuserload) {
1.371     albertel  721: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  722:     }
1.372     albertel  723:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  724:     return $userloadpercent;
1.283     www       725: }
                    726: 
                    727: # ------------------------------------------ Fight off request when overloaded
                    728: 
                    729: sub overloaderror {
                    730:     my ($r,$checkserver)=@_;
                    731:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    732:     my $loadavg;
                    733:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  734:        open(my $loadfile,'/proc/loadavg');
1.283     www       735:        $loadavg=<$loadfile>;
                    736:        $loadavg =~ s/\s.*//g;
1.285     matthew   737:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  738:        close($loadfile);
1.283     www       739:     } else {
                    740:        $loadavg=&reply('load',$checkserver);
                    741:     }
1.285     matthew   742:     my $overload=$loadavg-100;
1.283     www       743:     if ($overload>0) {
1.285     matthew   744: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       745:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       746:         return 413;
1.283     www       747:     }    
                    748:     return '';
1.5       www       749: }
1.1       albertel  750: 
                    751: # ------------------------------ Find server with least workload from spare.tab
1.11      www       752: 
1.1       albertel  753: sub spareserver {
1.670     albertel  754:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  755:     my $spare_server;
1.370     albertel  756:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  757:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    758:                                                      :  $userloadpercent;
                    759:     
                    760:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    761: 	($spare_server, $lowest_load) =
                    762: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    763:     }
                    764: 
                    765:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    766: 
                    767:     if (!$found_server) {
                    768: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    769: 	    ($spare_server, $lowest_load) =
                    770: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    771: 	}
                    772:     }
                    773: 
                    774:     if (!$want_server_name) {
1.968     raeburn   775:         my $protocol = 'http';
                    776:         if ($protocol{$spare_server} eq 'https') {
                    777:             $protocol = $protocol{$spare_server};
                    778:         }
1.1001    raeburn   779:         if (defined($spare_server)) {
                    780:             my $hostname = &hostname($spare_server);
                    781:             if (defined($hostname)) {  
                    782: 	        $spare_server = $protocol.'://'.$hostname;
                    783:             }
                    784:         }
1.784     albertel  785:     }
                    786:     return $spare_server;
                    787: }
                    788: 
                    789: sub compare_server_load {
                    790:     my ($try_server, $spare_server, $lowest_load) = @_;
                    791: 
                    792:     my $loadans     = &reply('load',    $try_server);
                    793:     my $userloadans = &reply('userload',$try_server);
                    794: 
                    795:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3  raeburn   796:         return; #didn't get a number from the server
1.784     albertel  797:     }
                    798: 
                    799:     my $load;
                    800:     if ($loadans =~ /\d/) {
                    801: 	if ($userloadans =~ /\d/) {
                    802: 	    #both are numbers, pick the bigger one
                    803: 	    $load = ($loadans > $userloadans) ? $loadans 
                    804: 		                              : $userloadans;
1.411     albertel  805: 	} else {
1.784     albertel  806: 	    $load = $loadans;
1.411     albertel  807: 	}
1.784     albertel  808:     } else {
                    809: 	$load = $userloadans;
                    810:     }
                    811: 
                    812:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    813: 	$spare_server = $try_server;
                    814: 	$lowest_load  = $load;
1.370     albertel  815:     }
1.784     albertel  816:     return ($spare_server,$lowest_load);
1.202     matthew   817: }
1.914     albertel  818: 
                    819: # --------------------------- ask offload servers if user already has a session
                    820: sub find_existing_session {
                    821:     my ($udom,$uname) = @_;
                    822:     foreach my $try_server (@{ $spareid{'primary'} },
                    823: 			    @{ $spareid{'default'} }) {
                    824: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    825:     }
                    826:     return;
                    827: }
                    828: 
                    829: # -------------------------------- ask if server already has a session for user
                    830: sub has_user_session {
                    831:     my ($lonid,$udom,$uname) = @_;
                    832:     my $result = &reply(join(':','userhassession',
                    833: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    834:     return 1 if ($result eq 'ok');
                    835: 
                    836:     return 0;
                    837: }
                    838: 
1.1056.4.3  raeburn   839: # --------- determine least loaded server in a user's domain which allows login
                    840: 
                    841: sub choose_server {
                    842:     my ($udom) = @_;
                    843:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
                    844:     my %servers = &get_servers($udom);
                    845:     my $lowest_load = 30000;
                    846:     my ($login_host,$hostname);
                    847:     foreach my $lonhost (keys(%servers)) {
                    848:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    849:         if ($loginvia eq '') {
                    850:             ($login_host, $lowest_load) =
                    851:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    852:         }
                    853:     }
                    854:     if ($login_host ne '') {
                    855:         $hostname = $servers{$login_host};
                    856:     }
                    857:     return ($login_host,$hostname);
                    858: }
                    859: 
1.202     matthew   860: # --------------------------------------------- Try to change a user's password
                    861: 
                    862: sub changepass {
1.799     raeburn   863:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   864:     $currentpass = &escape($currentpass);
                    865:     $newpass     = &escape($newpass);
1.1030    raeburn   866:     my $lonhost = $perlvar{'lonHostID'};
                    867:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   868: 		       $server);
                    869:     if (! $answer) {
                    870: 	&logthis("No reply on password change request to $server ".
                    871: 		 "by $uname in domain $udom.");
                    872:     } elsif ($answer =~ "^ok") {
                    873:         &logthis("$uname in $udom successfully changed their password ".
                    874: 		 "on $server.");
                    875:     } elsif ($answer =~ "^pwchange_failure") {
                    876: 	&logthis("$uname in $udom was unable to change their password ".
                    877: 		 "on $server.  The action was blocked by either lcpasswd ".
                    878: 		 "or pwchange");
                    879:     } elsif ($answer =~ "^non_authorized") {
                    880:         &logthis("$uname in $udom did not get their password correct when ".
                    881: 		 "attempting to change it on $server.");
                    882:     } elsif ($answer =~ "^auth_mode_error") {
                    883:         &logthis("$uname in $udom attempted to change their password despite ".
                    884: 		 "not being locally or internally authenticated on $server.");
                    885:     } elsif ($answer =~ "^unknown_user") {
                    886:         &logthis("$uname in $udom attempted to change their password ".
                    887: 		 "on $server but were unable to because $server is not ".
                    888: 		 "their home server.");
                    889:     } elsif ($answer =~ "^refused") {
                    890: 	&logthis("$server refused to change $uname in $udom password because ".
                    891: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   892:     } elsif ($answer =~ "invalid_client") {
                    893:         &logthis("$server refused to change $uname in $udom password because ".
                    894:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   895:     }
                    896:     return $answer;
1.1       albertel  897: }
                    898: 
1.169     harris41  899: # ----------------------- Try to determine user's current authentication scheme
                    900: 
                    901: sub queryauthenticate {
                    902:     my ($uname,$udom)=@_;
1.456     albertel  903:     my $uhome=&homeserver($uname,$udom);
                    904:     if (!$uhome) {
                    905: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    906: 	return 'no_host';
                    907:     }
                    908:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    909:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    910: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  911:     }
1.456     albertel  912:     return $answer;
1.169     harris41  913: }
                    914: 
1.1       albertel  915: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       916: 
1.1       albertel  917: sub authenticate {
1.1056.4.3  raeburn   918:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  919:     $upass=&escape($upass);
                    920:     $uname= &LONCAPA::clean_username($uname);
1.836     www       921:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   922:     my $newhome;
1.836     www       923:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    924: # Maybe the machine was offline and only re-appeared again recently?
                    925:         &reconlonc();
                    926: # One more
1.952     raeburn   927: 	$uhome=&homeserver($uname,$udom,1);
                    928:         if (($uhome eq 'no_host') && $checkdefauth) {
                    929:             if (defined(&domain($udom,'primary'))) {
                    930:                 $newhome=&domain($udom,'primary');
                    931:             }
                    932:             if ($newhome ne '') {
                    933:                 $uhome = $newhome;
                    934:             }
                    935:         }
1.836     www       936: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    937: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   938: 	    return 'no_host';
                    939:         }
1.1       albertel  940:     }
1.1056.4.3  raeburn   941:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  942:     if ($answer eq 'authorized') {
1.952     raeburn   943:         if ($newhome) {
                    944:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    945:             return 'no_account_on_host'; 
                    946:         } else {
                    947:             &logthis("User $uname at $udom authorized by $uhome");
                    948:             return $uhome;
                    949:         }
1.471     albertel  950:     }
                    951:     if ($answer eq 'non_authorized') {
                    952: 	&logthis("User $uname at $udom rejected by $uhome");
                    953: 	return 'no_host'; 
1.9       www       954:     }
1.471     albertel  955:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  956:     return 'no_host';
                    957: }
                    958: 
1.1056.4.3  raeburn   959: sub can_host_session {
                    960:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
                    961:     my $canhost = 1;
                    962:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
                    963:     if (ref($remotesessions) eq 'HASH') {
                    964:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
                    965:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
                    966:                 $canhost = 0;
                    967:             } else {
                    968:                 $canhost = 1;
                    969:             }
                    970:         }
                    971:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
                    972:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
                    973:                 $canhost = 1;
                    974:             } else {
                    975:                 $canhost = 0;
                    976:             }
                    977:         }
                    978:         if ($canhost) {
                    979:             if ($remotesessions->{'version'} ne '') {
                    980:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                    981:                 if ($reqmajor ne '' && $reqminor ne '') {
                    982:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                    983:                         my $major = $1;
                    984:                         my $minor = $2;
                    985:                         if (($major < $reqmajor ) ||
                    986:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                    987:                             $canhost = 0;
                    988:                         }
                    989:                     } else {
                    990:                         $canhost = 0;
                    991:                     }
                    992:                 }
                    993:             }
                    994:         }
                    995:     }
                    996:     if ($canhost) {
                    997:         if (ref($hostedsessions) eq 'HASH') {
                    998:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                    999:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                   1000:                     $canhost = 0;
                   1001:                 } else {
                   1002:                     $canhost = 1;
                   1003:                 }
                   1004:             }
                   1005:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                   1006:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                   1007:                     $canhost = 1;
                   1008:                 } else {
                   1009:                     $canhost = 0;
                   1010:                 }
                   1011:             }
                   1012:         }
                   1013:     }
                   1014:     return $canhost;
                   1015: }
                   1016: 
1.1       albertel 1017: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1018: 
1.599     albertel 1019: my %homecache;
1.1       albertel 1020: sub homeserver {
1.230     stredwic 1021:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1022:     my $index="$uname:$udom";
1.426     albertel 1023: 
1.599     albertel 1024:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1025: 
                   1026:     my %servers = &get_servers($udom,'library');
                   1027:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1028:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1029: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1030: 
                   1031: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1032: 	if ($answer eq 'found') {
                   1033: 	    delete($badServerCache{$tryserver}); 
                   1034: 	    return $homecache{$index}=$tryserver;
                   1035: 	} elsif ($answer eq 'no_host') {
                   1036: 	    $badServerCache{$tryserver}=1;
                   1037: 	}
1.1       albertel 1038:     }    
                   1039:     return 'no_host';
1.70      www      1040: }
                   1041: 
                   1042: # ------------------------------------- Find the usernames behind a list of IDs
                   1043: 
                   1044: sub idget {
                   1045:     my ($udom,@ids)=@_;
                   1046:     my %returnhash=();
                   1047:     
1.841     albertel 1048:     my %servers = &get_servers($udom,'library');
                   1049:     foreach my $tryserver (keys(%servers)) {
                   1050: 	my $idlist=join('&',@ids);
                   1051: 	$idlist=~tr/A-Z/a-z/; 
                   1052: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1053: 	my @answer=();
                   1054: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1055: 	    @answer=split(/\&/,$reply);
                   1056: 	}                    ;
                   1057: 	my $i;
                   1058: 	for ($i=0;$i<=$#ids;$i++) {
                   1059: 	    if ($answer[$i]) {
                   1060: 		$returnhash{$ids[$i]}=$answer[$i];
                   1061: 	    } 
                   1062: 	}
                   1063:     } 
1.70      www      1064:     return %returnhash;
                   1065: }
                   1066: 
                   1067: # ------------------------------------- Find the IDs behind a list of usernames
                   1068: 
                   1069: sub idrget {
                   1070:     my ($udom,@unames)=@_;
                   1071:     my %returnhash=();
1.800     albertel 1072:     foreach my $uname (@unames) {
                   1073:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1074:     }
1.70      www      1075:     return %returnhash;
                   1076: }
                   1077: 
                   1078: # ------------------------------- Store away a list of names and associated IDs
                   1079: 
                   1080: sub idput {
                   1081:     my ($udom,%ids)=@_;
                   1082:     my %servers=();
1.800     albertel 1083:     foreach my $uname (keys(%ids)) {
                   1084: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1085:         my $uhom=&homeserver($uname,$udom);
1.70      www      1086:         if ($uhom ne 'no_host') {
1.800     albertel 1087:             my $id=&escape($ids{$uname});
1.70      www      1088:             $id=~tr/A-Z/a-z/;
1.800     albertel 1089:             my $esc_unam=&escape($uname);
1.70      www      1090: 	    if ($servers{$uhom}) {
1.800     albertel 1091: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1092:             } else {
1.800     albertel 1093:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1094:             }
                   1095:         }
1.191     harris41 1096:     }
1.800     albertel 1097:     foreach my $server (keys(%servers)) {
                   1098:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1099:     }
1.344     www      1100: }
                   1101: 
1.1023    raeburn  1102: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1103: sub dump_dom {
1.1023    raeburn  1104:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1105:     if (!$udom) {
                   1106:         $udom=$env{'user.domain'};
                   1107:     }
                   1108:     my %returnhash;
1.1023    raeburn  1109:     if ($udom) {
                   1110:         my $uname = &get_domainconfiguser($udom);
                   1111:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1112:     }
                   1113:     return %returnhash;
                   1114: }
                   1115: 
1.1023    raeburn  1116: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1117: 
                   1118: sub get_dom {
1.860     raeburn  1119:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1120:     my $items='';
                   1121:     foreach my $item (@$storearr) {
                   1122:         $items.=&escape($item).'&';
                   1123:     }
                   1124:     $items=~s/\&$//;
1.860     raeburn  1125:     if (!$udom) {
                   1126:         $udom=$env{'user.domain'};
                   1127:         if (defined(&domain($udom,'primary'))) {
                   1128:             $uhome=&domain($udom,'primary');
                   1129:         } else {
1.874     albertel 1130:             undef($uhome);
1.860     raeburn  1131:         }
                   1132:     } else {
                   1133:         if (!$uhome) {
                   1134:             if (defined(&domain($udom,'primary'))) {
                   1135:                 $uhome=&domain($udom,'primary');
                   1136:             }
                   1137:         }
                   1138:     }
                   1139:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1140:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1141:         my %returnhash;
1.875     albertel 1142:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1143:             return %returnhash;
                   1144:         }
1.806     raeburn  1145:         my @pairs=split(/\&/,$rep);
                   1146:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1147:             return @pairs;
                   1148:         }
                   1149:         my $i=0;
                   1150:         foreach my $item (@$storearr) {
                   1151:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1152:             $i++;
                   1153:         }
                   1154:         return %returnhash;
                   1155:     } else {
1.880     banghart 1156:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1157:     }
                   1158: }
                   1159: 
                   1160: # -------------------------------------------- put items in domain db files 
                   1161: 
                   1162: sub put_dom {
1.860     raeburn  1163:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1164:     if (!$udom) {
                   1165:         $udom=$env{'user.domain'};
                   1166:         if (defined(&domain($udom,'primary'))) {
                   1167:             $uhome=&domain($udom,'primary');
                   1168:         } else {
1.874     albertel 1169:             undef($uhome);
1.860     raeburn  1170:         }
                   1171:     } else {
                   1172:         if (!$uhome) {
                   1173:             if (defined(&domain($udom,'primary'))) {
                   1174:                 $uhome=&domain($udom,'primary');
                   1175:             }
                   1176:         }
                   1177:     } 
                   1178:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1179:         my $items='';
                   1180:         foreach my $item (keys(%$storehash)) {
                   1181:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1182:         }
                   1183:         $items=~s/\&$//;
                   1184:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1185:     } else {
1.860     raeburn  1186:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1187:     }
                   1188: }
                   1189: 
1.1023    raeburn  1190: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1191: sub newput_dom {
1.1023    raeburn  1192:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1193:     my $result;
                   1194:     if (!$udom) {
                   1195:         $udom=$env{'user.domain'};
                   1196:     }
1.1023    raeburn  1197:     if ($udom) {
                   1198:         my $uname = &get_domainconfiguser($udom);
                   1199:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1200:     }
                   1201:     return $result;
                   1202: }
                   1203: 
1.1023    raeburn  1204: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1205: sub del_dom {
1.1023    raeburn  1206:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1207:     if (ref($storearr) eq 'ARRAY') {
                   1208:         if (!$udom) {
                   1209:             $udom=$env{'user.domain'};
                   1210:         }
1.1023    raeburn  1211:         if ($udom) {
                   1212:             my $uname = &get_domainconfiguser($udom); 
                   1213:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1214:         }
                   1215:     }
                   1216: }
                   1217: 
1.1023    raeburn  1218: # ----------------------------------construct domainconfig user for a domain 
                   1219: sub get_domainconfiguser {
                   1220:     my ($udom) = @_;
                   1221:     return $udom.'-domainconfig';
                   1222: }
                   1223: 
1.837     raeburn  1224: sub retrieve_inst_usertypes {
                   1225:     my ($udom) = @_;
                   1226:     my (%returnhash,@order);
1.989     raeburn  1227:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1228:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1229:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1230:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1231:         @order = @{$domdefs{'inststatusorder'}};
                   1232:     } else {
                   1233:         if (defined(&domain($udom,'primary'))) {
                   1234:             my $uhome=&domain($udom,'primary');
                   1235:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1236:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1237:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1238:                 return (\%returnhash,\@order);
                   1239:             }
                   1240:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1241:             my @pairs=split(/\&/,$hashitems);
                   1242:             foreach my $item (@pairs) {
                   1243:                 my ($key,$value)=split(/=/,$item,2);
                   1244:                 $key = &unescape($key);
                   1245:                 next if ($key =~ /^error: 2 /);
                   1246:                 $returnhash{$key}=&thaw_unescape($value);
                   1247:             }
                   1248:             my @esc_order = split(/\&/,$orderitems);
                   1249:             foreach my $item (@esc_order) {
                   1250:                 push(@order,&unescape($item));
                   1251:             }
                   1252:         } else {
                   1253:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1254:         }
                   1255:     }
                   1256:     return (\%returnhash,\@order);
                   1257: }
                   1258: 
1.868     raeburn  1259: sub is_domainimage {
                   1260:     my ($url) = @_;
                   1261:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1262:         if (&domain($1) ne '') {
                   1263:             return '1';
                   1264:         }
                   1265:     }
                   1266:     return;
                   1267: }
                   1268: 
1.899     raeburn  1269: sub inst_directory_query {
                   1270:     my ($srch) = @_;
                   1271:     my $udom = $srch->{'srchdomain'};
                   1272:     my %results;
                   1273:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1274:     my $outcome;
1.899     raeburn  1275:     if ($homeserver ne '') {
1.904     albertel 1276: 	my $queryid=&reply("querysend:instdirsearch:".
                   1277: 			   &escape($srch->{'srchby'}).':'.
                   1278: 			   &escape($srch->{'srchterm'}).':'.
                   1279: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1280: 	my $host=&hostname($homeserver);
                   1281: 	if ($queryid !~/^\Q$host\E\_/) {
                   1282: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1283: 	    return;
                   1284: 	}
                   1285: 	my $response = &get_query_reply($queryid);
                   1286: 	my $maxtries = 5;
                   1287: 	my $tries = 1;
                   1288: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1289: 	    $response = &get_query_reply($queryid);
                   1290: 	    $tries ++;
                   1291: 	}
                   1292: 
                   1293:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1294:             if ($response eq 'unavailable') {
                   1295:                 $outcome = $response;
                   1296:             } else {
                   1297:                 $outcome = 'ok';
                   1298:                 my @matches = split(/\n/,$response);
                   1299:                 foreach my $match (@matches) {
                   1300:                     my ($key,$value) = split(/=/,$match);
                   1301:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1302:                 }
1.899     raeburn  1303:             }
                   1304:         }
                   1305:     }
1.909     raeburn  1306:     return ($outcome,%results);
1.899     raeburn  1307: }
                   1308: 
                   1309: sub usersearch {
                   1310:     my ($srch) = @_;
                   1311:     my $dom = $srch->{'srchdomain'};
                   1312:     my %results;
                   1313:     my %libserv = &all_library();
                   1314:     my $query = 'usersearch';
                   1315:     foreach my $tryserver (keys(%libserv)) {
                   1316:         if (&host_domain($tryserver) eq $dom) {
                   1317:             my $host=&hostname($tryserver);
                   1318:             my $queryid=
1.911     raeburn  1319:                 &reply("querysend:".&escape($query).':'.
                   1320:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1321:                        &escape($srch->{'srchtype'}).':'.
                   1322:                        &escape($srch->{'srchterm'}),$tryserver);
                   1323:             if ($queryid !~/^\Q$host\E\_/) {
                   1324:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1325:                 next;
1.899     raeburn  1326:             }
                   1327:             my $reply = &get_query_reply($queryid);
                   1328:             my $maxtries = 1;
                   1329:             my $tries = 1;
                   1330:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1331:                 $reply = &get_query_reply($queryid);
                   1332:                 $tries ++;
                   1333:             }
                   1334:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1335:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1336:             } else {
1.911     raeburn  1337:                 my @matches;
                   1338:                 if ($reply =~ /\n/) {
                   1339:                     @matches = split(/\n/,$reply);
                   1340:                 } else {
                   1341:                     @matches = split(/\&/,$reply);
                   1342:                 }
1.899     raeburn  1343:                 foreach my $match (@matches) {
                   1344:                     my ($uname,$udom,%userhash);
1.911     raeburn  1345:                     foreach my $entry (split(/:/,$match)) {
                   1346:                         my ($key,$value) =
                   1347:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1348:                         $userhash{$key} = $value;
                   1349:                         if ($key eq 'username') {
                   1350:                             $uname = $value;
                   1351:                         } elsif ($key eq 'domain') {
                   1352:                             $udom = $value;
1.911     raeburn  1353:                         }
1.899     raeburn  1354:                     }
                   1355:                     $results{$uname.':'.$udom} = \%userhash;
                   1356:                 }
                   1357:             }
                   1358:         }
                   1359:     }
                   1360:     return %results;
                   1361: }
                   1362: 
1.912     raeburn  1363: sub get_instuser {
                   1364:     my ($udom,$uname,$id) = @_;
                   1365:     my $homeserver = &domain($udom,'primary');
                   1366:     my ($outcome,%results);
                   1367:     if ($homeserver ne '') {
                   1368:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1369:                            &escape($id).':'.&escape($udom),$homeserver);
                   1370:         my $host=&hostname($homeserver);
                   1371:         if ($queryid !~/^\Q$host\E\_/) {
                   1372:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1373:             return;
                   1374:         }
                   1375:         my $response = &get_query_reply($queryid);
                   1376:         my $maxtries = 5;
                   1377:         my $tries = 1;
                   1378:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1379:             $response = &get_query_reply($queryid);
                   1380:             $tries ++;
                   1381:         }
                   1382:         if (!&error($response) && $response ne 'refused') {
                   1383:             if ($response eq 'unavailable') {
                   1384:                 $outcome = $response;
                   1385:             } else {
                   1386:                 $outcome = 'ok';
                   1387:                 my @matches = split(/\n/,$response);
                   1388:                 foreach my $match (@matches) {
                   1389:                     my ($key,$value) = split(/=/,$match);
                   1390:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1391:                 }
                   1392:             }
                   1393:         }
                   1394:     }
                   1395:     my %userinfo;
                   1396:     if (ref($results{$uname}) eq 'HASH') {
                   1397:         %userinfo = %{$results{$uname}};
                   1398:     } 
                   1399:     return ($outcome,%userinfo);
                   1400: }
                   1401: 
                   1402: sub inst_rulecheck {
1.923     raeburn  1403:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1404:     my %returnhash;
                   1405:     if ($udom ne '') {
                   1406:         if (ref($rules) eq 'ARRAY') {
                   1407:             @{$rules} = map {&escape($_);} (@{$rules});
                   1408:             my $rulestr = join(':',@{$rules});
                   1409:             my $homeserver=&domain($udom,'primary');
                   1410:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1411:                 my $response;
                   1412:                 if ($item eq 'username') {                
                   1413:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1414:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1415:                                               $homeserver));
1.923     raeburn  1416:                 } elsif ($item eq 'id') {
                   1417:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1418:                                               ':'.&escape($id).':'.$rulestr,
                   1419:                                               $homeserver));
1.945     raeburn  1420:                 } elsif ($item eq 'selfcreate') {
                   1421:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1422:                                                &escape($udom).':'.&escape($uname).
                   1423:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1424:                 }
1.912     raeburn  1425:                 if ($response ne 'refused') {
                   1426:                     my @pairs=split(/\&/,$response);
                   1427:                     foreach my $item (@pairs) {
                   1428:                         my ($key,$value)=split(/=/,$item,2);
                   1429:                         $key = &unescape($key);
                   1430:                         next if ($key =~ /^error: 2 /);
                   1431:                         $returnhash{$key}=&thaw_unescape($value);
                   1432:                     }
                   1433:                 }
                   1434:             }
                   1435:         }
                   1436:     }
                   1437:     return %returnhash;
                   1438: }
                   1439: 
                   1440: sub inst_userrules {
1.923     raeburn  1441:     my ($udom,$check) = @_;
1.912     raeburn  1442:     my (%ruleshash,@ruleorder);
                   1443:     if ($udom ne '') {
                   1444:         my $homeserver=&domain($udom,'primary');
                   1445:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1446:             my $response;
                   1447:             if ($check eq 'id') {
                   1448:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1449:                                  $homeserver);
1.943     raeburn  1450:             } elsif ($check eq 'email') {
                   1451:                 $response=&reply('instemailrules:'.&escape($udom),
                   1452:                                  $homeserver);
1.923     raeburn  1453:             } else {
                   1454:                 $response=&reply('instuserrules:'.&escape($udom),
                   1455:                                  $homeserver);
                   1456:             }
1.912     raeburn  1457:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1458:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1459:                 ($response ne 'no_such_host')) {
                   1460:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1461:                 my @pairs=split(/\&/,$hashitems);
                   1462:                 foreach my $item (@pairs) {
                   1463:                     my ($key,$value)=split(/=/,$item,2);
                   1464:                     $key = &unescape($key);
                   1465:                     next if ($key =~ /^error: 2 /);
                   1466:                     $ruleshash{$key}=&thaw_unescape($value);
                   1467:                 }
                   1468:                 my @esc_order = split(/\&/,$orderitems);
                   1469:                 foreach my $item (@esc_order) {
                   1470:                     push(@ruleorder,&unescape($item));
                   1471:                 }
                   1472:             }
                   1473:         }
                   1474:     }
                   1475:     return (\%ruleshash,\@ruleorder);
                   1476: }
                   1477: 
1.976     raeburn  1478: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1479: 
                   1480: sub get_domain_defaults {
                   1481:     my ($domain) = @_;
                   1482:     my $cachetime = 60*60*24;
                   1483:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1484:     if (defined($cached)) {
                   1485:         if (ref($result) eq 'HASH') {
                   1486:             return %{$result};
                   1487:         }
                   1488:     }
                   1489:     my %domdefaults;
                   1490:     my %domconfig =
1.989     raeburn  1491:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1492:                                   'requestcourses','inststatus',
1.1056.4.3  raeburn  1493:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1494:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1495:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1496:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1497:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1498:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1499:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1500:     } else {
                   1501:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1502:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1503:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1504:     }
1.976     raeburn  1505:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1506:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1507:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1508:         } else {
                   1509:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1510:         } 
                   1511:         my @usertools = ('aboutme','blog','portfolio');
                   1512:         foreach my $item (@usertools) {
                   1513:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1514:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1515:             }
                   1516:         }
                   1517:     }
1.985     raeburn  1518:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1519:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1520:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1521:         }
                   1522:     }
1.989     raeburn  1523:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1524:         foreach my $item ('inststatustypes','inststatusorder') {
                   1525:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1526:         }
                   1527:     }
1.1047    raeburn  1528:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1529:         foreach my $item ('canuse_pdfforms') {
                   1530:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1531:         }
                   1532:     }
1.1056.4.3  raeburn  1533:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1534:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1535:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1536:         }
                   1537:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1538:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1539:         }
                   1540:     }
1.943     raeburn  1541:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1542:                                   $cachetime);
                   1543:     return %domdefaults;
                   1544: }
                   1545: 
1.344     www      1546: # --------------------------------------------------- Assign a key to a student
                   1547: 
                   1548: sub assign_access_key {
1.364     www      1549: #
                   1550: # a valid key looks like uname:udom#comments
                   1551: # comments are being appended
                   1552: #
1.498     www      1553:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1554:     $kdom=
1.620     albertel 1555:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1556:     $knum=
1.620     albertel 1557:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1558:     $cdom=
1.620     albertel 1559:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1560:     $cnum=
1.620     albertel 1561:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1562:     $udom=$env{'user.name'} unless (defined($udom));
                   1563:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1564:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1565:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1566:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1567:                                                   # assigned to this person
                   1568:                                                   # - this should not happen,
1.345     www      1569:                                                   # unless something went wrong
                   1570:                                                   # the first time around
                   1571: # ready to assign
1.364     www      1572:         $logentry=$1.'; '.$logentry;
1.496     www      1573:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1574:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1575: # key now belongs to user
1.346     www      1576: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1577:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1578:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1579:                 return 'ok';
                   1580:             } else {
                   1581:                 return 
                   1582:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1583: 	    }
                   1584:         } else {
                   1585:             return 'error: Could not assign key, try again later.';
                   1586:         }
1.364     www      1587:     } elsif (!$existing{$ckey}) {
1.345     www      1588: # the key does not exist
                   1589: 	return 'error: The key does not exist';
                   1590:     } else {
                   1591: # the key is somebody else's
                   1592: 	return 'error: The key is already in use';
                   1593:     }
1.344     www      1594: }
                   1595: 
1.364     www      1596: # ------------------------------------------ put an additional comment on a key
                   1597: 
                   1598: sub comment_access_key {
                   1599: #
                   1600: # a valid key looks like uname:udom#comments
                   1601: # comments are being appended
                   1602: #
                   1603:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1604:     $cdom=
1.620     albertel 1605:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1606:     $cnum=
1.620     albertel 1607:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1608:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1609:     if ($existing{$ckey}) {
                   1610:         $existing{$ckey}.='; '.$logentry;
                   1611: # ready to assign
1.367     www      1612:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1613:                                                  $cdom,$cnum) eq 'ok') {
                   1614: 	    return 'ok';
                   1615:         } else {
                   1616: 	    return 'error: Count not store comment.';
                   1617:         }
                   1618:     } else {
                   1619: # the key does not exist
                   1620: 	return 'error: The key does not exist';
                   1621:     }
                   1622: }
                   1623: 
1.344     www      1624: # ------------------------------------------------------ Generate a set of keys
                   1625: 
                   1626: sub generate_access_keys {
1.364     www      1627:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1628:     $cdom=
1.620     albertel 1629:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1630:     $cnum=
1.620     albertel 1631:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1632:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1633:     unless (($cdom) && ($cnum)) { return 0; }
                   1634:     if ($number>10000) { return 0; }
                   1635:     sleep(2); # make sure don't get same seed twice
                   1636:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1637:     my $total=0;
                   1638:     for (my $i=1;$i<=$number;$i++) {
                   1639:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1640:                   sprintf("%lx",int(100000*rand)).'-'.
                   1641:                   sprintf("%lx",int(100000*rand));
                   1642:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1643:        $newkey=~s/0/h/g; # and also 0 and O
                   1644:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1645:        if ($existing{$newkey}) {
                   1646:            $i--;
                   1647:        } else {
1.364     www      1648: 	  if (&put('accesskeys',
                   1649:               { $newkey => '# generated '.localtime().
1.620     albertel 1650:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1651:                            '; '.$logentry },
                   1652: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1653:               $total++;
                   1654: 	  }
                   1655:        }
                   1656:     }
1.620     albertel 1657:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1658:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1659:     return $total;
                   1660: }
                   1661: 
                   1662: # ------------------------------------------------------- Validate an accesskey
                   1663: 
                   1664: sub validate_access_key {
                   1665:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1666:     $cdom=
1.620     albertel 1667:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1668:     $cnum=
1.620     albertel 1669:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1670:     $udom=$env{'user.domain'} unless (defined($udom));
                   1671:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1672:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1673:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1674: }
                   1675: 
                   1676: # ------------------------------------- Find the section of student in a course
1.652     albertel 1677: sub devalidate_getsection_cache {
                   1678:     my ($udom,$unam,$courseid)=@_;
                   1679:     my $hashid="$udom:$unam:$courseid";
                   1680:     &devalidate_cache_new('getsection',$hashid);
                   1681: }
1.298     matthew  1682: 
1.815     albertel 1683: sub courseid_to_courseurl {
                   1684:     my ($courseid) = @_;
                   1685:     #already url style courseid
                   1686:     return $courseid if ($courseid =~ m{^/});
                   1687: 
                   1688:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1689: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1690: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1691: 	return "/$cdom/$cnum";
                   1692:     }
                   1693: 
                   1694:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1695:     if (exists($courseinfo{'num'})) {
                   1696: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1697:     }
                   1698: 
                   1699:     return undef;
                   1700: }
                   1701: 
1.298     matthew  1702: sub getsection {
                   1703:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1704:     my $cachetime=1800;
1.551     albertel 1705: 
                   1706:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1707:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1708:     if (defined($cached)) { return $result; }
                   1709: 
1.298     matthew  1710:     my %Pending; 
                   1711:     my %Expired;
                   1712:     #
                   1713:     # Each role can either have not started yet (pending), be active, 
                   1714:     #    or have expired.
                   1715:     #
                   1716:     # If there is an active role, we are done.
                   1717:     #
                   1718:     # If there is more than one role which has not started yet, 
                   1719:     #     choose the one which will start sooner
                   1720:     # If there is one role which has not started yet, return it.
                   1721:     #
                   1722:     # If there is more than one expired role, choose the one which ended last.
                   1723:     # If there is a role which has expired, return it.
                   1724:     #
1.815     albertel 1725:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1726:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1727:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1728:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1729:         my $section=$1;
                   1730:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1731:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1732:         my $now=time;
1.548     albertel 1733:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1734:             $Expired{$end}=$section;
                   1735:             next;
                   1736:         }
1.548     albertel 1737:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1738:             $Pending{$start}=$section;
                   1739:             next;
                   1740:         }
1.599     albertel 1741:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1742:     }
                   1743:     #
                   1744:     # Presumedly there will be few matching roles from the above
                   1745:     # loop and the sorting time will be negligible.
                   1746:     if (scalar(keys(%Pending))) {
                   1747:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1748:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1749:     } 
                   1750:     if (scalar(keys(%Expired))) {
                   1751:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1752:         my $time = pop(@sorted);
1.599     albertel 1753:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1754:     }
1.599     albertel 1755:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1756: }
1.70      www      1757: 
1.599     albertel 1758: sub save_cache {
                   1759:     &purge_remembered();
1.722     albertel 1760:     #&Apache::loncommon::validate_page();
1.620     albertel 1761:     undef(%env);
1.780     albertel 1762:     undef($env_loaded);
1.599     albertel 1763: }
1.452     albertel 1764: 
1.599     albertel 1765: my $to_remember=-1;
                   1766: my %remembered;
                   1767: my %accessed;
                   1768: my $kicks=0;
                   1769: my $hits=0;
1.849     albertel 1770: sub make_key {
                   1771:     my ($name,$id) = @_;
1.872     albertel 1772:     if (length($id) > 65 
                   1773: 	&& length(&escape($id)) > 200) {
                   1774: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1775:     }
1.849     albertel 1776:     return &escape($name.':'.$id);
                   1777: }
                   1778: 
1.599     albertel 1779: sub devalidate_cache_new {
                   1780:     my ($name,$id,$debug) = @_;
                   1781:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1782:     $id=&make_key($name,$id);
1.599     albertel 1783:     $memcache->delete($id);
                   1784:     delete($remembered{$id});
                   1785:     delete($accessed{$id});
                   1786: }
                   1787: 
                   1788: sub is_cached_new {
                   1789:     my ($name,$id,$debug) = @_;
1.849     albertel 1790:     $id=&make_key($name,$id);
1.599     albertel 1791:     if (exists($remembered{$id})) {
                   1792: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1793: 	$accessed{$id}=[&gettimeofday()];
                   1794: 	$hits++;
                   1795: 	return ($remembered{$id},1);
                   1796:     }
                   1797:     my $value = $memcache->get($id);
                   1798:     if (!(defined($value))) {
                   1799: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1800: 	return (undef,undef);
1.416     albertel 1801:     }
1.599     albertel 1802:     if ($value eq '__undef__') {
                   1803: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1804: 	$value=undef;
                   1805:     }
                   1806:     &make_room($id,$value,$debug);
                   1807:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1808:     return ($value,1);
                   1809: }
                   1810: 
                   1811: sub do_cache_new {
                   1812:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1813:     $id=&make_key($name,$id);
1.599     albertel 1814:     my $setvalue=$value;
                   1815:     if (!defined($setvalue)) {
                   1816: 	$setvalue='__undef__';
                   1817:     }
1.623     albertel 1818:     if (!defined($time) ) {
                   1819: 	$time=600;
                   1820:     }
1.599     albertel 1821:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1822:     my $result = $memcache->set($id,$setvalue,$time);
                   1823:     if (! $result) {
1.872     albertel 1824: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1825: 	$memcache->disconnect_all();
1.872     albertel 1826:     }
1.600     albertel 1827:     # need to make a copy of $value
1.919     albertel 1828:     &make_room($id,$value,$debug);
1.599     albertel 1829:     return $value;
                   1830: }
                   1831: 
                   1832: sub make_room {
                   1833:     my ($id,$value,$debug)=@_;
1.919     albertel 1834: 
                   1835:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1836:                                     : $value;
1.599     albertel 1837:     if ($to_remember<0) { return; }
                   1838:     $accessed{$id}=[&gettimeofday()];
                   1839:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1840:     my $to_kick;
                   1841:     my $max_time=0;
                   1842:     foreach my $other (keys(%accessed)) {
                   1843: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1844: 	    $to_kick=$other;
                   1845: 	    $max_time=&tv_interval($accessed{$other});
                   1846: 	}
                   1847:     }
                   1848:     delete($remembered{$to_kick});
                   1849:     delete($accessed{$to_kick});
                   1850:     $kicks++;
                   1851:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1852:     return;
                   1853: }
                   1854: 
1.599     albertel 1855: sub purge_remembered {
1.604     albertel 1856:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1857:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1858:     undef(%remembered);
                   1859:     undef(%accessed);
1.428     albertel 1860: }
1.70      www      1861: # ------------------------------------- Read an entry from a user's environment
                   1862: 
                   1863: sub userenvironment {
                   1864:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1865:     my $items;
                   1866:     foreach my $item (@what) {
                   1867:         $items.=&escape($item).'&';
                   1868:     }
                   1869:     $items=~s/\&$//;
1.70      www      1870:     my %returnhash=();
1.1009    raeburn  1871:     my $uhome = &homeserver($unam,$udom);
                   1872:     unless ($uhome eq 'no_host') {
                   1873:         my @answer=split(/\&/, 
                   1874:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1875:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1876:             return %returnhash;
                   1877:         }
1.1009    raeburn  1878:         my $i;
                   1879:         for ($i=0;$i<=$#what;$i++) {
                   1880: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1881:         }
1.70      www      1882:     }
                   1883:     return %returnhash;
1.1       albertel 1884: }
                   1885: 
1.617     albertel 1886: # ---------------------------------------------------------- Get a studentphoto
                   1887: sub studentphoto {
                   1888:     my ($udom,$unam,$ext) = @_;
                   1889:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1890:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1891:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1892:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1893:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1894:             } else {
                   1895:                 my ($result,$perm_reqd)=
1.707     albertel 1896: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1897:                 if ($result eq 'ok') {
                   1898:                     if (!($perm_reqd eq 'yes')) {
                   1899:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1900:                     }
                   1901:                 }
                   1902:             }
                   1903:         }
                   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:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1914: }
                   1915: 
                   1916: sub retrievestudentphoto {
                   1917:     my ($udom,$unam,$ext,$type) = @_;
                   1918:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1919:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1920:     if ($ret eq 'ok') {
                   1921:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1922:         if ($type eq 'thumbnail') {
                   1923:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1924:         }
                   1925:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1926:         return $tokenurl;
                   1927:     } else {
                   1928:         if ($type eq 'thumbnail') {
                   1929:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1930:         } else { 
                   1931:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1932:         }
1.617     albertel 1933:     }
                   1934: }
                   1935: 
1.263     www      1936: # -------------------------------------------------------------------- New chat
                   1937: 
                   1938: sub chatsend {
1.724     raeburn  1939:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1940:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1941:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1942:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1943:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1944: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1945: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1946: }
                   1947: 
                   1948: # ------------------------------------------ Find current version of a resource
                   1949: 
                   1950: sub getversion {
                   1951:     my $fname=&clutter(shift);
                   1952:     unless ($fname=~/^\/res\//) { return -1; }
                   1953:     return &currentversion(&filelocation('',$fname));
                   1954: }
                   1955: 
                   1956: sub currentversion {
                   1957:     my $fname=shift;
1.599     albertel 1958:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1959:     if (defined($cached)) { return $result; }
1.292     www      1960:     my $author=$fname;
                   1961:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1962:     my ($udom,$uname)=split(/\//,$author);
                   1963:     my $home=homeserver($uname,$udom);
                   1964:     if ($home eq 'no_host') { 
                   1965:         return -1; 
                   1966:     }
                   1967:     my $answer=reply("currentversion:$fname",$home);
                   1968:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1969: 	return -1;
                   1970:     }
1.599     albertel 1971:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1972: }
                   1973: 
1.1       albertel 1974: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1975: 
1.1       albertel 1976: sub subscribe {
                   1977:     my $fname=shift;
1.761     raeburn  1978:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1979:     $fname=~s/[\n\r]//g;
1.1       albertel 1980:     my $author=$fname;
                   1981:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1982:     my ($udom,$uname)=split(/\//,$author);
                   1983:     my $home=homeserver($uname,$udom);
1.335     albertel 1984:     if ($home eq 'no_host') {
                   1985:         return 'not_found';
1.1       albertel 1986:     }
                   1987:     my $answer=reply("sub:$fname",$home);
1.64      www      1988:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1989: 	$answer.=' by '.$home;
                   1990:     }
1.1       albertel 1991:     return $answer;
                   1992: }
                   1993:     
1.8       www      1994: # -------------------------------------------------------------- Replicate file
                   1995: 
                   1996: sub repcopy {
                   1997:     my $filename=shift;
1.23      www      1998:     $filename=~s/\/+/\//g;
1.607     raeburn  1999:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2000:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2001:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2002: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2003: 	return &repcopy_userfile($filename);
                   2004:     }
1.532     albertel 2005:     $filename=~s/[\n\r]//g;
1.8       www      2006:     my $transname="$filename.in.transfer";
1.828     www      2007: # FIXME: this should flock
1.607     raeburn  2008:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2009:     my $remoteurl=subscribe($filename);
1.64      www      2010:     if ($remoteurl =~ /^con_lost by/) {
                   2011: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2012:            return 'unavailable';
1.8       www      2013:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2014: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2015: 	   return 'not_found';
1.64      www      2016:     } elsif ($remoteurl =~ /^rejected by/) {
                   2017: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2018:            return 'forbidden';
1.20      www      2019:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2020:            return 'ok';
1.8       www      2021:     } else {
1.290     www      2022:         my $author=$filename;
                   2023:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2024:         my ($udom,$uname)=split(/\//,$author);
                   2025:         my $home=homeserver($uname,$udom);
                   2026:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2027:            my @parts=split(/\//,$filename);
                   2028:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2029:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2030:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2031: 	       return 'bad_request';
1.8       www      2032:            }
                   2033:            my $count;
                   2034:            for ($count=5;$count<$#parts;$count++) {
                   2035:                $path.="/$parts[$count]";
                   2036:                if ((-e $path)!=1) {
                   2037: 		   mkdir($path,0777);
                   2038:                }
                   2039:            }
                   2040:            my $ua=new LWP::UserAgent;
                   2041:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2042:            my $response=$ua->request($request,$transname);
                   2043:            if ($response->is_error()) {
                   2044: 	       unlink($transname);
                   2045:                my $message=$response->status_line;
1.672     albertel 2046:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2047:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2048:                return 'unavailable';
1.8       www      2049:            } else {
1.16      www      2050: 	       if ($remoteurl!~/\.meta$/) {
                   2051:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2052:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2053:                   if ($mresponse->is_error()) {
                   2054: 		      unlink($filename.'.meta');
                   2055:                       &logthis(
1.672     albertel 2056:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2057:                   }
                   2058: 	       }
1.8       www      2059:                rename($transname,$filename);
1.607     raeburn  2060:                return 'ok';
1.8       www      2061:            }
1.290     www      2062:        }
1.8       www      2063:     }
1.330     www      2064: }
                   2065: 
                   2066: # ------------------------------------------------ Get server side include body
                   2067: sub ssi_body {
1.381     albertel 2068:     my ($filelink,%form)=@_;
1.606     matthew  2069:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2070:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2071:     }
1.953     www      2072:     my $output='';
                   2073:     my $response;
1.980     raeburn  2074:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2075:        ($output,$response)=&externalssi($filelink);
1.953     www      2076:     } else {
1.1004    droeschl 2077:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2078:        $filelink .= 'inhibitmenu=yes';
1.953     www      2079:        ($output,$response)=&ssi($filelink,%form);
                   2080:     }
1.778     albertel 2081:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2082:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2083:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2084:     if (wantarray) {
                   2085:         return ($output, $response);
                   2086:     } else {
                   2087:         return $output;
                   2088:     }
1.8       www      2089: }
                   2090: 
1.15      www      2091: # --------------------------------------------------------- Server Side Include
                   2092: 
1.782     albertel 2093: sub absolute_url {
                   2094:     my ($host_name) = @_;
                   2095:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2096:     if ($host_name eq '') {
                   2097: 	$host_name = $ENV{'SERVER_NAME'};
                   2098:     }
                   2099:     return $protocol.$host_name;
                   2100: }
                   2101: 
1.942     foxr     2102: #
                   2103: #   Server side include.
                   2104: # Parameters:
                   2105: #  fn     Possibly encrypted resource name/id.
                   2106: #  form   Hash that describes how the rendering should be done
                   2107: #         and other things.
1.944     foxr     2108: # Returns:
1.950     raeburn  2109: #   Scalar context: The content of the response.
                   2110: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2111: #     
1.15      www      2112: sub ssi {
                   2113: 
1.944     foxr     2114:     my ($fn,%form)=@_;
1.15      www      2115:     my $ua=new LWP::UserAgent;
1.23      www      2116:     my $request;
1.711     albertel 2117: 
                   2118:     $form{'no_update_last_known'}=1;
1.895     albertel 2119:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2120:     if (%form) {
1.782     albertel 2121:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2122:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2123:     } else {
1.782     albertel 2124:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2125:     }
                   2126: 
1.15      www      2127:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2128:     my $response=$ua->request($request);
                   2129: 
1.944     foxr     2130:     if (wantarray) {
                   2131: 	return ($response->content, $response);
                   2132:     } else {
                   2133: 	return $response->content;
1.942     foxr     2134:     }
1.324     www      2135: }
                   2136: 
                   2137: sub externalssi {
                   2138:     my ($url)=@_;
                   2139:     my $ua=new LWP::UserAgent;
                   2140:     my $request=new HTTP::Request('GET',$url);
                   2141:     my $response=$ua->request($request);
1.954     raeburn  2142:     if (wantarray) {
                   2143:         return ($response->content, $response);
                   2144:     } else {
                   2145:         return $response->content;
                   2146:     }
1.15      www      2147: }
1.254     www      2148: 
1.492     albertel 2149: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2150: 
                   2151: sub allowuploaded {
                   2152:     my ($srcurl,$url)=@_;
                   2153:     $url=&clutter(&declutter($url));
                   2154:     my $dir=$url;
                   2155:     $dir=~s/\/[^\/]+$//;
                   2156:     my %httpref=();
                   2157:     my $httpurl=&hreflocation('',$url);
                   2158:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2159:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2160: }
1.477     raeburn  2161: 
1.478     albertel 2162: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2163: # input: action, courseID, current domain, intended
1.637     raeburn  2164: #        path to file, source of file, instruction to parse file for objects,
                   2165: #        ref to hash for embedded objects,
                   2166: #        ref to hash for codebase of java objects.
                   2167: #
1.485     raeburn  2168: # output: url to file (if action was uploaddoc), 
                   2169: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2170: #
1.478     albertel 2171: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2172: # course.
1.477     raeburn  2173: #
1.478     albertel 2174: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2175: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2176: #          course's home server.
1.477     raeburn  2177: #
1.478     albertel 2178: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2179: #          be copied from $source (current location) to 
                   2180: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2181: #         and will then be copied to
                   2182: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2183: #         course's home server.
1.485     raeburn  2184: #
1.481     raeburn  2185: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2186: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2187: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2188: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2189: #         in course's home server.
1.637     raeburn  2190: #
1.477     raeburn  2191: 
                   2192: sub process_coursefile {
1.638     albertel 2193:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2194:     my $fetchresult;
1.638     albertel 2195:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2196:     if ($action eq 'propagate') {
1.638     albertel 2197:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2198: 			     $home);
1.481     raeburn  2199:     } else {
1.477     raeburn  2200:         my $fpath = '';
                   2201:         my $fname = $file;
1.478     albertel 2202:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2203:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2204:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2205:         if ($action eq 'copy') {
                   2206:             if ($source eq '') {
                   2207:                 $fetchresult = 'no source file';
                   2208:                 return $fetchresult;
                   2209:             } else {
                   2210:                 my $destination = $filepath.'/'.$fname;
                   2211:                 rename($source,$destination);
                   2212:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2213:                                  $home);
1.481     raeburn  2214:             }
                   2215:         } elsif ($action eq 'uploaddoc') {
                   2216:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2217:             print $fh $env{'form.'.$source};
1.481     raeburn  2218:             close($fh);
1.637     raeburn  2219:             if ($parser eq 'parse') {
1.1024    raeburn  2220:                 my $mm = new File::MMagic;
                   2221:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2222:                 if ($mime_type eq 'text/html') {
                   2223:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2224:                     unless ($parse_result eq 'ok') {
                   2225:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2226:                     }
1.637     raeburn  2227:                 }
                   2228:             }
1.477     raeburn  2229:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2230:                                  $home);
1.481     raeburn  2231:             if ($fetchresult eq 'ok') {
                   2232:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2233:             } else {
                   2234:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2235:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2236:                 return '/adm/notfound.html';
                   2237:             }
1.477     raeburn  2238:         }
                   2239:     }
1.485     raeburn  2240:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2241:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2242:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2243:     }
                   2244:     return $fetchresult;
                   2245: }
                   2246: 
1.637     raeburn  2247: sub build_filepath {
                   2248:     my ($fpath) = @_;
                   2249:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2250:     unless ($fpath eq '') {
                   2251:         my @parts=split('/',$fpath);
                   2252:         foreach my $part (@parts) {
                   2253:             $filepath.= '/'.$part;
                   2254:             if ((-e $filepath)!=1) {
                   2255:                 mkdir($filepath,0777);
                   2256:             }
                   2257:         }
                   2258:     }
                   2259:     return $filepath;
                   2260: }
                   2261: 
                   2262: sub store_edited_file {
1.638     albertel 2263:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2264:     my $file = $primary_url;
                   2265:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2266:     my $fpath = '';
                   2267:     my $fname = $file;
                   2268:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2269:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2270:     my $filepath = &build_filepath($fpath);
                   2271:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2272:     print $fh $content;
                   2273:     close($fh);
1.638     albertel 2274:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2275:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2276: 			  $home);
1.637     raeburn  2277:     if ($$fetchresult eq 'ok') {
                   2278:         return '/uploaded/'.$fpath.'/'.$fname;
                   2279:     } else {
1.638     albertel 2280:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2281: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2282:         return '/adm/notfound.html';
                   2283:     }
                   2284: }
                   2285: 
1.531     albertel 2286: sub clean_filename {
1.831     albertel 2287:     my ($fname,$args)=@_;
1.315     www      2288: # Replace Windows backslashes by forward slashes
1.257     www      2289:     $fname=~s/\\/\//g;
1.831     albertel 2290:     if (!$args->{'keep_path'}) {
                   2291:         # Get rid of everything but the actual filename
                   2292: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2293:     }
1.315     www      2294: # Replace spaces by underscores
                   2295:     $fname=~s/\s+/\_/g;
                   2296: # Replace all other weird characters by nothing
1.831     albertel 2297:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2298: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2299: # numbers
                   2300:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2301:     return $fname;
                   2302: }
1.1051    raeburn  2303: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2304: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2305: # image with the same aspect ratio as the original, but with dimensions which do 
                   2306: # not exceed $resizewidth and $resizeheight.
                   2307:  
1.984     neumanie 2308: sub resizeImage {
1.1051    raeburn  2309:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2310:     my $ima = Image::Magick->new;
                   2311:     my $resized;
                   2312:     if (-e $img_path) {
                   2313:         $ima->Read($img_path);
                   2314:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2315:             my $width = $ima->Get('width');
                   2316:             my $height = $ima->Get('height');
                   2317:             if ($width > $resizewidth) {
                   2318: 	        my $factor = $width/$resizewidth;
                   2319:                 my $newheight = $height/$factor;
                   2320:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2321:                 $resized = 1;
                   2322:             }
                   2323:         }
                   2324:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2325:             my $width = $ima->Get('width');
                   2326:             my $height = $ima->Get('height');
                   2327:             if ($height > $resizeheight) {
                   2328:                 my $factor = $height/$resizeheight;
                   2329:                 my $newwidth = $width/$factor;
                   2330:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2331:                 $resized = 1;
                   2332:             }
                   2333:         }
                   2334:         if ($resized) {
                   2335:             $ima->Write($img_path);
                   2336:         }
                   2337:     }
                   2338:     return;
1.977     amueller 2339: }
                   2340: 
1.608     albertel 2341: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2342: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2343: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2344: #        $coursedoc - if true up to the current course
                   2345: #                     if false
                   2346: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2347: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2348: #        $allfiles - reference to hash for embedded objects
                   2349: #        $codebase - reference to hash for codebase of java objects
                   2350: #        $desuname - username for permanent storage of uploaded file
                   2351: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2352: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2353: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2354: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2355: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2356: # 
1.686     albertel 2357: # output: url of file in userspace, or error: <message> 
                   2358: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2359: 
1.531     albertel 2360: sub userfileupload {
1.860     raeburn  2361:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2362:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2363:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2364:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2365:     $fname=&clean_filename($fname);
1.315     www      2366: # See if there is anything left
1.257     www      2367:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2368:     chop($env{'form.'.$formname});
1.523     raeburn  2369:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2370:         my $now = time;
                   2371:         my $filepath = 'tmp/helprequests/'.$now;
                   2372:         my @parts=split(/\//,$filepath);
                   2373:         my $fullpath = $perlvar{'lonDaemons'};
                   2374:         for (my $i=0;$i<@parts;$i++) {
                   2375:             $fullpath .= '/'.$parts[$i];
                   2376:             if ((-e $fullpath)!=1) {
                   2377:                 mkdir($fullpath,0777);
                   2378:             }
                   2379:         }
                   2380:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2381:         print $fh $env{'form.'.$formname};
1.523     raeburn  2382:         close($fh);
1.741     raeburn  2383:         return $fullpath.'/'.$fname;
                   2384:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2385:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2386:                        '_'.$env{'user.domain'}.'/pending';
                   2387:         my @parts=split(/\//,$filepath);
                   2388:         my $fullpath = $perlvar{'lonDaemons'};
                   2389:         for (my $i=0;$i<@parts;$i++) {
                   2390:             $fullpath .= '/'.$parts[$i];
                   2391:             if ((-e $fullpath)!=1) {
                   2392:                 mkdir($fullpath,0777);
                   2393:             }
                   2394:         }
                   2395:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2396:         print $fh $env{'form.'.$formname};
                   2397:         close($fh);
                   2398:         return $fullpath.'/'.$fname;
1.523     raeburn  2399:     }
1.995     raeburn  2400:     if ($subdir eq 'scantron') {
                   2401:         $fname = 'scantron_orig_'.$fname;
                   2402:     } else {   
1.258     www      2403: # Create the directory if not present
1.995     raeburn  2404:         $fname="$subdir/$fname";
                   2405:     }
1.259     www      2406:     if ($coursedoc) {
1.638     albertel 2407: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2408: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2409:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2410:             return &finishuserfileupload($docuname,$docudom,
                   2411: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2412: 					 $codebase,$thumbwidth,$thumbheight,
                   2413:                                          $resizewidth,$resizeheight);
1.481     raeburn  2414:         } else {
1.620     albertel 2415:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2416:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2417: 				       $fname,$formname,$parser,
                   2418: 				       $allfiles,$codebase);
1.481     raeburn  2419:         }
1.719     banghart 2420:     } elsif (defined($destuname)) {
                   2421:         my $docuname=$destuname;
                   2422:         my $docudom=$destudom;
1.860     raeburn  2423: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2424: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2425:                                      $thumbwidth,$thumbheight,
                   2426:                                      $resizewidth,$resizeheight);
1.719     banghart 2427:         
1.259     www      2428:     } else {
1.638     albertel 2429:         my $docuname=$env{'user.name'};
                   2430:         my $docudom=$env{'user.domain'};
1.714     raeburn  2431:         if (exists($env{'form.group'})) {
                   2432:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2433:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2434:         }
1.860     raeburn  2435: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2436: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2437:                                      $thumbwidth,$thumbheight,
                   2438:                                      $resizewidth,$resizeheight);
1.259     www      2439:     }
1.271     www      2440: }
                   2441: 
                   2442: sub finishuserfileupload {
1.860     raeburn  2443:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051    raeburn  2444:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477     raeburn  2445:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2446:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2447:   
1.860     raeburn  2448:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2449:     $file=$fname;
                   2450:     if ($fname=~m|/|) {
                   2451:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2452: 	$path.=$fnamepath.'/';
                   2453:     }
1.259     www      2454:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2455:     my $count;
                   2456:     for ($count=4;$count<=$#parts;$count++) {
                   2457:         $filepath.="/$parts[$count]";
                   2458:         if ((-e $filepath)!=1) {
                   2459: 	    mkdir($filepath,0777);
                   2460:         }
                   2461:     }
1.984     neumanie 2462: 
1.258     www      2463: # Save the file
                   2464:     {
1.701     albertel 2465: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2466: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2467: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2468: 	    return '/adm/notfound.html';
                   2469: 	}
                   2470: 	if (!print FH ($env{'form.'.$formname})) {
                   2471: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2472: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2473: 	    return '/adm/notfound.html';
                   2474: 	}
1.570     albertel 2475: 	close(FH);
1.1051    raeburn  2476:         if ($resizewidth && $resizeheight) {
                   2477:             my $mm = new File::MMagic;
                   2478:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2479:             if ($mime_type =~ m{^image/}) {
                   2480: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2481:             }  
1.977     amueller 2482: 	}
1.258     www      2483:     }
1.637     raeburn  2484:     if ($parser eq 'parse') {
1.1024    raeburn  2485:         my $mm = new File::MMagic;
                   2486:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2487:         if ($mime_type eq 'text/html') {
                   2488:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2489:                                                        $allfiles,$codebase);
                   2490:             unless ($parse_result eq 'ok') {
                   2491:                 &logthis('Failed to parse '.$filepath.$file.
                   2492: 	   	         ' for embedded media: '.$parse_result); 
                   2493:             }
1.637     raeburn  2494:         }
                   2495:     }
1.860     raeburn  2496:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2497:         my $input = $filepath.'/'.$file;
                   2498:         my $output = $filepath.'/'.'tn-'.$file;
                   2499:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2500:         system("convert -sample $thumbsize $input $output");
                   2501:         if (-e $filepath.'/'.'tn-'.$file) {
                   2502:             $fetchthumb  = 1; 
                   2503:         }
                   2504:     }
1.858     raeburn  2505:  
1.259     www      2506: # Notify homeserver to grep it
                   2507: #
1.984     neumanie 2508:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2509:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2510:     if ($fetchresult eq 'ok') {
1.860     raeburn  2511:         if ($fetchthumb) {
                   2512:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2513:             if ($thumbresult ne 'ok') {
                   2514:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2515:                          $docuhome.': '.$thumbresult);
                   2516:             }
                   2517:         }
1.259     www      2518: #
1.258     www      2519: # Return the URL to it
1.494     albertel 2520:         return '/uploaded/'.$path.$file;
1.263     www      2521:     } else {
1.494     albertel 2522:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2523: 		 ': '.$fetchresult);
1.263     www      2524:         return '/adm/notfound.html';
1.858     raeburn  2525:     }
1.493     albertel 2526: }
                   2527: 
1.637     raeburn  2528: sub extract_embedded_items {
1.961     raeburn  2529:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2530:     my @state = ();
                   2531:     my %javafiles = (
                   2532:                       codebase => '',
                   2533:                       code => '',
                   2534:                       archive => ''
                   2535:                     );
                   2536:     my %mediafiles = (
                   2537:                       src => '',
                   2538:                       movie => '',
                   2539:                      );
1.648     raeburn  2540:     my $p;
                   2541:     if ($content) {
                   2542:         $p = HTML::LCParser->new($content);
                   2543:     } else {
1.961     raeburn  2544:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2545:     }
1.641     albertel 2546:     while (my $t=$p->get_token()) {
1.640     albertel 2547: 	if ($t->[0] eq 'S') {
                   2548: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2549: 	    push(@state, $tagname);
1.648     raeburn  2550:             if (lc($tagname) eq 'allow') {
                   2551:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2552:             }
1.640     albertel 2553: 	    if (lc($tagname) eq 'img') {
                   2554: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2555: 	    }
1.886     albertel 2556: 	    if (lc($tagname) eq 'a') {
                   2557: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2558: 	    }
1.645     raeburn  2559:             if (lc($tagname) eq 'script') {
                   2560:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2561:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2562:                 } else {
                   2563:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2564:                 }
                   2565:             }
                   2566:             if (lc($tagname) eq 'link') {
                   2567:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2568:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2569:                 }
                   2570:             }
1.640     albertel 2571: 	    if (lc($tagname) eq 'object' ||
                   2572: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2573: 		foreach my $item (keys(%javafiles)) {
                   2574: 		    $javafiles{$item} = '';
                   2575: 		}
                   2576: 	    }
                   2577: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2578: 		my $name = lc($attr->{'name'});
                   2579: 		foreach my $item (keys(%javafiles)) {
                   2580: 		    if ($name eq $item) {
                   2581: 			$javafiles{$item} = $attr->{'value'};
                   2582: 			last;
                   2583: 		    }
                   2584: 		}
                   2585: 		foreach my $item (keys(%mediafiles)) {
                   2586: 		    if ($name eq $item) {
                   2587: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2588: 			last;
                   2589: 		    }
                   2590: 		}
                   2591: 	    }
                   2592: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2593: 		foreach my $item (keys(%javafiles)) {
                   2594: 		    if ($attr->{$item}) {
                   2595: 			$javafiles{$item} = $attr->{$item};
                   2596: 			last;
                   2597: 		    }
                   2598: 		}
                   2599: 		foreach my $item (keys(%mediafiles)) {
                   2600: 		    if ($attr->{$item}) {
                   2601: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2602: 			last;
                   2603: 		    }
                   2604: 		}
                   2605: 	    }
                   2606: 	} elsif ($t->[0] eq 'E') {
                   2607: 	    my ($tagname) = ($t->[1]);
                   2608: 	    if ($javafiles{'codebase'} ne '') {
                   2609: 		$javafiles{'codebase'} .= '/';
                   2610: 	    }  
                   2611: 	    if (lc($tagname) eq 'applet' ||
                   2612: 		lc($tagname) eq 'object' ||
                   2613: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2614: 		) {
                   2615: 		foreach my $item (keys(%javafiles)) {
                   2616: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2617: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2618: 			&add_filetype($allfiles,$file,$item);
                   2619: 		    }
                   2620: 		}
                   2621: 	    } 
                   2622: 	    pop @state;
                   2623: 	}
                   2624:     }
1.637     raeburn  2625:     return 'ok';
                   2626: }
                   2627: 
1.639     albertel 2628: sub add_filetype {
                   2629:     my ($allfiles,$file,$type)=@_;
                   2630:     if (exists($allfiles->{$file})) {
                   2631: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2632: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2633: 	}
                   2634:     } else {
                   2635: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2636:     }
                   2637: }
                   2638: 
1.493     albertel 2639: sub removeuploadedurl {
1.984     neumanie 2640:     my ($url)=@_;	
                   2641:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2642:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2643: }
                   2644: 
                   2645: sub removeuserfile {
                   2646:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2647:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2648:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2649:     if ($result eq 'ok') {	
1.798     raeburn  2650:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2651:             my $metafile = $fname.'.meta';
                   2652:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2653: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2654:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2655:             my $sqlresult = 
1.823     albertel 2656:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2657:                                         'portfolio_metadata',$group,
                   2658:                                         'delete');
1.798     raeburn  2659:         }
                   2660:     }
                   2661:     return $result;
1.257     www      2662: }
1.15      www      2663: 
1.530     albertel 2664: sub mkdiruserfile {
                   2665:     my ($docuname,$docudom,$dir)=@_;
                   2666:     my $home=&homeserver($docuname,$docudom);
                   2667:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2668: }
                   2669: 
1.531     albertel 2670: sub renameuserfile {
                   2671:     my ($docuname,$docudom,$old,$new)=@_;
                   2672:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2673:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2674:                         &escape("$old").':'.&escape("$new"),$home);
                   2675:     if ($result eq 'ok') {
                   2676:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2677:             my $oldmeta = $old.'.meta';
                   2678:             my $newmeta = $new.'.meta';
                   2679:             my $metaresult = 
                   2680:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2681: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2682:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2683:             my $sqlresult = 
1.823     albertel 2684:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2685:                                         'portfolio_metadata',$group,
                   2686:                                         'delete');
1.798     raeburn  2687:         }
                   2688:     }
                   2689:     return $result;
1.531     albertel 2690: }
                   2691: 
1.14      www      2692: # ------------------------------------------------------------------------- Log
                   2693: 
                   2694: sub log {
                   2695:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2696:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2697: }
                   2698: 
                   2699: # ------------------------------------------------------------------ Course Log
1.352     www      2700: #
                   2701: # This routine flushes several buffers of non-mission-critical nature
                   2702: #
1.157     www      2703: 
                   2704: sub flushcourselogs {
1.352     www      2705:     &logthis('Flushing log buffers');
                   2706: #
                   2707: # course logs
                   2708: # This is a log of all transactions in a course, which can be used
                   2709: # for data mining purposes
                   2710: #
                   2711: # It also collects the courseid database, which lists last transaction
                   2712: # times and course titles for all courseids
                   2713: #
                   2714:     my %courseidbuffer=();
1.921     raeburn  2715:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2716:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2717: 		          &escape($courselogs{$crsid}),
                   2718: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2719: 	    delete $courselogs{$crsid};
                   2720:         } else {
                   2721:             &logthis('Failed to flush log buffer for '.$crsid);
                   2722:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2723:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2724:                         " exceeded maximum size, deleting.</font>");
                   2725:                delete $courselogs{$crsid};
                   2726:             }
1.352     www      2727:         }
1.920     raeburn  2728:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2729:             'description' => $coursedescrbuf{$crsid},
                   2730:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2731:             'type'        => $coursetypebuf{$crsid},
                   2732:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2733:         };
1.191     harris41 2734:     }
1.352     www      2735: #
                   2736: # Write course id database (reverse lookup) to homeserver of courses 
                   2737: # Is used in pickcourse
                   2738: #
1.840     albertel 2739:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2740:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2741:                                     $courseidbuffer{$crs_home},
                   2742:                                     $crs_home,'timeonly');
1.352     www      2743:     }
                   2744: #
                   2745: # File accesses
                   2746: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2747: #
1.449     matthew  2748:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2749:         if ($entry =~ /___count$/) {
                   2750:             my ($dom,$name);
1.807     albertel 2751:             ($dom,$name,undef)=
1.811     albertel 2752: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2753:             if (! defined($dom) || $dom eq '' || 
                   2754:                 ! defined($name) || $name eq '') {
1.620     albertel 2755:                 my $cid = $env{'request.course.id'};
                   2756:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2757:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2758:             }
1.450     matthew  2759:             my $value = $accesshash{$entry};
                   2760:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2761:             my %temphash=($url => $value);
1.449     matthew  2762:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2763:             if ($result eq 'ok') {
                   2764:                 delete $accesshash{$entry};
                   2765:             } elsif ($result eq 'unknown_cmd') {
                   2766:                 # Target server has old code running on it.
1.450     matthew  2767:                 my %temphash=($entry => $value);
1.449     matthew  2768:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2769:                     delete $accesshash{$entry};
                   2770:                 }
                   2771:             }
                   2772:         } else {
1.811     albertel 2773:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2774:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2775:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2776:                 delete $accesshash{$entry};
                   2777:             }
1.185     www      2778:         }
1.191     harris41 2779:     }
1.352     www      2780: #
                   2781: # Roles
                   2782: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2783: #
1.800     albertel 2784:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2785:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2786: 	    split(/\:/,$entry);
                   2787:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2788:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2789:                 $rudom,$runame) eq 'ok') {
                   2790: 	    delete $userrolehash{$entry};
                   2791:         }
                   2792:     }
1.662     raeburn  2793: #
                   2794: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2795: #
                   2796:     my %domrolebuffer = ();
1.1000    raeburn  2797:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2798:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2799:         if ($domrolebuffer{$rudom}) {
                   2800:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2801:                       '='.&escape($domainrolehash{$entry});
                   2802:         } else {
                   2803:             $domrolebuffer{$rudom}.=&escape($entry).
                   2804:                       '='.&escape($domainrolehash{$entry});
                   2805:         }
                   2806:         delete $domainrolehash{$entry};
                   2807:     }
                   2808:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2809: 	my %servers = &get_servers($dom,'library');
                   2810: 	foreach my $tryserver (keys(%servers)) {
                   2811: 	    unless (&reply('domroleput:'.$dom.':'.
                   2812: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2813: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2814: 	    }
1.662     raeburn  2815:         }
                   2816:     }
1.186     www      2817:     $dumpcount++;
1.157     www      2818: }
                   2819: 
                   2820: sub courselog {
                   2821:     my $what=shift;
1.158     www      2822:     $what=time.':'.$what;
1.620     albertel 2823:     unless ($env{'request.course.id'}) { return ''; }
                   2824:     $coursedombuf{$env{'request.course.id'}}=
                   2825:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2826:     $coursenumbuf{$env{'request.course.id'}}=
                   2827:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2828:     $coursehombuf{$env{'request.course.id'}}=
                   2829:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2830:     $coursedescrbuf{$env{'request.course.id'}}=
                   2831:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2832:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2833:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2834:     $courseownerbuf{$env{'request.course.id'}}=
                   2835:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2836:     $coursetypebuf{$env{'request.course.id'}}=
                   2837:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2838:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2839: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2840:     } else {
1.620     albertel 2841: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2842:     }
1.620     albertel 2843:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2844: 	&flushcourselogs();
                   2845:     }
1.158     www      2846: }
                   2847: 
                   2848: sub courseacclog {
                   2849:     my $fnsymb=shift;
1.620     albertel 2850:     unless ($env{'request.course.id'}) { return ''; }
                   2851:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2852:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2853:         $what.=':POST';
1.583     matthew  2854:         # FIXME: Probably ought to escape things....
1.800     albertel 2855: 	foreach my $key (keys(%env)) {
                   2856:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2857:                 my $formitem = $1;
                   2858:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2859:                     $what.=':'.$formitem.'='.$env{$key};
                   2860:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2861:                     $what.=':'.$formitem.'='.$env{$key};
                   2862:                 }
1.158     www      2863:             }
1.191     harris41 2864:         }
1.583     matthew  2865:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2866:         # FIXME: We should not be depending on a form parameter that someone
                   2867:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2868:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2869:             $what.= ':POST';
                   2870:             # FIXME: Probably ought to escape things....
                   2871:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2872:                                  'crsdiscuss') {
1.620     albertel 2873:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2874:             }
                   2875:         }
1.158     www      2876:     }
                   2877:     &courselog($what);
1.149     www      2878: }
                   2879: 
1.185     www      2880: sub countacc {
                   2881:     my $url=&declutter(shift);
1.458     matthew  2882:     return if (! defined($url) || $url eq '');
1.620     albertel 2883:     unless ($env{'request.course.id'}) { return ''; }
                   2884:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2885:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2886:     $accesshash{$key}++;
1.185     www      2887: }
1.349     www      2888: 
1.361     www      2889: sub linklog {
                   2890:     my ($from,$to)=@_;
                   2891:     $from=&declutter($from);
                   2892:     $to=&declutter($to);
                   2893:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2894:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2895: }
                   2896:   
1.349     www      2897: sub userrolelog {
                   2898:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2899:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2900:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2901:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2902:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2903:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2904:        $userrolehash
                   2905:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2906:                     =$tend.':'.$tstart;
1.662     raeburn  2907:     }
1.898     albertel 2908:     if (($env{'request.role'} =~ /dc\./) &&
                   2909: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2910: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2911: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2912:          ($trole=~/^co/))) {
1.898     albertel 2913:        $userrolehash
                   2914:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2915:                     =$tend.':'.$tstart;
                   2916:     }
1.662     raeburn  2917:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2918:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2919:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2920:         ($trole=~/^sc/)) {
                   2921:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2922:        $domainrolehash
                   2923:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2924:                     = $tend.':'.$tstart;
                   2925:     }
1.351     www      2926: }
                   2927: 
1.957     raeburn  2928: sub courserolelog {
                   2929:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2930:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2931:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2932:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2933:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2934:         ($trole eq 'co')) {
1.957     raeburn  2935:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2936:             my $cdom = $1;
                   2937:             my $cnum = $2;
                   2938:             my $sec = $3;
                   2939:             my $namespace = 'rolelog';
                   2940:             my %storehash = (
                   2941:                                role    => $trole,
                   2942:                                start   => $tstart,
                   2943:                                end     => $tend,
                   2944:                                selfenroll => $selfenroll,
                   2945:                                context    => $context,
                   2946:                             );
                   2947:             if ($trole eq 'gr') {
                   2948:                 $namespace = 'groupslog';
                   2949:                 $storehash{'group'} = $sec;
                   2950:             } else {
                   2951:                 $storehash{'section'} = $sec;
                   2952:             }
                   2953:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2954:             if (($trole ne 'st') || ($sec ne '')) {
                   2955:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2956:             }
1.957     raeburn  2957:         }
                   2958:     }
                   2959:     return;
                   2960: }
                   2961: 
1.351     www      2962: sub get_course_adv_roles {
1.948     raeburn  2963:     my ($cid,$codes) = @_;
1.620     albertel 2964:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2965:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2966:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2967:     my %nothide=();
1.800     albertel 2968:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2969:         if ($user !~ /:/) {
                   2970: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2971:         } else {
                   2972:             $nothide{$user}=1;
                   2973:         }
1.470     www      2974:     }
1.351     www      2975:     my %returnhash=();
                   2976:     my %dumphash=
                   2977:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2978:     my $now=time;
1.997     raeburn  2979:     my %privileged;
1.1000    raeburn  2980:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2981: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2982:         if (($tstart) && ($tstart<0)) { next; }
                   2983:         if (($tend) && ($tend<$now)) { next; }
                   2984:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2985:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2986: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2987:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2988:             my %dompersonnel =
1.998     raeburn  2989:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2990:             $privileged{$domain} = {};
                   2991:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2992:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2993:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2994:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2995:                         $privileged{$udom}{$uname} = 1;
                   2996:                     }
                   2997:                 }
                   2998:             }
                   2999:         }
                   3000:         if ((exists($privileged{$domain}{$username})) && 
                   3001:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3002: 	if ($role eq 'cr') { next; }
1.948     raeburn  3003:         if ($codes) {
                   3004:             if ($section) { $role .= ':'.$section; }
                   3005:             if ($returnhash{$role}) {
                   3006:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3007:             } else {
                   3008:                 $returnhash{$role}=$username.':'.$domain;
                   3009:             }
1.351     www      3010:         } else {
1.988     raeburn  3011:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3012:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3013:             if ($returnhash{$key}) {
                   3014: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3015:             } else {
                   3016:                 $returnhash{$key}=$username.':'.$domain;
                   3017:             }
1.351     www      3018:         }
1.948     raeburn  3019:     }
1.400     www      3020:     return %returnhash;
                   3021: }
                   3022: 
                   3023: sub get_my_roles {
1.937     raeburn  3024:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3025:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3026:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3027:     my (%dumphash,%nothide);
1.858     raeburn  3028:     if ($context eq 'userroles') { 
                   3029:         %dumphash = &dump('roles',$udom,$uname);
                   3030:     } else {
                   3031:         %dumphash=
1.400     www      3032:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3033:         if ($hidepriv) {
                   3034:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3035:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3036:                 if ($user !~ /:/) {
                   3037:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3038:                 } else {
                   3039:                     $nothide{$user} = 1;
                   3040:                 }
                   3041:             }
                   3042:         }
1.858     raeburn  3043:     }
1.400     www      3044:     my %returnhash=();
                   3045:     my $now=time;
1.999     raeburn  3046:     my %privileged;
1.800     albertel 3047:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3048:         my ($role,$tend,$tstart);
                   3049:         if ($context eq 'userroles') {
                   3050: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3051:         } else {
                   3052:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3053:         }
1.400     www      3054:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3055:         my $status = 'active';
1.939     raeburn  3056:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3057:             $status = 'previous';
                   3058:         } 
                   3059:         if (($tstart) && ($now<$tstart)) {
                   3060:             $status = 'future';
                   3061:         }
                   3062:         if (ref($types) eq 'ARRAY') {
                   3063:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3064:                 next;
                   3065:             } 
                   3066:         } else {
                   3067:             if ($status ne 'active') {
                   3068:                 next;
                   3069:             }
                   3070:         }
1.867     raeburn  3071:         my ($rolecode,$username,$domain,$section,$area);
                   3072:         if ($context eq 'userroles') {
                   3073:             ($area,$rolecode) = split(/_/,$entry);
                   3074:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3075:         } else {
                   3076:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3077:         }
1.832     raeburn  3078:         if (ref($roledoms) eq 'ARRAY') {
                   3079:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3080:                 next;
                   3081:             }
                   3082:         }
                   3083:         if (ref($roles) eq 'ARRAY') {
                   3084:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3085:                 if ($role =~ /^cr\//) {
                   3086:                     if (!grep(/^cr$/,@{$roles})) {
                   3087:                         next;
                   3088:                     }
                   3089:                 } else {
                   3090:                     next;
                   3091:                 }
1.832     raeburn  3092:             }
1.867     raeburn  3093:         }
1.937     raeburn  3094:         if ($hidepriv) {
1.999     raeburn  3095:             if ($context eq 'userroles') {
                   3096:                 if ((&privileged($username,$domain)) &&
                   3097:                     (!$nothide{$username.':'.$domain})) {
                   3098:                     next;
                   3099:                 }
                   3100:             } else {
                   3101:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3102:                     my %dompersonnel =
                   3103:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3104:                     $privileged{$domain} = {};
                   3105:                     if (keys(%dompersonnel)) {
                   3106:                         foreach my $server (keys(%dompersonnel)) {
                   3107:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3108:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3109:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3110:                                     $privileged{$udom}{$uname} = $trole;
                   3111:                                 }
                   3112:                             }
                   3113:                         }
                   3114:                     }
                   3115:                 }
                   3116:                 if (exists($privileged{$domain}{$username})) {
                   3117:                     if (!$nothide{$username.':'.$domain}) {
                   3118:                         next;
                   3119:                     }
                   3120:                 }
1.937     raeburn  3121:             }
                   3122:         }
1.933     raeburn  3123:         if ($withsec) {
                   3124:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3125:                 $tstart.':'.$tend;
                   3126:         } else {
                   3127:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3128:         }
1.832     raeburn  3129:     }
1.373     www      3130:     return %returnhash;
1.399     www      3131: }
                   3132: 
                   3133: # ----------------------------------------------------- Frontpage Announcements
                   3134: #
                   3135: #
                   3136: 
                   3137: sub postannounce {
                   3138:     my ($server,$text)=@_;
1.844     albertel 3139:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3140:     unless ($text=~/\w/) { $text=''; }
                   3141:     return &reply('setannounce:'.&escape($text),$server);
                   3142: }
                   3143: 
                   3144: sub getannounce {
1.448     albertel 3145: 
                   3146:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3147: 	my $announcement='';
1.800     albertel 3148: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3149: 	close($fh);
1.399     www      3150: 	if ($announcement=~/\w/) { 
                   3151: 	    return 
                   3152:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3153:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3154: 	} else {
                   3155: 	    return '';
                   3156: 	}
                   3157:     } else {
                   3158: 	return '';
                   3159:     }
1.351     www      3160: }
1.353     www      3161: 
                   3162: # ---------------------------------------------------------- Course ID routines
                   3163: # Deal with domain's nohist_courseid.db files
                   3164: #
                   3165: 
                   3166: sub courseidput {
1.921     raeburn  3167:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3168:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3169:     my $outcome;
                   3170:     if ($caller eq 'timeonly') {
                   3171:         my $cids = '';
                   3172:         foreach my $item (keys(%$storehash)) {
                   3173:             $cids.=&escape($item).'&';
                   3174:         }
                   3175:         $cids=~s/\&$//;
                   3176:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3177:                           $coursehome);       
                   3178:     } else {
                   3179:         my $items = '';
                   3180:         foreach my $item (keys(%$storehash)) {
                   3181:             $items.= &escape($item).'='.
                   3182:                      &freeze_escape($$storehash{$item}).'&';
                   3183:         }
                   3184:         $items=~s/\&$//;
                   3185:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3186:                           $coursehome);
1.918     raeburn  3187:     }
                   3188:     if ($outcome eq 'unknown_cmd') {
                   3189:         my $what;
                   3190:         foreach my $cid (keys(%$storehash)) {
                   3191:             $what .= &escape($cid).'=';
1.921     raeburn  3192:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3193:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3194:             }
                   3195:             $what =~ s/\:$/&/;
                   3196:         }
                   3197:         $what =~ s/\&$//;  
                   3198:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3199:     } else {
                   3200:         return $outcome;
                   3201:     }
1.353     www      3202: }
                   3203: 
                   3204: sub courseiddump {
1.921     raeburn  3205:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3206:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3207:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3208:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3209:     my $as_hash = 1;
                   3210:     my %returnhash;
                   3211:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3212:     my %libserv = &all_library();
                   3213:     foreach my $tryserver (keys(%libserv)) {
                   3214:         if ( (  $hostidflag == 1 
                   3215: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3216: 	     || (!defined($hostidflag)) ) {
                   3217: 
1.918     raeburn  3218: 	    if (($domfilter eq '') ||
                   3219: 		(&host_domain($tryserver) eq $domfilter)) {
                   3220:                 my $rep = 
                   3221:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3222:                          $sincefilter.':'.&escape($descfilter).':'.
                   3223:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3224:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3225:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3226:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3227:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3228:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3229:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3230:                          &escape($creationcontext).':'.$domcloner,
                   3231:                          $tryserver);
1.918     raeburn  3232:                 my @pairs=split(/\&/,$rep);
                   3233:                 foreach my $item (@pairs) {
                   3234:                     my ($key,$value)=split(/\=/,$item,2);
                   3235:                     $key = &unescape($key);
                   3236:                     next if ($key =~ /^error: 2 /);
                   3237:                     my $result = &thaw_unescape($value);
                   3238:                     if (ref($result) eq 'HASH') {
                   3239:                         $returnhash{$key}=$result;
                   3240:                     } else {
1.921     raeburn  3241:                         my @responses = split(/:/,$value);
                   3242:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3243:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3244:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3245:                         }
1.1008    raeburn  3246:                     }
1.353     www      3247:                 }
                   3248:             }
                   3249:         }
                   3250:     }
                   3251:     return %returnhash;
                   3252: }
                   3253: 
1.1055    raeburn  3254: sub courselastaccess {
                   3255:     my ($cdom,$cnum,$hostidref) = @_;
                   3256:     my %returnhash;
                   3257:     if ($cdom && $cnum) {
                   3258:         my $chome = &homeserver($cnum,$cdom);
                   3259:         if ($chome ne 'no_host') {
                   3260:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3261:             &extract_lastaccess(\%returnhash,$rep);
                   3262:         }
                   3263:     } else {
                   3264:         if (!$cdom) { $cdom=''; }
                   3265:         my %libserv = &all_library();
                   3266:         foreach my $tryserver (keys(%libserv)) {
                   3267:             if (ref($hostidref) eq 'ARRAY') {
                   3268:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3269:             } 
                   3270:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3271:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3272:                 &extract_lastaccess(\%returnhash,$rep);
                   3273:             }
                   3274:         }
                   3275:     }
                   3276:     return %returnhash;
                   3277: }
                   3278: 
                   3279: sub extract_lastaccess {
                   3280:     my ($returnhash,$rep) = @_;
                   3281:     if (ref($returnhash) eq 'HASH') {
                   3282:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3283:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3284:                  $rep eq '') {
                   3285:             my @pairs=split(/\&/,$rep);
                   3286:             foreach my $item (@pairs) {
                   3287:                 my ($key,$value)=split(/\=/,$item,2);
                   3288:                 $key = &unescape($key);
                   3289:                 next if ($key =~ /^error: 2 /);
                   3290:                 $returnhash->{$key} = &thaw_unescape($value);
                   3291:             }
                   3292:         }
                   3293:     }
                   3294:     return;
                   3295: }
                   3296: 
1.658     raeburn  3297: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3298: 
                   3299: sub dcmailput {
1.685     raeburn  3300:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3301:     my $status = &Apache::lonnet::critical(
1.740     www      3302:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3303:        &escape($message),$server);
1.662     raeburn  3304:     return $status;
                   3305: }
                   3306: 
1.658     raeburn  3307: sub dcmaildump {
                   3308:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3309:     my %returnhash=();
1.846     albertel 3310: 
                   3311:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3312:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3313:                                                          &escape($enddate).':';
                   3314: 	my @esc_senders=map { &escape($_)} @$senders;
                   3315: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3316: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3317:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3318:             if (($key) && ($value)) {
                   3319:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3320:             }
                   3321:         }
                   3322:     }
                   3323:     return %returnhash;
                   3324: }
1.662     raeburn  3325: # ---------------------------------------------------------- Domain roles
                   3326: 
                   3327: sub get_domain_roles {
                   3328:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3329:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3330:         $startdate = '.';
                   3331:     }
1.1018    raeburn  3332:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3333:         $enddate = '.';
                   3334:     }
1.922     raeburn  3335:     my $rolelist;
                   3336:     if (ref($roles) eq 'ARRAY') {
                   3337:         $rolelist = join(':',@{$roles});
                   3338:     }
1.662     raeburn  3339:     my %personnel = ();
1.841     albertel 3340: 
                   3341:     my %servers = &get_servers($dom,'library');
                   3342:     foreach my $tryserver (keys(%servers)) {
                   3343: 	%{$personnel{$tryserver}}=();
                   3344: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3345: 					    &escape($startdate).':'.
                   3346: 					    &escape($enddate).':'.
                   3347: 					    &escape($rolelist), $tryserver))) {
                   3348: 	    my ($key,$value) = split(/\=/,$line,2);
                   3349: 	    if (($key) && ($value)) {
                   3350: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3351: 	    }
                   3352: 	}
1.662     raeburn  3353:     }
                   3354:     return %personnel;
                   3355: }
1.658     raeburn  3356: 
1.149     www      3357: # ----------------------------------------------------------- Check out an item
                   3358: 
1.504     albertel 3359: sub get_first_access {
                   3360:     my ($type,$argsymb)=@_;
1.790     albertel 3361:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3362:     if ($argsymb) { $symb=$argsymb; }
                   3363:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3364:     if ($type eq 'course') {
                   3365: 	$res='course';
                   3366:     } elsif ($type eq 'map') {
1.588     albertel 3367: 	$res=&symbread($map);
                   3368:     } else {
                   3369: 	$res=$symb;
                   3370:     }
                   3371:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3372:     return $times{"$courseid\0$res"};
1.504     albertel 3373: }
                   3374: 
                   3375: sub set_first_access {
                   3376:     my ($type)=@_;
1.790     albertel 3377:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3378:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3379:     if ($type eq 'course') {
                   3380: 	$res='course';
                   3381:     } elsif ($type eq 'map') {
1.588     albertel 3382: 	$res=&symbread($map);
                   3383:     } else {
                   3384: 	$res=$symb;
                   3385:     }
                   3386:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3387:     if (!$firstaccess) {
1.588     albertel 3388: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3389:     }
                   3390:     return 'already_set';
1.504     albertel 3391: }
                   3392: 
1.149     www      3393: sub checkout {
                   3394:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3395:     my $now=time;
                   3396:     my $lonhost=$perlvar{'lonHostID'};
                   3397:     my $infostr=&escape(
1.234     www      3398:                  'CHECKOUTTOKEN&'.
1.149     www      3399:                  $tuname.'&'.
                   3400:                  $tudom.'&'.
                   3401:                  $tcrsid.'&'.
                   3402:                  $symb.'&'.
                   3403: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3404:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3405:     if ($token=~/^error\:/) { 
1.672     albertel 3406:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3407:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3408:                  "</font>");
                   3409:         return ''; 
                   3410:     }
                   3411: 
1.149     www      3412:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3413:     $token=~tr/a-z/A-Z/;
                   3414: 
1.153     www      3415:     my %infohash=('resource.0.outtoken' => $token,
                   3416:                   'resource.0.checkouttime' => $now,
                   3417:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3418: 
                   3419:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3420:        return '';
1.151     www      3421:     } else {
1.672     albertel 3422:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3423:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3424:                  "</font>");
1.149     www      3425:     }    
                   3426: 
                   3427:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3428:                          &escape('Checkout '.$infostr.' - '.
                   3429:                                                  $token)) ne 'ok') {
                   3430: 	return '';
1.151     www      3431:     } else {
1.672     albertel 3432:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3433:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3434:                  "</font>");
1.149     www      3435:     }
1.151     www      3436:     return $token;
1.149     www      3437: }
                   3438: 
                   3439: # ------------------------------------------------------------ Check in an item
                   3440: 
                   3441: sub checkin {
                   3442:     my $token=shift;
1.150     www      3443:     my $now=time;
                   3444:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3445:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3446:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3447:     $dtoken=~s/\W/\_/g;
1.234     www      3448:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3449:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3450: 
1.154     www      3451:     unless (($tuname) && ($tudom)) {
                   3452:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3453:         return '';
                   3454:     }
                   3455:     
                   3456:     unless (&allowed('mgr',$tcrsid)) {
                   3457:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3458:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3459:         return '';
                   3460:     }
                   3461: 
1.153     www      3462:     my %infohash=('resource.0.intoken' => $token,
                   3463:                   'resource.0.checkintime' => $now,
                   3464:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3465: 
                   3466:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3467:        return '';
                   3468:     }    
                   3469: 
                   3470:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3471:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3472: 	return '';
                   3473:     }
                   3474: 
                   3475:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3476: }
                   3477: 
                   3478: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3479: 
                   3480: sub expirespread {
                   3481:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3482:     my $cid=$env{'request.course.id'}; 
1.110     www      3483:     if ($cid) {
                   3484:        my $now=time;
                   3485:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3486:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3487:                             $env{'course.'.$cid.'.num'}.
1.110     www      3488: 	        	    ':nohist_expirationdates:'.
                   3489:                             &escape($key).'='.$now,
1.620     albertel 3490:                             $env{'course.'.$cid.'.home'})
1.110     www      3491:     }
                   3492:     return 'ok';
1.14      www      3493: }
                   3494: 
1.109     www      3495: # ----------------------------------------------------- Devalidate Spreadsheets
                   3496: 
                   3497: sub devalidate {
1.325     www      3498:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3499:     my $cid=$env{'request.course.id'}; 
1.109     www      3500:     if ($cid) {
1.391     matthew  3501:         # delete the stored spreadsheets for
                   3502:         # - the student level sheet of this user in course's homespace
                   3503:         # - the assessment level sheet for this resource 
                   3504:         #   for this user in user's homespace
1.553     albertel 3505: 	# - current conditional state info
1.325     www      3506: 	my $key=$uname.':'.$udom.':';
1.109     www      3507:         my $status=
1.299     matthew  3508: 	    &del('nohist_calculatedsheets',
1.391     matthew  3509: 		 [$key.'studentcalc:'],
1.620     albertel 3510: 		 $env{'course.'.$cid.'.domain'},
                   3511: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3512: 		.' '.
                   3513: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3514: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3515:         unless ($status eq 'ok ok') {
                   3516:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3517:                     $uname.' at '.$udom.' for '.
1.109     www      3518: 		    $symb.': '.$status);
1.133     albertel 3519:         }
1.553     albertel 3520: 	&delenv('user.state.'.$cid);
1.109     www      3521:     }
                   3522: }
                   3523: 
1.265     albertel 3524: sub get_scalar {
                   3525:     my ($string,$end) = @_;
                   3526:     my $value;
                   3527:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3528: 	$value = $1;
                   3529:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3530: 	$value = $1;
                   3531:     }
                   3532:     return &unescape($value);
                   3533: }
                   3534: 
                   3535: sub array2str {
                   3536:   my (@array) = @_;
                   3537:   my $result=&arrayref2str(\@array);
                   3538:   $result=~s/^__ARRAY_REF__//;
                   3539:   $result=~s/__END_ARRAY_REF__$//;
                   3540:   return $result;
                   3541: }
                   3542: 
1.204     albertel 3543: sub arrayref2str {
                   3544:   my ($arrayref) = @_;
1.265     albertel 3545:   my $result='__ARRAY_REF__';
1.204     albertel 3546:   foreach my $elem (@$arrayref) {
1.265     albertel 3547:     if(ref($elem) eq 'ARRAY') {
                   3548:       $result.=&arrayref2str($elem).'&';
                   3549:     } elsif(ref($elem) eq 'HASH') {
                   3550:       $result.=&hashref2str($elem).'&';
                   3551:     } elsif(ref($elem)) {
                   3552:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3553:     } else {
                   3554:       $result.=&escape($elem).'&';
                   3555:     }
                   3556:   }
                   3557:   $result=~s/\&$//;
1.265     albertel 3558:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3559:   return $result;
                   3560: }
                   3561: 
1.168     albertel 3562: sub hash2str {
1.204     albertel 3563:   my (%hash) = @_;
                   3564:   my $result=&hashref2str(\%hash);
1.265     albertel 3565:   $result=~s/^__HASH_REF__//;
                   3566:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3567:   return $result;
                   3568: }
                   3569: 
                   3570: sub hashref2str {
                   3571:   my ($hashref)=@_;
1.265     albertel 3572:   my $result='__HASH_REF__';
1.800     albertel 3573:   foreach my $key (sort(keys(%$hashref))) {
                   3574:     if (ref($key) eq 'ARRAY') {
                   3575:       $result.=&arrayref2str($key).'=';
                   3576:     } elsif (ref($key) eq 'HASH') {
                   3577:       $result.=&hashref2str($key).'=';
                   3578:     } elsif (ref($key)) {
1.265     albertel 3579:       $result.='=';
1.800     albertel 3580:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3581:     } else {
1.800     albertel 3582: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3583:     }
                   3584: 
1.800     albertel 3585:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3586:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3587:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3588:       $result.=&hashref2str($hashref->{$key}).'&';
                   3589:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3590:        $result.='&';
1.800     albertel 3591:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3592:     } else {
1.800     albertel 3593:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3594:     }
                   3595:   }
1.168     albertel 3596:   $result=~s/\&$//;
1.265     albertel 3597:   $result .= '__END_HASH_REF__';
1.168     albertel 3598:   return $result;
                   3599: }
                   3600: 
                   3601: sub str2hash {
1.265     albertel 3602:     my ($string)=@_;
                   3603:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3604:     return %$hash;
                   3605: }
                   3606: 
                   3607: sub str2hashref {
1.168     albertel 3608:   my ($string) = @_;
1.265     albertel 3609: 
                   3610:   my %hash;
                   3611: 
                   3612:   if($string !~ /^__HASH_REF__/) {
                   3613:       if (! ($string eq '' || !defined($string))) {
                   3614: 	  $hash{'error'}='Not hash reference';
                   3615:       }
                   3616:       return (\%hash, $string);
                   3617:   }
                   3618: 
                   3619:   $string =~ s/^__HASH_REF__//;
                   3620: 
                   3621:   while($string !~ /^__END_HASH_REF__/) {
                   3622:       #key
                   3623:       my $key='';
                   3624:       if($string =~ /^__HASH_REF__/) {
                   3625:           ($key, $string)=&str2hashref($string);
                   3626:           if(defined($key->{'error'})) {
                   3627:               $hash{'error'}='Bad data';
                   3628:               return (\%hash, $string);
                   3629:           }
                   3630:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3631:           ($key, $string)=&str2arrayref($string);
                   3632:           if($key->[0] eq 'Array reference error') {
                   3633:               $hash{'error'}='Bad data';
                   3634:               return (\%hash, $string);
                   3635:           }
                   3636:       } else {
                   3637:           $string =~ s/^(.*?)=//;
1.267     albertel 3638: 	  $key=&unescape($1);
1.265     albertel 3639:       }
                   3640:       $string =~ s/^=//;
                   3641: 
                   3642:       #value
                   3643:       my $value='';
                   3644:       if($string =~ /^__HASH_REF__/) {
                   3645:           ($value, $string)=&str2hashref($string);
                   3646:           if(defined($value->{'error'})) {
                   3647:               $hash{'error'}='Bad data';
                   3648:               return (\%hash, $string);
                   3649:           }
                   3650:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3651:           ($value, $string)=&str2arrayref($string);
                   3652:           if($value->[0] eq 'Array reference error') {
                   3653:               $hash{'error'}='Bad data';
                   3654:               return (\%hash, $string);
                   3655:           }
                   3656:       } else {
                   3657: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3658:       }
                   3659:       $string =~ s/^&//;
                   3660: 
                   3661:       $hash{$key}=$value;
1.204     albertel 3662:   }
1.265     albertel 3663: 
                   3664:   $string =~ s/^__END_HASH_REF__//;
                   3665: 
                   3666:   return (\%hash, $string);
1.204     albertel 3667: }
                   3668: 
                   3669: sub str2array {
1.265     albertel 3670:     my ($string)=@_;
                   3671:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3672:     return @$array;
                   3673: }
                   3674: 
                   3675: sub str2arrayref {
1.204     albertel 3676:   my ($string) = @_;
1.265     albertel 3677:   my @array;
                   3678: 
                   3679:   if($string !~ /^__ARRAY_REF__/) {
                   3680:       if (! ($string eq '' || !defined($string))) {
                   3681: 	  $array[0]='Array reference error';
                   3682:       }
                   3683:       return (\@array, $string);
                   3684:   }
                   3685: 
                   3686:   $string =~ s/^__ARRAY_REF__//;
                   3687: 
                   3688:   while($string !~ /^__END_ARRAY_REF__/) {
                   3689:       my $value='';
                   3690:       if($string =~ /^__HASH_REF__/) {
                   3691:           ($value, $string)=&str2hashref($string);
                   3692:           if(defined($value->{'error'})) {
                   3693:               $array[0] ='Array reference error';
                   3694:               return (\@array, $string);
                   3695:           }
                   3696:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3697:           ($value, $string)=&str2arrayref($string);
                   3698:           if($value->[0] eq 'Array reference error') {
                   3699:               $array[0] ='Array reference error';
                   3700:               return (\@array, $string);
                   3701:           }
                   3702:       } else {
                   3703: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3704:       }
                   3705:       $string =~ s/^&//;
                   3706: 
                   3707:       push(@array, $value);
1.191     harris41 3708:   }
1.265     albertel 3709: 
                   3710:   $string =~ s/^__END_ARRAY_REF__//;
                   3711: 
                   3712:   return (\@array, $string);
1.168     albertel 3713: }
                   3714: 
1.167     albertel 3715: # -------------------------------------------------------------------Temp Store
                   3716: 
1.168     albertel 3717: sub tmpreset {
                   3718:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3719:   if (!$symb) {
                   3720:     $symb=&symbread();
1.620     albertel 3721:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3722:   }
                   3723:   $symb=escape($symb);
                   3724: 
1.620     albertel 3725:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3726:   $namespace=~s/\//\_/g;
                   3727:   $namespace=~s/\W//g;
                   3728: 
1.620     albertel 3729:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3730:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3731:   if ($domain eq 'public' && $stuname eq 'public') {
                   3732:       $stuname=$ENV{'REMOTE_ADDR'};
                   3733:   }
1.168     albertel 3734:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3735:   my %hash;
                   3736:   if (tie(%hash,'GDBM_File',
                   3737: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3738: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3739:     foreach my $key (keys(%hash)) {
1.180     albertel 3740:       if ($key=~ /:$symb/) {
1.168     albertel 3741: 	delete($hash{$key});
                   3742:       }
                   3743:     }
                   3744:   }
                   3745: }
                   3746: 
1.167     albertel 3747: sub tmpstore {
1.168     albertel 3748:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3749: 
                   3750:   if (!$symb) {
                   3751:     $symb=&symbread();
1.620     albertel 3752:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3753:   }
                   3754:   $symb=escape($symb);
                   3755: 
                   3756:   if (!$namespace) {
                   3757:     # I don't think we would ever want to store this for a course.
                   3758:     # it seems this will only be used if we don't have a course.
1.620     albertel 3759:     #$namespace=$env{'request.course.id'};
1.168     albertel 3760:     #if (!$namespace) {
1.620     albertel 3761:       $namespace=$env{'request.state'};
1.168     albertel 3762:     #}
                   3763:   }
                   3764:   $namespace=~s/\//\_/g;
                   3765:   $namespace=~s/\W//g;
1.620     albertel 3766:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3767:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3768:   if ($domain eq 'public' && $stuname eq 'public') {
                   3769:       $stuname=$ENV{'REMOTE_ADDR'};
                   3770:   }
1.168     albertel 3771:   my $now=time;
                   3772:   my %hash;
                   3773:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3774:   if (tie(%hash,'GDBM_File',
                   3775: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3776: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3777:     $hash{"version:$symb"}++;
                   3778:     my $version=$hash{"version:$symb"};
                   3779:     my $allkeys=''; 
                   3780:     foreach my $key (keys(%$storehash)) {
                   3781:       $allkeys.=$key.':';
1.591     albertel 3782:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3783:     }
                   3784:     $hash{"$version:$symb:timestamp"}=$now;
                   3785:     $allkeys.='timestamp';
                   3786:     $hash{"$version:keys:$symb"}=$allkeys;
                   3787:     if (untie(%hash)) {
                   3788:       return 'ok';
                   3789:     } else {
                   3790:       return "error:$!";
                   3791:     }
                   3792:   } else {
                   3793:     return "error:$!";
                   3794:   }
                   3795: }
1.167     albertel 3796: 
1.168     albertel 3797: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3798: 
1.168     albertel 3799: sub tmprestore {
                   3800:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3801: 
1.168     albertel 3802:   if (!$symb) {
                   3803:     $symb=&symbread();
1.620     albertel 3804:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3805:   }
                   3806:   $symb=escape($symb);
                   3807: 
1.620     albertel 3808:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3809: 
1.620     albertel 3810:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3811:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3812:   if ($domain eq 'public' && $stuname eq 'public') {
                   3813:       $stuname=$ENV{'REMOTE_ADDR'};
                   3814:   }
1.168     albertel 3815:   my %returnhash;
                   3816:   $namespace=~s/\//\_/g;
                   3817:   $namespace=~s/\W//g;
                   3818:   my %hash;
                   3819:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3820:   if (tie(%hash,'GDBM_File',
                   3821: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3822: 	  &GDBM_READER(),0640)) {
1.168     albertel 3823:     my $version=$hash{"version:$symb"};
                   3824:     $returnhash{'version'}=$version;
                   3825:     my $scope;
                   3826:     for ($scope=1;$scope<=$version;$scope++) {
                   3827:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3828:       my @keys=split(/:/,$vkeys);
                   3829:       my $key;
                   3830:       $returnhash{"$scope:keys"}=$vkeys;
                   3831:       foreach $key (@keys) {
1.591     albertel 3832: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3833: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3834:       }
                   3835:     }
1.168     albertel 3836:     if (!(untie(%hash))) {
                   3837:       return "error:$!";
                   3838:     }
                   3839:   } else {
                   3840:     return "error:$!";
                   3841:   }
                   3842:   return %returnhash;
1.167     albertel 3843: }
                   3844: 
1.9       www      3845: # ----------------------------------------------------------------------- Store
                   3846: 
                   3847: sub store {
1.124     www      3848:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3849:     my $home='';
                   3850: 
1.168     albertel 3851:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3852: 
1.213     www      3853:     $symb=&symbclean($symb);
1.122     albertel 3854:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3855: 
1.620     albertel 3856:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3857:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3858: 
                   3859:     &devalidate($symb,$stuname,$domain);
1.109     www      3860: 
                   3861:     $symb=escape($symb);
1.187     www      3862:     if (!$namespace) { 
1.620     albertel 3863:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3864:           return ''; 
                   3865:        } 
                   3866:     }
1.620     albertel 3867:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3868: 
                   3869:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3870:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3871: 
1.12      www      3872:     my $namevalue='';
1.800     albertel 3873:     foreach my $key (keys(%$storehash)) {
                   3874:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3875:     }
1.12      www      3876:     $namevalue=~s/\&$//;
1.187     www      3877:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3878:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3879: }
                   3880: 
1.47      www      3881: # -------------------------------------------------------------- Critical Store
                   3882: 
                   3883: sub cstore {
1.124     www      3884:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3885:     my $home='';
                   3886: 
1.168     albertel 3887:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3888: 
1.213     www      3889:     $symb=&symbclean($symb);
1.122     albertel 3890:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3891: 
1.620     albertel 3892:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3893:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3894: 
                   3895:     &devalidate($symb,$stuname,$domain);
1.109     www      3896: 
                   3897:     $symb=escape($symb);
1.187     www      3898:     if (!$namespace) { 
1.620     albertel 3899:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3900:           return ''; 
                   3901:        } 
                   3902:     }
1.620     albertel 3903:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3904: 
                   3905:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3906:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3907: 
1.47      www      3908:     my $namevalue='';
1.800     albertel 3909:     foreach my $key (keys(%$storehash)) {
                   3910:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3911:     }
1.47      www      3912:     $namevalue=~s/\&$//;
1.187     www      3913:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3914:     return critical
                   3915:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3916: }
                   3917: 
1.9       www      3918: # --------------------------------------------------------------------- Restore
                   3919: 
                   3920: sub restore {
1.124     www      3921:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3922:     my $home='';
                   3923: 
1.168     albertel 3924:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3925: 
1.122     albertel 3926:     if (!$symb) {
                   3927:       unless ($symb=escape(&symbread())) { return ''; }
                   3928:     } else {
1.213     www      3929:       $symb=&escape(&symbclean($symb));
1.122     albertel 3930:     }
1.188     www      3931:     if (!$namespace) { 
1.620     albertel 3932:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3933:           return ''; 
                   3934:        } 
                   3935:     }
1.620     albertel 3936:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3937:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3938:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3939:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3940: 
1.12      www      3941:     my %returnhash=();
1.800     albertel 3942:     foreach my $line (split(/\&/,$answer)) {
                   3943: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3944:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3945:     }
1.75      www      3946:     my $version;
                   3947:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3948:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3949:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3950:        }
1.75      www      3951:     }
1.13      www      3952:     return %returnhash;
1.34      www      3953: }
                   3954: 
                   3955: # ---------------------------------------------------------- Course Description
                   3956: 
                   3957: sub coursedescription {
1.731     albertel 3958:     my ($courseid,$args)=@_;
1.34      www      3959:     $courseid=~s/^\///;
1.49      www      3960:     $courseid=~s/\_/\//g;
1.34      www      3961:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3962:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3963:     my $normalid=$cdomain.'_'.$cnum;
                   3964:     # need to always cache even if we get errors otherwise we keep 
                   3965:     # trying and trying and trying to get the course description.
                   3966:     my %envhash=();
                   3967:     my %returnhash=();
1.731     albertel 3968:     
                   3969:     my $expiretime=600;
                   3970:     if ($env{'request.course.id'} eq $normalid) {
                   3971: 	$expiretime=120;
                   3972:     }
                   3973: 
                   3974:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3975:     if (!$args->{'freshen_cache'}
                   3976: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3977: 	foreach my $key (keys(%env)) {
                   3978: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3979: 	    my ($setting) = $1;
                   3980: 	    $returnhash{$setting} = $env{$key};
                   3981: 	}
                   3982: 	return %returnhash;
                   3983:     }
                   3984: 
                   3985:     # get the data agin
                   3986:     if (!$args->{'one_time'}) {
                   3987: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3988:     }
1.811     albertel 3989: 
1.34      www      3990:     if ($chome ne 'no_host') {
1.302     albertel 3991:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3992:        if (!exists($returnhash{'con_lost'})) {
                   3993:            $returnhash{'home'}= $chome;
                   3994: 	   $returnhash{'domain'} = $cdomain;
                   3995: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3996:            if (!defined($returnhash{'type'})) {
                   3997:                $returnhash{'type'} = 'Course';
                   3998:            }
1.130     albertel 3999:            while (my ($name,$value) = each %returnhash) {
1.53      www      4000:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4001:            }
1.270     www      4002:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4003:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4004: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4005:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4006:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4007:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4008:        }
                   4009:     }
1.731     albertel 4010:     if (!$args->{'one_time'}) {
1.949     raeburn  4011: 	&appenv(\%envhash);
1.731     albertel 4012:     }
1.302     albertel 4013:     return %returnhash;
1.461     www      4014: }
                   4015: 
1.1056.4.5! raeburn  4016: sub update_released_required {
        !          4017:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
        !          4018:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
        !          4019:         $cid = $env{'request.course.id'};
        !          4020:         $cdom = $env{'course.'.$cid.'.domain'};
        !          4021:         $cnum = $env{'course.'.$cid.'.num'};
        !          4022:         $chome = $env{'course.'.$cid.'.home'};
        !          4023:     }
        !          4024:     if ($needsrelease) {
        !          4025:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
        !          4026:         my $needsupdate;
        !          4027:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
        !          4028:             $needsupdate = 1;
        !          4029:         } else {
        !          4030:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
        !          4031:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
        !          4032:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
        !          4033:                 $needsupdate = 1;
        !          4034:             }
        !          4035:         }
        !          4036:         if ($needsupdate) {
        !          4037:             my %needshash = (
        !          4038:                              'internal.releaserequired' => $needsrelease,
        !          4039:                             );
        !          4040:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
        !          4041:             if ($putresult eq 'ok') {
        !          4042:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
        !          4043:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
        !          4044:                 if (ref($crsinfo{$cid}) eq 'HASH') {
        !          4045:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
        !          4046:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
        !          4047:                 }
        !          4048:             }
        !          4049:         }
        !          4050:     }
        !          4051:     return;
        !          4052: }
        !          4053: 
1.461     www      4054: # -------------------------------------------------See if a user is privileged
                   4055: 
                   4056: sub privileged {
                   4057:     my ($username,$domain)=@_;
                   4058:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4059: 			&homeserver($username,$domain));
1.1033    raeburn  4060:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4061:         ($rolesdump =~ /^error:/)) {
                   4062:         return 0;
                   4063:     }
1.461     www      4064:     my $now=time;
                   4065:     if ($rolesdump ne '') {
1.800     albertel 4066:         foreach my $entry (split(/&/,$rolesdump)) {
                   4067: 	    if ($entry!~/^rolesdef_/) {
                   4068: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4069: 		$area=~s/\_\w\w$//;
                   4070: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4071: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4072: 		    my $active=1;
                   4073: 		    if ($tend) {
                   4074: 			if ($tend<$now) { $active=0; }
                   4075: 		    }
                   4076: 		    if ($tstart) {
                   4077: 			if ($tstart>$now) { $active=0; }
                   4078: 		    }
                   4079: 		    if ($active) { return 1; }
                   4080: 		}
                   4081: 	    }
                   4082: 	}
                   4083:     }
                   4084:     return 0;
1.9       www      4085: }
1.1       albertel 4086: 
1.103     harris41 4087: # -------------------------------------------------------- Get user privileges
1.11      www      4088: 
                   4089: sub rolesinit {
                   4090:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4091:     my $now=time;
                   4092:     my %userroles = ('user.login.time' => $now);
1.1056.4.3  raeburn  4093:     my $extra = &freeze_escape({'clientcheckrole' => 1});
                   4094:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4095:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4096:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4097:         return \%userroles;
                   4098:     }
1.11      www      4099:     my %allroles=();
1.678     raeburn  4100:     my %allgroups=();   
                   4101:     my $group_privs;
1.11      www      4102: 
                   4103:     if ($rolesdump ne '') {
1.800     albertel 4104:         foreach my $entry (split(/&/,$rolesdump)) {
                   4105: 	  if ($entry!~/^rolesdef_/) {
                   4106:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4107: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4108:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4109: 	    if ($role=~/^cr/) { 
1.807     albertel 4110: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4111: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4112: 		    ($tend,$tstart)=split('_',$trest);
                   4113: 		} else {
                   4114: 		    $trole=$role;
                   4115: 		}
1.678     raeburn  4116:             } elsif ($role =~ m|^gr/|) {
                   4117:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4118:                 ($trole,$group_privs) = split(/\//,$trole);
                   4119:                 $group_privs = &unescape($group_privs);
1.587     albertel 4120: 	    } else {
                   4121: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4122: 	    }
1.743     albertel 4123: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4124: 					 $username);
                   4125: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4126:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4127:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4128:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4129: 		my $spec=$trole.'.'.$area;
                   4130: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4131: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4132:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4133:                 } elsif ($trole eq 'gr') {
                   4134:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4135: 		} else {
1.567     raeburn  4136:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4137: 		}
1.12      www      4138:             }
1.662     raeburn  4139:           }
1.191     harris41 4140:         }
1.743     albertel 4141:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4142:         $userroles{'user.adv'}    = $adv;
                   4143: 	$userroles{'user.author'} = $author;
1.620     albertel 4144:         $env{'user.adv'}=$adv;
1.11      www      4145:     }
1.743     albertel 4146:     return \%userroles;  
1.11      www      4147: }
                   4148: 
1.567     raeburn  4149: sub set_arearole {
                   4150:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4151: # log the associated role with the area
                   4152:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4153:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4154: }
                   4155: 
                   4156: sub custom_roleprivs {
                   4157:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4158:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4159:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4160:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4161:         my ($rdummy,$roledef)=
                   4162:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4163:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4164:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4165:             if (defined($syspriv)) {
1.1043    raeburn  4166:                 if ($trest =~ /^$match_community$/) {
                   4167:                     $syspriv =~ s/bre\&S//; 
                   4168:                 }
1.567     raeburn  4169:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4170:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4171:             }
                   4172:             if ($tdomain ne '') {
                   4173:                 if (defined($dompriv)) {
                   4174:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4175:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4176:                 }
                   4177:                 if (($trest ne '') && (defined($coursepriv))) {
                   4178:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4179:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4180:                 }
                   4181:             }
                   4182:         }
                   4183:     }
                   4184: }
                   4185: 
1.678     raeburn  4186: sub group_roleprivs {
                   4187:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4188:     my $access = 1;
                   4189:     my $now = time;
                   4190:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4191:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4192:     if ($access) {
1.811     albertel 4193:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4194:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4195:     }
                   4196: }
1.567     raeburn  4197: 
                   4198: sub standard_roleprivs {
                   4199:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4200:     if (defined($pr{$trole.':s'})) {
                   4201:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4202:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4203:     }
                   4204:     if ($tdomain ne '') {
                   4205:         if (defined($pr{$trole.':d'})) {
                   4206:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4207:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4208:         }
                   4209:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4210:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4211:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4212:         }
                   4213:     }
                   4214: }
                   4215: 
                   4216: sub set_userprivs {
1.1056.4.2  raeburn  4217:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4218:     my $author=0;
                   4219:     my $adv=0;
1.678     raeburn  4220:     my %grouproles = ();
                   4221:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4222:         my @groupkeys;
1.1000    raeburn  4223:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4224:             push(@groupkeys,$role);
                   4225:         }
                   4226:         if (ref($groups_roles) eq 'HASH') {
                   4227:             foreach my $key (keys(%{$groups_roles})) {
                   4228:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4229:                     push(@groupkeys,$key);
                   4230:                 }
                   4231:             }
                   4232:         }
                   4233:         if (@groupkeys > 0) {
                   4234:             foreach my $role (@groupkeys) {
                   4235:                 my ($trole,$area,$sec,$extendedarea);
                   4236:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4237:                     $trole = $1;
                   4238:                     $area = $2;
                   4239:                     $sec = $3;
                   4240:                     $extendedarea = $area.$sec;
                   4241:                     if (exists($$allgroups{$area})) {
                   4242:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4243:                             my $spec = $trole.'.'.$extendedarea;
                   4244:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4245:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4246:                         }
1.678     raeburn  4247:                     }
                   4248:                 }
                   4249:             }
                   4250:         }
                   4251:     }
1.800     albertel 4252:     foreach my $group (keys(%grouproles)) {
                   4253:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4254:     }
1.800     albertel 4255:     foreach my $role (keys(%{$allroles})) {
                   4256:         my %thesepriv;
1.941     raeburn  4257:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4258:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4259:             if ($item ne '') {
                   4260:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4261:                 if ($restrictions eq '') {
                   4262:                     $thesepriv{$privilege}='F';
                   4263:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4264:                     $thesepriv{$privilege}.=$restrictions;
                   4265:                 }
                   4266:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4267:             }
                   4268:         }
                   4269:         my $thesestr='';
1.800     albertel 4270:         foreach my $priv (keys(%thesepriv)) {
                   4271: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4272: 	}
                   4273:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4274:     }
                   4275:     return ($author,$adv);
                   4276: }
                   4277: 
1.994     raeburn  4278: sub role_status {
1.1002    raeburn  4279:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4280:     my @pwhere = ();
                   4281:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4282:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4283:         unless (!defined($$role) || $$role eq '') {
                   4284:             $$where=join('.',@pwhere);
                   4285:             $$trolecode=$$role.'.'.$$where;
                   4286:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4287:             $$tstatus='is';
                   4288:             if ($$tstart && $$tstart>$then) {
                   4289:                 $$tstatus='future';
1.1034    raeburn  4290:                 if ($$tstart<$now) {
                   4291:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4292:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4293:                             my (%allroles,%allgroups,$group_privs,
                   4294:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4295:                             my %userroles = (
                   4296:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4297:                             );
1.1056.4.2  raeburn  4298:                             @rolecodes = ('cm');
1.1002    raeburn  4299:                             my $spec=$$role.'.'.$$where;
                   4300:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4301:                             if ($$role =~ /^cr\//) {
                   4302:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4303:                                 push(@rolecodes,'cr');
1.1002    raeburn  4304:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4305:                                 push(@rolecodes,$$role);
1.1002    raeburn  4306:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4307:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4308:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
                   4309: 
1.1002    raeburn  4310:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4311:                                 $group_privs = &unescape($group_privs);
                   4312:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4313:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4314:                                 if (keys(%course_roles) > 0) {
                   4315:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4316:                                     if ($tdomain ne '' && $tnum ne '') {
                   4317:                                         foreach my $key (keys(%course_roles)) {
                   4318:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4319:                                                 my $crsrole = $1;
                   4320:                                                 my $crssec = $2;
                   4321:                                                 if ($crsrole =~ /^cr/) {
                   4322:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4323:                                                         push(@rolecodes,'cr');
                   4324:                                                     }
                   4325:                                                 } else {
                   4326:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4327:                                                         push(@rolecodes,$crsrole);
                   4328:                                                     }
                   4329:                                                 }
                   4330:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4331:                                                 if ($crssec ne '') {
                   4332:                                                     $rolekey .= '/'.$crssec;
                   4333:                                                 }
                   4334:                                                 $rolekey .= './';
                   4335:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4336:                                             }
                   4337:                                         }
                   4338:                                     }
                   4339:                                 }
1.1002    raeburn  4340:                             } else {
1.1056.4.2  raeburn  4341:                                 push(@rolecodes,$$role);
1.1002    raeburn  4342:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4343:                             }
1.1056.4.2  raeburn  4344:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4345:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4346:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4347:                         }
                   4348:                     }
1.1034    raeburn  4349:                     $$tstatus = 'is';
1.1002    raeburn  4350:                 }
1.994     raeburn  4351:             }
                   4352:             if ($$tend) {
                   4353:                 if ($$tend<$then) {
                   4354:                     $$tstatus='expired';
                   4355:                 } elsif ($$tend<$now) {
                   4356:                     $$tstatus='will_not';
                   4357:                 }
                   4358:             }
                   4359:         }
                   4360:     }
                   4361: }
                   4362: 
                   4363: sub check_adhoc_privs {
1.1002    raeburn  4364:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4365:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4366:     if ($env{$cckey}) {
                   4367:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4368:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4369:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4370:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4371:         }
                   4372:     } else {
                   4373:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4374:     }
                   4375: }
                   4376: 
                   4377: sub set_adhoc_privileges {
                   4378: # role can be cc or ca
                   4379:     my ($dcdom,$pickedcourse,$role) = @_;
                   4380:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4381:     my $spec = $role.'.'.$area;
                   4382:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4383:                                   $env{'user.name'});
                   4384:     my %ccrole = ();
                   4385:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4386:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4387:     &appenv(\%userroles,[$role,'cm']);
                   4388:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4389:     &appenv( {'request.role'        => $spec,
                   4390:               'request.role.domain' => $dcdom,
                   4391:               'request.course.sec'  => ''
                   4392:              }
                   4393:            );
                   4394:     my $tadv=0;
                   4395:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4396:     &appenv({'request.role.adv'    => $tadv});
                   4397: }
                   4398: 
1.12      www      4399: # --------------------------------------------------------------- get interface
                   4400: 
                   4401: sub get {
1.131     albertel 4402:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4403:    my $items='';
1.800     albertel 4404:    foreach my $item (@$storearr) {
                   4405:        $items.=&escape($item).'&';
1.191     harris41 4406:    }
1.12      www      4407:    $items=~s/\&$//;
1.620     albertel 4408:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4409:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4410:    my $uhome=&homeserver($uname,$udomain);
                   4411: 
1.133     albertel 4412:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4413:    my @pairs=split(/\&/,$rep);
1.273     albertel 4414:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4415:      return @pairs;
                   4416:    }
1.15      www      4417:    my %returnhash=();
1.42      www      4418:    my $i=0;
1.800     albertel 4419:    foreach my $item (@$storearr) {
                   4420:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4421:       $i++;
1.191     harris41 4422:    }
1.15      www      4423:    return %returnhash;
1.27      www      4424: }
                   4425: 
                   4426: # --------------------------------------------------------------- del interface
                   4427: 
                   4428: sub del {
1.133     albertel 4429:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4430:    my $items='';
1.800     albertel 4431:    foreach my $item (@$storearr) {
                   4432:        $items.=&escape($item).'&';
1.191     harris41 4433:    }
1.984     neumanie 4434: 
1.27      www      4435:    $items=~s/\&$//;
1.620     albertel 4436:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4437:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4438:    my $uhome=&homeserver($uname,$udomain);
                   4439:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4440: }
                   4441: 
                   4442: # -------------------------------------------------------------- dump interface
                   4443: 
                   4444: sub dump {
1.755     albertel 4445:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4446:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4447:     if (!$uname) { $uname=$env{'user.name'}; }
                   4448:     my $uhome=&homeserver($uname,$udomain);
                   4449:     if ($regexp) {
                   4450: 	$regexp=&escape($regexp);
                   4451:     } else {
                   4452: 	$regexp='.';
                   4453:     }
                   4454:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4455:     my @pairs=split(/\&/,$rep);
                   4456:     my %returnhash=();
                   4457:     foreach my $item (@pairs) {
                   4458: 	my ($key,$value)=split(/=/,$item,2);
                   4459: 	$key = &unescape($key);
                   4460: 	next if ($key =~ /^error: 2 /);
                   4461: 	$returnhash{$key}=&thaw_unescape($value);
                   4462:     }
                   4463:     return %returnhash;
1.407     www      4464: }
                   4465: 
1.717     albertel 4466: # --------------------------------------------------------- dumpstore interface
                   4467: 
                   4468: sub dumpstore {
                   4469:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4470:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4471:    if (!$uname) { $uname=$env{'user.name'}; }
                   4472:    my $uhome=&homeserver($uname,$udomain);
                   4473:    if ($regexp) {
                   4474:        $regexp=&escape($regexp);
                   4475:    } else {
                   4476:        $regexp='.';
                   4477:    }
                   4478:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4479:    my @pairs=split(/\&/,$rep);
                   4480:    my %returnhash=();
                   4481:    foreach my $item (@pairs) {
                   4482:        my ($key,$value)=split(/=/,$item,2);
                   4483:        next if ($key =~ /^error: 2 /);
                   4484:        $returnhash{$key}=&thaw_unescape($value);
                   4485:    }
                   4486:    return %returnhash;
1.717     albertel 4487: }
                   4488: 
1.407     www      4489: # -------------------------------------------------------------- keys interface
                   4490: 
                   4491: sub getkeys {
                   4492:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4493:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4494:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4495:    my $uhome=&homeserver($uname,$udomain);
                   4496:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4497:    my @keyarray=();
1.800     albertel 4498:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4499:       next if ($key =~ /^error: 2 /);
1.800     albertel 4500:       push(@keyarray,&unescape($key));
1.407     www      4501:    }
                   4502:    return @keyarray;
1.318     matthew  4503: }
                   4504: 
1.319     matthew  4505: # --------------------------------------------------------------- currentdump
                   4506: sub currentdump {
1.328     matthew  4507:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4508:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4509:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4510:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4511:    my $uhome = &homeserver($sname,$sdom);
                   4512:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4513:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4514:    #
1.318     matthew  4515:    my %returnhash=();
1.319     matthew  4516:    #
                   4517:    if ($rep eq "unknown_cmd") { 
                   4518:        # an old lond will not know currentdump
                   4519:        # Do a dump and make it look like a currentdump
1.822     albertel 4520:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4521:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4522:        my %hash = @tmp;
                   4523:        @tmp=();
1.424     matthew  4524:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4525:    } else {
                   4526:        my @pairs=split(/\&/,$rep);
1.800     albertel 4527:        foreach my $pair (@pairs) {
                   4528:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4529:            my ($symb,$param) = split(/:/,$key);
                   4530:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4531:                                                         &thaw_unescape($value);
1.319     matthew  4532:        }
1.191     harris41 4533:    }
1.12      www      4534:    return %returnhash;
1.424     matthew  4535: }
                   4536: 
                   4537: sub convert_dump_to_currentdump{
                   4538:     my %hash = %{shift()};
                   4539:     my %returnhash;
                   4540:     # Code ripped from lond, essentially.  The only difference
                   4541:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4542:     # we might run in to problems with parameter names =~ /^v\./
                   4543:     while (my ($key,$value) = each(%hash)) {
                   4544:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4545: 	$symb  = &unescape($symb);
                   4546: 	$param = &unescape($param);
1.424     matthew  4547:         next if ($v eq 'version' || $symb eq 'keys');
                   4548:         next if (exists($returnhash{$symb}) &&
                   4549:                  exists($returnhash{$symb}->{$param}) &&
                   4550:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4551:         $returnhash{$symb}->{$param}=$value;
                   4552:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4553:     }
                   4554:     #
                   4555:     # Remove all of the keys in the hashes which keep track of
                   4556:     # the version of the parameter.
                   4557:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4558:         # use a foreach because we are going to delete from the hash.
                   4559:         foreach my $key (keys(%$param_hash)) {
                   4560:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4561:         }
                   4562:     }
                   4563:     return \%returnhash;
1.12      www      4564: }
                   4565: 
1.627     albertel 4566: # ------------------------------------------------------ critical inc interface
                   4567: 
                   4568: sub cinc {
                   4569:     return &inc(@_,'critical');
                   4570: }
                   4571: 
1.449     matthew  4572: # --------------------------------------------------------------- inc interface
                   4573: 
                   4574: sub inc {
1.627     albertel 4575:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4576:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4577:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4578:     my $uhome=&homeserver($uname,$udomain);
                   4579:     my $items='';
                   4580:     if (! ref($store)) {
                   4581:         # got a single value, so use that instead
                   4582:         $items = &escape($store).'=&';
                   4583:     } elsif (ref($store) eq 'SCALAR') {
                   4584:         $items = &escape($$store).'=&';        
                   4585:     } elsif (ref($store) eq 'ARRAY') {
                   4586:         $items = join('=&',map {&escape($_);} @{$store});
                   4587:     } elsif (ref($store) eq 'HASH') {
                   4588:         while (my($key,$value) = each(%{$store})) {
                   4589:             $items.= &escape($key).'='.&escape($value).'&';
                   4590:         }
                   4591:     }
                   4592:     $items=~s/\&$//;
1.627     albertel 4593:     if ($critical) {
                   4594: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4595:     } else {
                   4596: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4597:     }
1.449     matthew  4598: }
                   4599: 
1.12      www      4600: # --------------------------------------------------------------- put interface
                   4601: 
                   4602: sub put {
1.134     albertel 4603:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4604:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4605:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4606:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4607:    my $items='';
1.800     albertel 4608:    foreach my $item (keys(%$storehash)) {
                   4609:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4610:    }
1.12      www      4611:    $items=~s/\&$//;
1.134     albertel 4612:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4613: }
                   4614: 
1.631     albertel 4615: # ------------------------------------------------------------ newput interface
                   4616: 
                   4617: sub newput {
                   4618:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4619:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4620:    if (!$uname) { $uname=$env{'user.name'}; }
                   4621:    my $uhome=&homeserver($uname,$udomain);
                   4622:    my $items='';
                   4623:    foreach my $key (keys(%$storehash)) {
                   4624:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4625:    }
                   4626:    $items=~s/\&$//;
                   4627:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4628: }
                   4629: 
                   4630: # ---------------------------------------------------------  putstore interface
                   4631: 
1.524     raeburn  4632: sub putstore {
1.715     albertel 4633:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4634:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4635:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4636:    my $uhome=&homeserver($uname,$udomain);
                   4637:    my $items='';
1.715     albertel 4638:    foreach my $key (keys(%$storehash)) {
                   4639:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4640:    }
1.715     albertel 4641:    $items=~s/\&$//;
1.716     albertel 4642:    my $esc_symb=&escape($symb);
                   4643:    my $esc_v=&escape($version);
1.715     albertel 4644:    my $reply =
1.716     albertel 4645:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4646: 	      $uhome);
                   4647:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4648:        # gfall back to way things use to be done
1.715     albertel 4649:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4650: 			    $uname);
1.524     raeburn  4651:    }
1.715     albertel 4652:    return $reply;
                   4653: }
                   4654: 
                   4655: sub old_putstore {
1.716     albertel 4656:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4657:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4658:     if (!$uname) { $uname=$env{'user.name'}; }
                   4659:     my $uhome=&homeserver($uname,$udomain);
                   4660:     my %newstorehash;
1.800     albertel 4661:     foreach my $item (keys(%$storehash)) {
                   4662: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4663: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4664:     }
                   4665:     my $items='';
                   4666:     my %allitems = ();
1.800     albertel 4667:     foreach my $item (keys(%newstorehash)) {
                   4668: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4669: 	    my $key = $1.':keys:'.$2;
                   4670: 	    $allitems{$key} .= $3.':';
                   4671: 	}
1.800     albertel 4672: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4673:     }
1.800     albertel 4674:     foreach my $item (keys(%allitems)) {
                   4675: 	$allitems{$item} =~ s/\:$//;
                   4676: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4677:     }
                   4678:     $items=~s/\&$//;
                   4679:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4680: }
                   4681: 
1.47      www      4682: # ------------------------------------------------------ critical put interface
                   4683: 
                   4684: sub cput {
1.134     albertel 4685:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4686:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4687:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4688:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4689:    my $items='';
1.800     albertel 4690:    foreach my $item (keys(%$storehash)) {
                   4691:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4692:    }
1.47      www      4693:    $items=~s/\&$//;
1.134     albertel 4694:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4695: }
                   4696: 
                   4697: # -------------------------------------------------------------- eget interface
                   4698: 
                   4699: sub eget {
1.133     albertel 4700:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4701:    my $items='';
1.800     albertel 4702:    foreach my $item (@$storearr) {
                   4703:        $items.=&escape($item).'&';
1.191     harris41 4704:    }
1.12      www      4705:    $items=~s/\&$//;
1.620     albertel 4706:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4707:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4708:    my $uhome=&homeserver($uname,$udomain);
                   4709:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4710:    my @pairs=split(/\&/,$rep);
                   4711:    my %returnhash=();
1.42      www      4712:    my $i=0;
1.800     albertel 4713:    foreach my $item (@$storearr) {
                   4714:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4715:       $i++;
1.191     harris41 4716:    }
1.12      www      4717:    return %returnhash;
                   4718: }
                   4719: 
1.667     albertel 4720: # ------------------------------------------------------------ tmpput interface
                   4721: sub tmpput {
1.802     raeburn  4722:     my ($storehash,$server,$context)=@_;
1.667     albertel 4723:     my $items='';
1.800     albertel 4724:     foreach my $item (keys(%$storehash)) {
                   4725: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4726:     }
                   4727:     $items=~s/\&$//;
1.802     raeburn  4728:     if (defined($context)) {
                   4729:         $items .= ':'.&escape($context);
                   4730:     }
1.667     albertel 4731:     return &reply("tmpput:$items",$server);
                   4732: }
                   4733: 
                   4734: # ------------------------------------------------------------ tmpget interface
                   4735: sub tmpget {
1.688     albertel 4736:     my ($token,$server)=@_;
                   4737:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4738:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4739:     my %returnhash;
                   4740:     foreach my $item (split(/\&/,$rep)) {
                   4741: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4742:         next if ($key =~ /^error: 2 /);
1.667     albertel 4743: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4744:     }
                   4745:     return %returnhash;
                   4746: }
                   4747: 
1.688     albertel 4748: # ------------------------------------------------------------ tmpget interface
                   4749: sub tmpdel {
                   4750:     my ($token,$server)=@_;
                   4751:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4752:     return &reply("tmpdel:$token",$server);
                   4753: }
                   4754: 
1.765     albertel 4755: # -------------------------------------------------- portfolio access checking
                   4756: 
                   4757: sub portfolio_access {
1.766     albertel 4758:     my ($requrl) = @_;
1.765     albertel 4759:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4760:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4761:     if ($result) {
                   4762:         my %setters;
                   4763:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4764:             my ($startblock,$endblock) =
                   4765:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4766:             if ($startblock && $endblock) {
                   4767:                 return 'B';
                   4768:             }
                   4769:         } else {
                   4770:             my ($startblock,$endblock) =
                   4771:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4772:             if ($startblock && $endblock) {
                   4773:                 return 'B';
                   4774:             }
                   4775:         }
                   4776:     }
1.765     albertel 4777:     if ($result eq 'ok') {
1.766     albertel 4778:        return 'F';
1.765     albertel 4779:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4780:        return 'A';
1.765     albertel 4781:     }
1.766     albertel 4782:     return '';
1.765     albertel 4783: }
                   4784: 
                   4785: sub get_portfolio_access {
1.767     albertel 4786:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4787: 
                   4788:     if (!ref($access_hash)) {
                   4789: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4790: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4791: 						   $file_name);
                   4792: 	$access_hash = $access_controls{$file_name};
                   4793:     }
                   4794: 
1.765     albertel 4795:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4796:     my $now = time;
                   4797:     if (ref($access_hash) eq 'HASH') {
                   4798:         foreach my $key (keys(%{$access_hash})) {
                   4799:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4800:             if ($start > $now) {
                   4801:                 next;
                   4802:             }
                   4803:             if ($end && $end<$now) {
                   4804:                 next;
                   4805:             }
                   4806:             if ($scope eq 'public') {
                   4807:                 $public = $key;
                   4808:                 last;
                   4809:             } elsif ($scope eq 'guest') {
                   4810:                 $guest = $key;
                   4811:             } elsif ($scope eq 'domains') {
                   4812:                 push(@domains,$key);
                   4813:             } elsif ($scope eq 'users') {
                   4814:                 push(@users,$key);
                   4815:             } elsif ($scope eq 'course') {
                   4816:                 push(@courses,$key);
                   4817:             } elsif ($scope eq 'group') {
                   4818:                 push(@groups,$key);
                   4819:             }
                   4820:         }
                   4821:         if ($public) {
                   4822:             return 'ok';
                   4823:         }
                   4824:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4825:             if ($guest) {
                   4826:                 return $guest;
                   4827:             }
                   4828:         } else {
                   4829:             if (@domains > 0) {
                   4830:                 foreach my $domkey (@domains) {
                   4831:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4832:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4833:                             return 'ok';
                   4834:                         }
                   4835:                     }
                   4836:                 }
                   4837:             }
                   4838:             if (@users > 0) {
                   4839:                 foreach my $userkey (@users) {
1.865     raeburn  4840:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4841:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4842:                             if (ref($item) eq 'HASH') {
                   4843:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4844:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4845:                                     return 'ok';
                   4846:                                 }
                   4847:                             }
                   4848:                         }
                   4849:                     } 
1.765     albertel 4850:                 }
                   4851:             }
                   4852:             my %roleshash;
                   4853:             my @courses_and_groups = @courses;
                   4854:             push(@courses_and_groups,@groups); 
                   4855:             if (@courses_and_groups > 0) {
                   4856:                 my (%allgroups,%allroles); 
                   4857:                 my ($start,$end,$role,$sec,$group);
                   4858:                 foreach my $envkey (%env) {
1.1056.4.1  raeburn  4859:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4860:                         my $cid = $2.'_'.$3; 
                   4861:                         if ($1 eq 'gr') {
                   4862:                             $group = $4;
                   4863:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4864:                         } else {
                   4865:                             if ($4 eq '') {
                   4866:                                 $sec = 'none';
                   4867:                             } else {
                   4868:                                 $sec = $4;
                   4869:                             }
                   4870:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4871:                         }
1.811     albertel 4872:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4873:                         my $cid = $2.'_'.$3;
                   4874:                         if ($4 eq '') {
                   4875:                             $sec = 'none';
                   4876:                         } else {
                   4877:                             $sec = $4;
                   4878:                         }
                   4879:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4880:                     }
                   4881:                 }
                   4882:                 if (keys(%allroles) == 0) {
                   4883:                     return;
                   4884:                 }
                   4885:                 foreach my $key (@courses_and_groups) {
                   4886:                     my %content = %{$$access_hash{$key}};
                   4887:                     my $cnum = $content{'number'};
                   4888:                     my $cdom = $content{'domain'};
                   4889:                     my $cid = $cdom.'_'.$cnum;
                   4890:                     if (!exists($allroles{$cid})) {
                   4891:                         next;
                   4892:                     }    
                   4893:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4894:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4895:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4896:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4897:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4898:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4899:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4900:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4901:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4902:                                         if (grep/^all$/,@sections) {
                   4903:                                             return 'ok';
                   4904:                                         } else {
                   4905:                                             if (grep/^$sec$/,@sections) {
                   4906:                                                 return 'ok';
                   4907:                                             }
                   4908:                                         }
                   4909:                                     }
                   4910:                                 }
                   4911:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4912:                                     if (grep/^none$/,@groups) {
                   4913:                                         return 'ok';
                   4914:                                     }
                   4915:                                 } else {
                   4916:                                     if (grep/^all$/,@groups) {
                   4917:                                         return 'ok';
                   4918:                                     } 
                   4919:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4920:                                         if (grep/^$group$/,@groups) {
                   4921:                                             return 'ok';
                   4922:                                         }
                   4923:                                     }
                   4924:                                 } 
                   4925:                             }
                   4926:                         }
                   4927:                     }
                   4928:                 }
                   4929:             }
                   4930:             if ($guest) {
                   4931:                 return $guest;
                   4932:             }
                   4933:         }
                   4934:     }
                   4935:     return;
                   4936: }
                   4937: 
                   4938: sub course_group_datechecker {
                   4939:     my ($dates,$now,$status) = @_;
                   4940:     my ($start,$end) = split(/\./,$dates);
                   4941:     if (!$start && !$end) {
                   4942:         return 'ok';
                   4943:     }
                   4944:     if (grep/^active$/,@{$status}) {
                   4945:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4946:             return 'ok';
                   4947:         }
                   4948:     }
                   4949:     if (grep/^previous$/,@{$status}) {
                   4950:         if ($end > $now ) {
                   4951:             return 'ok';
                   4952:         }
                   4953:     }
                   4954:     if (grep/^future$/,@{$status}) {
                   4955:         if ($start > $now) {
                   4956:             return 'ok';
                   4957:         }
                   4958:     }
                   4959:     return; 
                   4960: }
                   4961: 
                   4962: sub parse_portfolio_url {
                   4963:     my ($url) = @_;
                   4964: 
                   4965:     my ($type,$udom,$unum,$group,$file_name);
                   4966:     
1.823     albertel 4967:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4968: 	$type = 1;
                   4969:         $udom = $1;
                   4970:         $unum = $2;
                   4971:         $file_name = $3;
1.823     albertel 4972:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4973: 	$type = 2;
                   4974:         $udom = $1;
                   4975:         $unum = $2;
                   4976:         $group = $3;
                   4977:         $file_name = $3.'/'.$4;
                   4978:     }
                   4979:     if (wantarray) {
                   4980: 	return ($type,$udom,$unum,$file_name,$group);
                   4981:     }
                   4982:     return $type;
                   4983: }
                   4984: 
                   4985: sub is_portfolio_url {
                   4986:     my ($url) = @_;
                   4987:     return scalar(&parse_portfolio_url($url));
                   4988: }
                   4989: 
1.798     raeburn  4990: sub is_portfolio_file {
                   4991:     my ($file) = @_;
1.820     raeburn  4992:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4993:         return 1;
                   4994:     }
                   4995:     return;
                   4996: }
                   4997: 
1.976     raeburn  4998: sub usertools_access {
1.985     raeburn  4999:     my ($uname,$udom,$tool,$action,$context) = @_;
                   5000:     my ($access,%tools);
                   5001:     if ($context eq '') {
                   5002:         $context = 'tools';
                   5003:     }
                   5004:     if ($context eq 'requestcourses') {
                   5005:         %tools = (
                   5006:                       official   => 1,
                   5007:                       unofficial => 1,
1.1006    raeburn  5008:                       community  => 1,
1.985     raeburn  5009:                  );
                   5010:     } else {
                   5011:         %tools = (
                   5012:                       aboutme   => 1,
                   5013:                       blog      => 1,
                   5014:                       portfolio => 1,
                   5015:                  );
                   5016:     }
1.976     raeburn  5017:     return if (!defined($tools{$tool}));
                   5018: 
                   5019:     if ((!defined($udom)) || (!defined($uname))) {
                   5020:         $udom = $env{'user.domain'};
                   5021:         $uname = $env{'user.name'};
                   5022:     }
                   5023: 
1.978     raeburn  5024:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5025:         if ($action ne 'reload') {
1.985     raeburn  5026:             if ($context eq 'requestcourses') {
                   5027:                 return $env{'environment.canrequest.'.$tool};
                   5028:             } else {
                   5029:                 return $env{'environment.availabletools.'.$tool};
                   5030:             }
                   5031:         }
1.976     raeburn  5032:     }
                   5033: 
                   5034:     my ($toolstatus,$inststatus);
                   5035: 
1.985     raeburn  5036:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5037:          ($action ne 'reload')) {
                   5038:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5039:         $inststatus = $env{'environment.inststatus'};
                   5040:     } else {
1.1025    raeburn  5041:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985     raeburn  5042:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  5043:         $inststatus = $userenv{'inststatus'};
                   5044:     }
                   5045: 
                   5046:     if ($toolstatus ne '') {
                   5047:         if ($toolstatus) {
                   5048:             $access = 1;
                   5049:         } else {
                   5050:             $access = 0;
                   5051:         }
                   5052:         return $access;
                   5053:     }
                   5054: 
                   5055:     my $is_adv = &is_advanced_user($udom,$uname);
                   5056:     my %domdef = &get_domain_defaults($udom);
                   5057:     if (ref($domdef{$tool}) eq 'HASH') {
                   5058:         if ($is_adv) {
                   5059:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5060:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5061:                     $access = 1;
                   5062:                 } else {
                   5063:                     $access = 0;
                   5064:                 }
                   5065:                 return $access;
                   5066:             }
                   5067:         }
                   5068:         if ($inststatus ne '') {
                   5069:             my ($hasaccess,$hasnoaccess);
                   5070:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5071:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5072:                     if ($domdef{$tool}{$affiliation}) {
                   5073:                         $hasaccess = 1;
                   5074:                     } else {
                   5075:                         $hasnoaccess = 1;
                   5076:                     }
                   5077:                 }
                   5078:             }
                   5079:             if ($hasaccess || $hasnoaccess) {
                   5080:                 if ($hasaccess) {
                   5081:                     $access = 1;
                   5082:                 } elsif ($hasnoaccess) {
                   5083:                     $access = 0; 
                   5084:                 }
                   5085:                 return $access;
                   5086:             }
                   5087:         } else {
                   5088:             if ($domdef{$tool}{'default'} ne '') {
                   5089:                 if ($domdef{$tool}{'default'}) {
                   5090:                     $access = 1;
                   5091:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5092:                     $access = 0;
                   5093:                 }
                   5094:                 return $access;
                   5095:             }
                   5096:         }
                   5097:     } else {
1.985     raeburn  5098:         if ($context eq 'tools') {
                   5099:             $access = 1;
                   5100:         } else {
                   5101:             $access = 0;
                   5102:         }
1.976     raeburn  5103:         return $access;
                   5104:     }
                   5105: }
                   5106: 
1.1050    raeburn  5107: sub is_course_owner {
                   5108:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5109:     if (($udom eq '') || ($uname eq '')) {
                   5110:         $udom = $env{'user.domain'};
                   5111:         $uname = $env{'user.name'};
                   5112:     }
                   5113:     unless (($udom eq '') || ($uname eq '')) {
                   5114:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5115:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5116:                 return 1;
                   5117:             } else {
                   5118:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5119:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5120:                     return 1;
                   5121:                 }
                   5122:             }
                   5123:         }
                   5124:     }
                   5125:     return;
                   5126: }
                   5127: 
1.976     raeburn  5128: sub is_advanced_user {
                   5129:     my ($udom,$uname) = @_;
                   5130:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5131:     my %allroles;
                   5132:     my $is_adv;
                   5133:     foreach my $role (keys(%roleshash)) {
                   5134:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5135:         my $area = '/'.$tdomain.'/'.$trest;
                   5136:         if ($sec ne '') {
                   5137:             $area .= '/'.$sec;
                   5138:         }
                   5139:         if (($area ne '') && ($trole ne '')) {
                   5140:             my $spec=$trole.'.'.$area;
                   5141:             if ($trole =~ /^cr\//) {
                   5142:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5143:             } elsif ($trole ne 'gr') {
                   5144:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5145:             }
                   5146:         }
                   5147:     }
                   5148:     foreach my $role (keys(%allroles)) {
                   5149:         last if ($is_adv);
                   5150:         foreach my $item (split(/:/,$allroles{$role})) {
                   5151:             if ($item ne '') {
                   5152:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5153:                 if ($privilege eq 'adv') {
                   5154:                     $is_adv = 1;
                   5155:                     last;
                   5156:                 }
                   5157:             }
                   5158:         }
                   5159:     }
                   5160:     return $is_adv;
                   5161: }
1.798     raeburn  5162: 
1.1035    raeburn  5163: sub check_can_request {
1.1036    raeburn  5164:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5165:     my $canreq = 0;
                   5166:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5167:     my @options = ('approval','validate','autolimit');
                   5168:     my $optregex = join('|',@options);
                   5169:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5170:         foreach my $type (@{$types}) {
                   5171:             if (&usertools_access($env{'user.name'},
                   5172:                                   $env{'user.domain'},
                   5173:                                   $type,undef,'requestcourses')) {
                   5174:                 $canreq ++;
1.1036    raeburn  5175:                 if (ref($request_domains) eq 'HASH') {
                   5176:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5177:                 }
1.1035    raeburn  5178:                 if ($dom eq $env{'user.domain'}) {
                   5179:                     $can_request->{$type} = 1;
                   5180:                 }
                   5181:             }
                   5182:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5183:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5184:                 if (@curr > 0) {
1.1036    raeburn  5185:                     foreach my $item (@curr) {
                   5186:                         if (ref($request_domains) eq 'HASH') {
                   5187:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5188:                             if ($otherdom ne '') {
                   5189:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5190:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5191:                                         push(@{$request_domains->{$type}},$otherdom);
                   5192:                                     }
                   5193:                                 } else {
                   5194:                                     push(@{$request_domains->{$type}},$otherdom);
                   5195:                                 }
                   5196:                             }
                   5197:                         }
                   5198:                     }
                   5199:                     unless($dom eq $env{'user.domain'}) {
                   5200:                         $canreq ++;
1.1035    raeburn  5201:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5202:                             $can_request->{$type} = 1;
                   5203:                         }
                   5204:                     }
                   5205:                 }
                   5206:             }
                   5207:         }
                   5208:     }
                   5209:     return $canreq;
                   5210: }
                   5211: 
1.341     www      5212: # ---------------------------------------------- Custom access rule evaluation
                   5213: 
                   5214: sub customaccess {
                   5215:     my ($priv,$uri)=@_;
1.807     albertel 5216:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5217:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5218:     $udom = &LONCAPA::clean_domain($udom);
                   5219:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5220:     my $access=0;
1.800     albertel 5221:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5222: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5223: 	if ($type eq 'user') {
                   5224: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5225: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5226: 		if ($tdom) {
                   5227: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5228: 		}
1.896     albertel 5229: 		if ($tuname) {
                   5230: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5231: 		}
                   5232: 		$access=($effect eq 'allow');
                   5233: 		last;
                   5234: 	    }
                   5235: 	} else {
                   5236: 	    if ($role) {
                   5237: 		if ($role ne $urole) { next; }
                   5238: 	    }
                   5239: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5240: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5241: 		if ($tdom) {
                   5242: 		    if ($tdom ne $udom) { next; }
                   5243: 		}
                   5244: 		if ($tcrs) {
                   5245: 		    if ($tcrs ne $ucrs) { next; }
                   5246: 		}
                   5247: 		if ($tsec) {
                   5248: 		    if ($tsec ne $usec) { next; }
                   5249: 		}
                   5250: 		$access=($effect eq 'allow');
                   5251: 		last;
                   5252: 	    }
                   5253: 	    if ($realm eq '' && $role eq '') {
                   5254: 		$access=($effect eq 'allow');
                   5255: 	    }
1.402     bowersj2 5256: 	}
1.341     www      5257:     }
                   5258:     return $access;
                   5259: }
                   5260: 
1.103     harris41 5261: # ------------------------------------------------- Check for a user privilege
1.12      www      5262: 
                   5263: sub allowed {
1.810     raeburn  5264:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5265:     my $ver_orguri=$uri;
1.439     www      5266:     $uri=&deversion($uri);
1.152     www      5267:     my $orguri=$uri;
1.52      www      5268:     $uri=&declutter($uri);
1.809     raeburn  5269: 
1.810     raeburn  5270:     if ($priv eq 'evb') {
                   5271: # Evade communication block restrictions for specified role in a course
                   5272:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5273:             return $1;
                   5274:         } else {
                   5275:             return;
                   5276:         }
                   5277:     }
                   5278: 
1.620     albertel 5279:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5280: # Free bre access to adm and meta resources
1.775     albertel 5281:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5282: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5283: 	&& ($priv eq 'bre')) {
1.14      www      5284: 	return 'F';
1.159     www      5285:     }
                   5286: 
1.545     banghart 5287: # Free bre access to user's own portfolio contents
1.714     raeburn  5288:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5289:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5290: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5291:         my %setters;
                   5292:         my ($startblock,$endblock) = 
                   5293:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5294:         if ($startblock && $endblock) {
                   5295:             return 'B';
                   5296:         } else {
                   5297:             return 'F';
                   5298:         }
1.545     banghart 5299:     }
                   5300: 
1.762     raeburn  5301: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5302:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5303:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5304:         if (exists($env{'request.course.id'})) {
                   5305:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5306:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5307:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5308:                 my $courseprivid=$env{'request.course.id'};
                   5309:                 $courseprivid=~s/\_/\//;
                   5310:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5311:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5312:                     return $1; 
1.762     raeburn  5313:                 } else {
                   5314:                     if ($env{'request.course.sec'}) {
                   5315:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5316:                     }
                   5317:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5318:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5319:                         return $2;
                   5320:                     }
1.714     raeburn  5321:                 }
                   5322:             }
                   5323:         }
                   5324:     }
                   5325: 
1.159     www      5326: # Free bre to public access
                   5327: 
                   5328:     if ($priv eq 'bre') {
1.238     www      5329:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5330: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5331:            return 'F'; 
                   5332:         }
1.238     www      5333:         if ($copyright eq 'priv') {
                   5334:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5335: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5336: 		return '';
                   5337:             }
                   5338:         }
                   5339:         if ($copyright eq 'domain') {
                   5340:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5341: 	    unless (($env{'user.domain'} eq $1) ||
                   5342:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5343: 		return '';
                   5344:             }
1.262     matthew  5345:         }
1.620     albertel 5346:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5347:             # Library role, so allow browsing of resources in this domain.
                   5348:             return 'F';
1.238     www      5349:         }
1.341     www      5350:         if ($copyright eq 'custom') {
                   5351: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5352:         }
1.14      www      5353:     }
1.264     matthew  5354:     # Domain coordinator is trying to create a course
1.620     albertel 5355:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5356:         # uri is the requested domain in this case.
                   5357:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5358:         # a role of dc for the domain in question.
1.620     albertel 5359:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5360:     }
1.29      www      5361: 
1.52      www      5362:     my $thisallowed='';
                   5363:     my $statecond=0;
                   5364:     my $courseprivid='';
                   5365: 
1.1039    raeburn  5366:     my $ownaccess;
1.1043    raeburn  5367:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5368:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5369:         if ($uri eq '') {
                   5370:             $ownaccess = 1;
                   5371:         } else {
                   5372:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5373:                 my $udom = $env{'user.domain'};
                   5374:                 my $uname = $env{'user.name'};
                   5375:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5376:                     $ownaccess = 1;
1.1040    raeburn  5377:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5378:                     unless ($uri =~ m{\.\./}) {
                   5379:                         $ownaccess = 1;
                   5380:                     }
                   5381:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5382:                     my $now = time;
                   5383:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5384:                         my $adom = $1;
                   5385:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5386:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5387:                                 my ($start,$end) = split('.',$env{$key});
                   5388:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5389:                                     $ownaccess = 1;
                   5390:                                     last;
                   5391:                                 }
                   5392:                             }
                   5393:                         }
                   5394:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5395:                         my $adom = $1;
                   5396:                         my $aname = $2;
1.1042    raeburn  5397:                         foreach my $role ('ca','aa') { 
                   5398:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5399:                                 my ($start,$end) =
                   5400:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5401:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5402:                                     $ownaccess = 1;
                   5403:                                     last;
                   5404:                                 }
1.1039    raeburn  5405:                             }
                   5406:                         }
                   5407:                     }
                   5408:                 }
                   5409:             }
                   5410:         }
                   5411:     }
                   5412: 
1.52      www      5413: # Course
                   5414: 
1.620     albertel 5415:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5416:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5417:             $thisallowed.=$1;
                   5418:         }
1.52      www      5419:     }
1.29      www      5420: 
1.52      www      5421: # Domain
                   5422: 
1.620     albertel 5423:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5424:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5425:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5426:             $thisallowed.=$1;
                   5427:         }
1.12      www      5428:     }
1.52      www      5429: 
                   5430: # Course: uri itself is a course
1.66      www      5431:     my $courseuri=$uri;
                   5432:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5433:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5434: 
1.620     albertel 5435:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5436:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5437:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5438:             $thisallowed.=$1;
                   5439:         }
1.12      www      5440:     }
1.29      www      5441: 
1.665     albertel 5442: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5443: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5444:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5445: 	$thisallowed='';
1.671     raeburn  5446:         my ($match)=&is_on_map($uri);
                   5447:         if ($match) {
                   5448:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5449:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5450:                 $thisallowed.=$1;
                   5451:             }
                   5452:         } else {
1.705     albertel 5453:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5454:             if ($refuri) {
                   5455:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5456:                     $thisallowed='F';
1.671     raeburn  5457:                 } else {
                   5458:                     $refuri=&declutter($refuri);
                   5459:                     my ($match) = &is_on_map($refuri);
                   5460:                     if ($match) {
                   5461:                         $thisallowed='F';
                   5462:                     }
1.669     raeburn  5463:                 }
1.671     raeburn  5464:             }
                   5465:         }
1.314     www      5466:     }
1.492     albertel 5467: 
1.766     albertel 5468:     if ($priv eq 'bre'
                   5469: 	&& $thisallowed ne 'F' 
                   5470: 	&& $thisallowed ne '2'
                   5471: 	&& &is_portfolio_url($uri)) {
                   5472: 	$thisallowed = &portfolio_access($uri);
                   5473:     }
                   5474:     
1.52      www      5475: # Full access at system, domain or course-wide level? Exit.
1.29      www      5476:     if ($thisallowed=~/F/) {
                   5477: 	return 'F';
                   5478:     }
                   5479: 
1.52      www      5480: # If this is generating or modifying users, exit with special codes
1.29      www      5481: 
1.643     www      5482:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5483: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5484: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5485: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5486: 	    unless ($auname) { return $thisallowed; }
                   5487: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5488: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5489: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5490: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5491: 	}
1.52      www      5492: 	return $thisallowed;
                   5493:     }
                   5494: #
1.103     harris41 5495: # Gathered so far: system, domain and course wide privileges
1.52      www      5496: #
                   5497: # Course: See if uri or referer is an individual resource that is part of 
                   5498: # the course
                   5499: 
1.620     albertel 5500:     if ($env{'request.course.id'}) {
1.232     www      5501: 
1.620     albertel 5502:        $courseprivid=$env{'request.course.id'};
                   5503:        if ($env{'request.course.sec'}) {
                   5504:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5505:        }
                   5506:        $courseprivid=~s/\_/\//;
                   5507:        my $checkreferer=1;
1.232     www      5508:        my ($match,$cond)=&is_on_map($uri);
                   5509:        if ($match) {
                   5510:            $statecond=$cond;
1.620     albertel 5511:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5512:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5513:                $thisallowed.=$1;
                   5514:                $checkreferer=0;
                   5515:            }
1.29      www      5516:        }
1.83      www      5517:        
1.148     www      5518:        if ($checkreferer) {
1.620     albertel 5519: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5520:             unless ($refuri) {
1.800     albertel 5521:                 foreach my $key (keys(%env)) {
                   5522: 		    if ($key=~/^httpref\..*\*/) {
                   5523: 			my $pattern=$key;
1.156     www      5524:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5525:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5526:                         $pattern=~s/\//\\\//g;
1.152     www      5527:                         if ($orguri=~/$pattern/) {
1.800     albertel 5528: 			    $refuri=$env{$key};
1.148     www      5529:                         }
                   5530:                     }
1.191     harris41 5531:                 }
1.148     www      5532:             }
1.232     www      5533: 
1.148     www      5534:          if ($refuri) { 
1.152     www      5535: 	  $refuri=&declutter($refuri);
1.232     www      5536:           my ($match,$cond)=&is_on_map($refuri);
                   5537:             if ($match) {
                   5538:               my $refstatecond=$cond;
1.620     albertel 5539:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5540:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5541:                   $thisallowed.=$1;
1.53      www      5542:                   $uri=$refuri;
                   5543:                   $statecond=$refstatecond;
1.52      www      5544:               }
                   5545:           }
1.148     www      5546:         }
1.29      www      5547:        }
1.52      www      5548:    }
1.29      www      5549: 
1.52      www      5550: #
1.103     harris41 5551: # Gathered now: all privileges that could apply, and condition number
1.52      www      5552: # 
                   5553: #
                   5554: # Full or no access?
                   5555: #
1.29      www      5556: 
1.52      www      5557:     if ($thisallowed=~/F/) {
                   5558: 	return 'F';
                   5559:     }
1.29      www      5560: 
1.52      www      5561:     unless ($thisallowed) {
                   5562:         return '';
                   5563:     }
1.29      www      5564: 
1.52      www      5565: # Restrictions exist, deal with them
                   5566: #
                   5567: #   C:according to course preferences
                   5568: #   R:according to resource settings
                   5569: #   L:unless locked
                   5570: #   X:according to user session state
                   5571: #
                   5572: 
                   5573: # Possibly locked functionality, check all courses
1.54      www      5574: # Locks might take effect only after 10 minutes cache expiration for other
                   5575: # courses, and 2 minutes for current course
1.52      www      5576: 
                   5577:     my $envkey;
                   5578:     if ($thisallowed=~/L/) {
1.1000    raeburn  5579:         foreach $envkey (keys(%env)) {
1.54      www      5580:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5581:                my $courseid=$2;
                   5582:                my $roleid=$1.'.'.$2;
1.92      www      5583:                $courseid=~s/^\///;
1.54      www      5584:                my $expiretime=600;
1.620     albertel 5585:                if ($env{'request.role'} eq $roleid) {
1.54      www      5586: 		  $expiretime=120;
                   5587:                }
                   5588: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5589:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5590:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5591: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5592:                }
1.620     albertel 5593:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5594:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5595: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5596:                        &log($env{'user.domain'},$env{'user.name'},
                   5597:                             $env{'user.home'},
1.57      www      5598:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5599:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5600:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5601: 		       return '';
                   5602:                    }
                   5603:                }
1.620     albertel 5604:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5605:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5606: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5607:                        &log($env{'user.domain'},$env{'user.name'},
                   5608:                             $env{'user.home'},
1.57      www      5609:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5610:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5611:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5612: 		       return '';
                   5613:                    }
                   5614:                }
                   5615: 	   }
1.29      www      5616:        }
1.52      www      5617:     }
                   5618:    
                   5619: #
                   5620: # Rest of the restrictions depend on selected course
                   5621: #
                   5622: 
1.620     albertel 5623:     unless ($env{'request.course.id'}) {
1.766     albertel 5624: 	if ($thisallowed eq 'A') {
                   5625: 	    return 'A';
1.814     raeburn  5626:         } elsif ($thisallowed eq 'B') {
                   5627:             return 'B';
1.766     albertel 5628: 	} else {
                   5629: 	    return '1';
                   5630: 	}
1.52      www      5631:     }
1.29      www      5632: 
1.52      www      5633: #
                   5634: # Now user is definitely in a course
                   5635: #
1.53      www      5636: 
                   5637: 
                   5638: # Course preferences
                   5639: 
                   5640:    if ($thisallowed=~/C/) {
1.620     albertel 5641:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5642:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5643:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5644: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5645: 	   if ($priv ne 'pch') { 
                   5646: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5647: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5648: 			$env{'request.course.id'});
                   5649: 	   }
1.237     www      5650:            return '';
                   5651:        }
                   5652: 
1.620     albertel 5653:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5654: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5655: 	   if ($priv ne 'pch') { 
                   5656: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5657: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5658: 			$env{'request.course.id'});
                   5659: 	   }
1.54      www      5660:            return '';
                   5661:        }
1.53      www      5662:    }
                   5663: 
                   5664: # Resource preferences
                   5665: 
                   5666:    if ($thisallowed=~/R/) {
1.620     albertel 5667:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5668:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5669: 	   if ($priv ne 'pch') { 
                   5670: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5671: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5672: 	   }
                   5673: 	   return '';
1.54      www      5674:        }
1.53      www      5675:    }
1.30      www      5676: 
1.246     www      5677: # Restricted by state or randomout?
1.30      www      5678: 
1.52      www      5679:    if ($thisallowed=~/X/) {
1.620     albertel 5680:       if ($env{'acc.randomout'}) {
1.579     albertel 5681: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5682:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5683:             return ''; 
                   5684:          }
1.247     www      5685:       }
                   5686:       if (&condval($statecond)) {
1.52      www      5687: 	 return '2';
                   5688:       } else {
                   5689:          return '';
                   5690:       }
                   5691:    }
1.30      www      5692: 
1.766     albertel 5693:     if ($thisallowed eq 'A') {
                   5694: 	return 'A';
1.814     raeburn  5695:     } elsif ($thisallowed eq 'B') {
                   5696:         return 'B';
1.766     albertel 5697:     }
1.52      www      5698:    return 'F';
1.232     www      5699: }
                   5700: 
1.710     albertel 5701: sub split_uri_for_cond {
                   5702:     my $uri=&deversion(&declutter(shift));
                   5703:     my @uriparts=split(/\//,$uri);
                   5704:     my $filename=pop(@uriparts);
                   5705:     my $pathname=join('/',@uriparts);
                   5706:     return ($pathname,$filename);
                   5707: }
1.232     www      5708: # --------------------------------------------------- Is a resource on the map?
                   5709: 
                   5710: sub is_on_map {
1.710     albertel 5711:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5712:     #Trying to find the conditional for the file
1.620     albertel 5713:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5714: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5715:     if ($match) {
1.289     bowersj2 5716: 	return (1,$1);
                   5717:     } else {
1.434     www      5718: 	return (0,0);
1.289     bowersj2 5719:     }
1.12      www      5720: }
                   5721: 
1.427     www      5722: # --------------------------------------------------------- Get symb from alias
                   5723: 
                   5724: sub get_symb_from_alias {
                   5725:     my $symb=shift;
                   5726:     my ($map,$resid,$url)=&decode_symb($symb);
                   5727: # Already is a symb
                   5728:     if ($url) { return $symb; }
                   5729: # Must be an alias
                   5730:     my $aliassymb='';
                   5731:     my %bighash;
1.620     albertel 5732:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5733:                             &GDBM_READER(),0640)) {
                   5734:         my $rid=$bighash{'mapalias_'.$symb};
                   5735: 	if ($rid) {
                   5736: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5737: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5738: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5739: 	}
                   5740:         untie %bighash;
                   5741:     }
                   5742:     return $aliassymb;
                   5743: }
                   5744: 
1.12      www      5745: # ----------------------------------------------------------------- Define Role
                   5746: 
                   5747: sub definerole {
                   5748:   if (allowed('mcr','/')) {
                   5749:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5750:     foreach my $role (split(':',$sysrole)) {
                   5751: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5752:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5753:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5754: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5755:                return "refused:s:$crole&$cqual"; 
                   5756:             }
                   5757:         }
1.191     harris41 5758:     }
1.800     albertel 5759:     foreach my $role (split(':',$domrole)) {
                   5760: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5761:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5762:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5763: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5764:                return "refused:d:$crole&$cqual"; 
                   5765:             }
                   5766:         }
1.191     harris41 5767:     }
1.800     albertel 5768:     foreach my $role (split(':',$courole)) {
                   5769: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5770:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5771:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5772: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5773:                return "refused:c:$crole&$cqual"; 
                   5774:             }
                   5775:         }
1.191     harris41 5776:     }
1.620     albertel 5777:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5778:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5779: 	        "rolesdef_$rolename=".
                   5780:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5781:     return reply($command,$env{'user.home'});
1.12      www      5782:   } else {
                   5783:     return 'refused';
                   5784:   }
1.105     harris41 5785: }
                   5786: 
                   5787: # ---------------- Make a metadata query against the network of library servers
                   5788: 
                   5789: sub metadata_query {
1.244     matthew  5790:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5791:     my %rhash;
1.845     albertel 5792:     my %libserv = &all_library();
1.244     matthew  5793:     my @server_list = (defined($server_array) ? @$server_array
                   5794:                                               : keys(%libserv) );
                   5795:     for my $server (@server_list) {
1.118     harris41 5796: 	unless ($custom or $customshow) {
                   5797: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5798: 	    $rhash{$server}=$reply;
                   5799: 	}
                   5800: 	else {
                   5801: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5802: 			     &escape($custom).':'.&escape($customshow),
                   5803: 			     $server);
                   5804: 	    $rhash{$server}=$reply;
                   5805: 	}
1.112     harris41 5806:     }
1.118     harris41 5807:     return \%rhash;
1.240     www      5808: }
                   5809: 
                   5810: # ----------------------------------------- Send log queries and wait for reply
                   5811: 
                   5812: sub log_query {
                   5813:     my ($uname,$udom,$query,%filters)=@_;
                   5814:     my $uhome=&homeserver($uname,$udom);
                   5815:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5816:     my $uhost=&hostname($uhome);
1.800     albertel 5817:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5818:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5819:                        $uhome);
1.479     albertel 5820:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5821:     return get_query_reply($queryid);
                   5822: }
                   5823: 
1.818     raeburn  5824: # -------------------------- Update MySQL table for portfolio file
                   5825: 
                   5826: sub update_portfolio_table {
1.821     raeburn  5827:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5828:     if ($group ne '') {
                   5829:         $file_name =~s /^\Q$group\E//;
                   5830:     }
1.818     raeburn  5831:     my $homeserver = &homeserver($uname,$udom);
                   5832:     my $queryid=
1.821     raeburn  5833:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5834:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5835:     my $reply = &get_query_reply($queryid);
                   5836:     return $reply;
                   5837: }
                   5838: 
1.899     raeburn  5839: # -------------------------- Update MySQL allusers table
                   5840: 
                   5841: sub update_allusers_table {
                   5842:     my ($uname,$udom,$names) = @_;
                   5843:     my $homeserver = &homeserver($uname,$udom);
                   5844:     my $queryid=
                   5845:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5846:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5847:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5848:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5849:                'generation='.&escape($names->{'generation'}).'%%'.
                   5850:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5851:                'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4  raeburn  5852:     return;
1.899     raeburn  5853: }
                   5854: 
1.508     raeburn  5855: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5856: 
                   5857: sub fetch_enrollment_query {
1.511     raeburn  5858:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5859:     my $homeserver;
1.547     raeburn  5860:     my $maxtries = 1;
1.508     raeburn  5861:     if ($context eq 'automated') {
                   5862:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5863:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5864:     } else {
                   5865:         $homeserver = &homeserver($cnum,$dom);
                   5866:     }
1.838     albertel 5867:     my $host=&hostname($homeserver);
1.506     raeburn  5868:     my $cmd = '';
1.1000    raeburn  5869:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5870:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5871:     }
                   5872:     $cmd =~ s/%%$//;
                   5873:     $cmd = &escape($cmd);
                   5874:     my $query = 'fetchenrollment';
1.620     albertel 5875:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5876:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5877:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5878:         return 'error: '.$queryid;
                   5879:     }
1.506     raeburn  5880:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5881:     my $tries = 1;
                   5882:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5883:         $reply = &get_query_reply($queryid);
                   5884:         $tries ++;
                   5885:     }
1.526     raeburn  5886:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5887:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5888:     } else {
1.901     albertel 5889:         my @responses = split(/:/,$reply);
1.515     raeburn  5890:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5891:             foreach my $line (@responses) {
                   5892:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5893:                 $$replyref{$key} = $value;
                   5894:             }
                   5895:         } else {
1.506     raeburn  5896:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5897:             foreach my $line (@responses) {
                   5898:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5899:                 $$replyref{$key} = $value;
                   5900:                 if ($value > 0) {
1.800     albertel 5901:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5902:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5903:                         my $destname = $pathname.'/'.$filename;
                   5904:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5905:                         if ($xml_classlist =~ /^error/) {
                   5906:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5907:                         } else {
1.506     raeburn  5908:                             if ( open(FILE,">$destname") ) {
                   5909:                                 print FILE &unescape($xml_classlist);
                   5910:                                 close(FILE);
1.526     raeburn  5911:                             } else {
                   5912:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5913:                             }
                   5914:                         }
                   5915:                     }
                   5916:                 }
                   5917:             }
                   5918:         }
                   5919:         return 'ok';
                   5920:     }
                   5921:     return 'error';
                   5922: }
                   5923: 
1.242     www      5924: sub get_query_reply {
                   5925:     my $queryid=shift;
1.240     www      5926:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5927:     my $reply='';
                   5928:     for (1..100) {
                   5929: 	sleep 2;
                   5930:         if (-e $replyfile.'.end') {
1.448     albertel 5931: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5932: 		$reply = join('',<$fh>);
                   5933: 		close($fh);
1.240     www      5934: 	   } else { return 'error: reply_file_error'; }
1.242     www      5935:            return &unescape($reply);
                   5936: 	}
1.240     www      5937:     }
1.242     www      5938:     return 'timeout:'.$queryid;
1.240     www      5939: }
                   5940: 
                   5941: sub courselog_query {
1.241     www      5942: #
                   5943: # possible filters:
                   5944: # url: url or symb
                   5945: # username
                   5946: # domain
                   5947: # action: view, submit, grade
                   5948: # start: timestamp
                   5949: # end: timestamp
                   5950: #
1.240     www      5951:     my (%filters)=@_;
1.620     albertel 5952:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5953:     if ($filters{'url'}) {
                   5954: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5955:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5956:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5957:     }
1.620     albertel 5958:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5959:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5960:     return &log_query($cname,$cdom,'courselog',%filters);
                   5961: }
                   5962: 
                   5963: sub userlog_query {
1.858     raeburn  5964: #
                   5965: # possible filters:
                   5966: # action: log check role
                   5967: # start: timestamp
                   5968: # end: timestamp
                   5969: #
1.240     www      5970:     my ($uname,$udom,%filters)=@_;
                   5971:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5972: }
                   5973: 
1.506     raeburn  5974: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5975: 
                   5976: sub auto_run {
1.508     raeburn  5977:     my ($cnum,$cdom) = @_;
1.876     raeburn  5978:     my $response = 0;
                   5979:     my $settings;
                   5980:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5981:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5982:         $settings = $domconfig{'autoenroll'};
                   5983:         if ($settings->{'run'} eq '1') {
                   5984:             $response = 1;
                   5985:         }
                   5986:     } else {
1.934     raeburn  5987:         my $homeserver;
                   5988:         if (&is_course($cdom,$cnum)) {
                   5989:             $homeserver = &homeserver($cnum,$cdom);
                   5990:         } else {
                   5991:             $homeserver = &domain($cdom,'primary');
                   5992:         }
                   5993:         if ($homeserver ne 'no_host') {
                   5994:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5995:         }
1.876     raeburn  5996:     }
1.506     raeburn  5997:     return $response;
                   5998: }
1.776     albertel 5999: 
1.506     raeburn  6000: sub auto_get_sections {
1.508     raeburn  6001:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6002:     my $homeserver;
                   6003:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6004:         $homeserver = &homeserver($cnum,$cdom);
                   6005:     }
                   6006:     if (!defined($homeserver)) { 
                   6007:         if ($cdom =~ /^$match_domain$/) {
                   6008:             $homeserver = &domain($cdom,'primary');
                   6009:         }
                   6010:     }
                   6011:     my @secs;
                   6012:     if (defined($homeserver)) {
                   6013:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6014:         unless ($response eq 'refused') {
                   6015:             @secs = split(/:/,$response);
                   6016:         }
1.506     raeburn  6017:     }
                   6018:     return @secs;
                   6019: }
1.776     albertel 6020: 
1.506     raeburn  6021: sub auto_new_course {
1.508     raeburn  6022:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   6023:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  6024:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  6025:     return $response;
                   6026: }
1.776     albertel 6027: 
1.506     raeburn  6028: sub auto_validate_courseID {
1.508     raeburn  6029:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6030:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6031:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6032:     return $response;
                   6033: }
1.776     albertel 6034: 
1.1007    raeburn  6035: sub auto_validate_instcode {
1.1020    raeburn  6036:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6037:     my ($homeserver,$response);
                   6038:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6039:         $homeserver = &homeserver($cnum,$cdom);
                   6040:     }
                   6041:     if (!defined($homeserver)) {
                   6042:         if ($cdom =~ /^$match_domain$/) {
                   6043:             $homeserver = &domain($cdom,'primary');
                   6044:         }
                   6045:     }
1.1056.4.2  raeburn  6046:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6047:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6048:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6049:     return ($outcome,$description);
1.1007    raeburn  6050: }
                   6051: 
1.506     raeburn  6052: sub auto_create_password {
1.873     raeburn  6053:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6054:     my ($homeserver,$response);
1.506     raeburn  6055:     my $create_passwd = 0;
                   6056:     my $authchk = '';
1.873     raeburn  6057:     if ($udom =~ /^$match_domain$/) {
                   6058:         $homeserver = &domain($udom,'primary');
                   6059:     }
                   6060:     if ($homeserver eq '') {
                   6061:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6062:             $homeserver = &homeserver($cnum,$cdom);
                   6063:         }
                   6064:     }
                   6065:     if ($homeserver eq '') {
                   6066:         $authchk = 'nodomain';
1.506     raeburn  6067:     } else {
1.873     raeburn  6068:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6069:         if ($response eq 'refused') {
                   6070:             $authchk = 'refused';
                   6071:         } else {
1.901     albertel 6072:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6073:         }
1.506     raeburn  6074:     }
                   6075:     return ($authparam,$create_passwd,$authchk);
                   6076: }
                   6077: 
1.706     raeburn  6078: sub auto_photo_permission {
                   6079:     my ($cnum,$cdom,$students) = @_;
                   6080:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6081:     my ($outcome,$perm_reqd,$conditions) = 
                   6082: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6083:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6084: 	return (undef,undef);
                   6085:     }
1.706     raeburn  6086:     return ($outcome,$perm_reqd,$conditions);
                   6087: }
                   6088: 
                   6089: sub auto_checkphotos {
                   6090:     my ($uname,$udom,$pid) = @_;
                   6091:     my $homeserver = &homeserver($uname,$udom);
                   6092:     my ($result,$resulttype);
                   6093:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6094: 				   &escape($uname).':'.&escape($pid),
                   6095: 				   $homeserver));
1.709     albertel 6096:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6097: 	return (undef,undef);
                   6098:     }
1.706     raeburn  6099:     if ($outcome) {
                   6100:         ($result,$resulttype) = split(/:/,$outcome);
                   6101:     } 
                   6102:     return ($result,$resulttype);
                   6103: }
                   6104: 
                   6105: sub auto_photochoice {
                   6106:     my ($cnum,$cdom) = @_;
                   6107:     my $homeserver = &homeserver($cnum,$cdom);
                   6108:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6109: 						       &escape($cdom),
                   6110: 						       $homeserver)));
1.709     albertel 6111:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6112: 	return (undef,undef);
                   6113:     }
1.706     raeburn  6114:     return ($update,$comment);
                   6115: }
                   6116: 
                   6117: sub auto_photoupdate {
                   6118:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6119:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6120:     my $host=&hostname($homeserver);
1.706     raeburn  6121:     my $cmd = '';
                   6122:     my $maxtries = 1;
1.800     albertel 6123:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6124:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6125:     }
                   6126:     $cmd =~ s/%%$//;
                   6127:     $cmd = &escape($cmd);
                   6128:     my $query = 'institutionalphotos';
                   6129:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6130:     unless ($queryid=~/^\Q$host\E\_/) {
                   6131:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6132:         return 'error: '.$queryid;
                   6133:     }
                   6134:     my $reply = &get_query_reply($queryid);
                   6135:     my $tries = 1;
                   6136:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6137:         $reply = &get_query_reply($queryid);
                   6138:         $tries ++;
                   6139:     }
                   6140:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6141:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6142:     } else {
                   6143:         my @responses = split(/:/,$reply);
                   6144:         my $outcome = shift(@responses); 
                   6145:         foreach my $item (@responses) {
                   6146:             my ($key,$value) = split(/=/,$item);
                   6147:             $$photo{$key} = $value;
                   6148:         }
                   6149:         return $outcome;
                   6150:     }
                   6151:     return 'error';
                   6152: }
                   6153: 
1.521     raeburn  6154: sub auto_instcode_format {
1.793     albertel 6155:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6156: 	$cat_order) = @_;
1.521     raeburn  6157:     my $courses = '';
1.772     raeburn  6158:     my @homeservers;
1.521     raeburn  6159:     if ($caller eq 'global') {
1.841     albertel 6160: 	my %servers = &get_servers($codedom,'library');
                   6161: 	foreach my $tryserver (keys(%servers)) {
                   6162: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6163: 		push(@homeservers,$tryserver);
                   6164: 	    }
1.584     raeburn  6165:         }
1.1022    raeburn  6166:     } elsif ($caller eq 'requests') {
                   6167:         if ($codedom =~ /^$match_domain$/) {
                   6168:             my $chome = &domain($codedom,'primary');
                   6169:             unless ($chome eq 'no_host') {
                   6170:                 push(@homeservers,$chome);
                   6171:             }
                   6172:         }
1.521     raeburn  6173:     } else {
1.772     raeburn  6174:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6175:     }
1.793     albertel 6176:     foreach my $code (keys(%{$instcodes})) {
                   6177:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6178:     }
                   6179:     chop($courses);
1.772     raeburn  6180:     my $ok_response = 0;
                   6181:     my $response;
                   6182:     while (@homeservers > 0 && $ok_response == 0) {
                   6183:         my $server = shift(@homeservers); 
                   6184:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6185:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6186:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6187: 		split(/:/,$response);
1.772     raeburn  6188:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6189:             push(@{$codetitles},&str2array($codetitles_str));
                   6190:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6191:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6192:             $ok_response = 1;
                   6193:         }
                   6194:     }
                   6195:     if ($ok_response) {
1.521     raeburn  6196:         return 'ok';
1.772     raeburn  6197:     } else {
                   6198:         return $response;
1.521     raeburn  6199:     }
                   6200: }
                   6201: 
1.792     raeburn  6202: sub auto_instcode_defaults {
                   6203:     my ($domain,$returnhash,$code_order) = @_;
                   6204:     my @homeservers;
1.841     albertel 6205: 
                   6206:     my %servers = &get_servers($domain,'library');
                   6207:     foreach my $tryserver (keys(%servers)) {
                   6208: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6209: 	    push(@homeservers,$tryserver);
                   6210: 	}
1.792     raeburn  6211:     }
1.841     albertel 6212: 
1.792     raeburn  6213:     my $response;
1.841     albertel 6214:     foreach my $server (@homeservers) {
1.792     raeburn  6215:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6216:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6217: 	
                   6218: 	foreach my $pair (split(/\&/,$response)) {
                   6219: 	    my ($name,$value)=split(/\=/,$pair);
                   6220: 	    if ($name eq 'code_order') {
                   6221: 		@{$code_order} = split(/\&/,&unescape($value));
                   6222: 	    } else {
                   6223: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6224: 	    }
                   6225: 	}
                   6226: 	return 'ok';
1.792     raeburn  6227:     }
1.841     albertel 6228: 
                   6229:     return $response;
1.1003    raeburn  6230: }
                   6231: 
                   6232: sub auto_possible_instcodes {
1.1007    raeburn  6233:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6234:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6235:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6236:         return;
                   6237:     }
1.1003    raeburn  6238:     my (@homeservers,$uhome);
                   6239:     if (defined(&domain($domain,'primary'))) {
                   6240:         $uhome=&domain($domain,'primary');
                   6241:         push(@homeservers,&domain($domain,'primary'));
                   6242:     } else {
                   6243:         my %servers = &get_servers($domain,'library');
                   6244:         foreach my $tryserver (keys(%servers)) {
                   6245:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6246:                 push(@homeservers,$tryserver);
                   6247:             }
                   6248:         }
                   6249:     }
                   6250:     my $response;
                   6251:     foreach my $server (@homeservers) {
                   6252:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6253:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6254:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6255:             split(':',$response);
                   6256:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6257:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6258:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6259:             my ($name,$value)=split('=',$item);
                   6260:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6261:         }
                   6262:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6263:             my ($name,$value)=split('=',$item);
                   6264:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6265:         }
                   6266:         return 'ok';
                   6267:     }
                   6268:     return $response;
                   6269: }
1.792     raeburn  6270: 
1.1010    raeburn  6271: sub auto_courserequest_checks {
                   6272:     my ($dom) = @_;
1.1020    raeburn  6273:     my ($homeserver,%validations);
                   6274:     if ($dom =~ /^$match_domain$/) {
                   6275:         $homeserver = &domain($dom,'primary');
                   6276:     }
                   6277:     unless ($homeserver eq 'no_host') {
                   6278:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6279:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6280:             my @items = split(/&/,$response);
                   6281:             foreach my $item (@items) {
                   6282:                 my ($key,$value) = split('=',$item);
                   6283:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6284:             }
                   6285:         }
                   6286:     }
1.1010    raeburn  6287:     return %validations; 
                   6288: }
                   6289: 
1.1020    raeburn  6290: sub auto_courserequest_validation {
                   6291:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6292:     my ($homeserver,$response);
                   6293:     if ($dom =~ /^$match_domain$/) {
                   6294:         $homeserver = &domain($dom,'primary');
                   6295:     }
                   6296:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6297:           
1.1020    raeburn  6298:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6299:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6300:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6301:                                     $homeserver));
                   6302:     }
                   6303:     return $response;
                   6304: }
                   6305: 
1.777     albertel 6306: sub auto_validate_class_sec {
1.918     raeburn  6307:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6308:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6309:     my $ownerlist;
                   6310:     if (ref($owners) eq 'ARRAY') {
                   6311:         $ownerlist = join(',',@{$owners});
                   6312:     } else {
                   6313:         $ownerlist = $owners;
                   6314:     }
1.773     raeburn  6315:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6316:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6317:     return $response;
                   6318: }
                   6319: 
1.679     raeburn  6320: # ------------------------------------------------------- Course Group routines
                   6321: 
                   6322: sub get_coursegroups {
1.809     raeburn  6323:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6324:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6325: }
                   6326: 
1.679     raeburn  6327: sub modify_coursegroup {
                   6328:     my ($cdom,$cnum,$groupsettings) = @_;
                   6329:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6330: }
                   6331: 
1.809     raeburn  6332: sub toggle_coursegroup_status {
                   6333:     my ($cdom,$cnum,$group,$action) = @_;
                   6334:     my ($from_namespace,$to_namespace);
                   6335:     if ($action eq 'delete') {
                   6336:         $from_namespace = 'coursegroups';
                   6337:         $to_namespace = 'deleted_groups';
                   6338:     } else {
                   6339:         $from_namespace = 'deleted_groups';
                   6340:         $to_namespace = 'coursegroups';
                   6341:     }
                   6342:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6343:     if (my $tmp = &error(%curr_group)) {
                   6344:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6345:         return ('read error',$tmp);
                   6346:     } else {
                   6347:         my %savedsettings = %curr_group; 
1.809     raeburn  6348:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6349:         my $deloutcome;
                   6350:         if ($result eq 'ok') {
1.809     raeburn  6351:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6352:         } else {
                   6353:             return ('write error',$result);
                   6354:         }
                   6355:         if ($deloutcome eq 'ok') {
                   6356:             return 'ok';
                   6357:         } else {
                   6358:             return ('delete error',$deloutcome);
                   6359:         }
                   6360:     }
                   6361: }
                   6362: 
1.679     raeburn  6363: sub modify_group_roles {
1.957     raeburn  6364:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6365:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6366:     my $role = 'gr/'.&escape($userprivs);
                   6367:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6368:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6369:     if ($result eq 'ok') {
                   6370:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6371:     }
1.679     raeburn  6372:     return $result;
                   6373: }
                   6374: 
                   6375: sub modify_coursegroup_membership {
                   6376:     my ($cdom,$cnum,$membership) = @_;
                   6377:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6378:     return $result;
                   6379: }
                   6380: 
1.682     raeburn  6381: sub get_active_groups {
                   6382:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6383:     my $now = time;
                   6384:     my %groups = ();
                   6385:     foreach my $key (keys(%env)) {
1.811     albertel 6386:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6387:             my ($start,$end) = split(/\./,$env{$key});
                   6388:             if (($end!=0) && ($end<$now)) { next; }
                   6389:             if (($start!=0) && ($start>$now)) { next; }
                   6390:             if ($1 eq $cdom && $2 eq $cnum) {
                   6391:                 $groups{$3} = $env{$key} ;
                   6392:             }
                   6393:         }
                   6394:     }
                   6395:     return %groups;
                   6396: }
                   6397: 
1.683     raeburn  6398: sub get_group_membership {
                   6399:     my ($cdom,$cnum,$group) = @_;
                   6400:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6401: }
                   6402: 
                   6403: sub get_users_groups {
                   6404:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6405:     my @usersgroups;
1.683     raeburn  6406:     my $cachetime=1800;
                   6407: 
                   6408:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6409:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6410:     if (defined($cached)) {
1.734     albertel 6411:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6412:     } else {  
                   6413:         $grouplist = '';
1.816     raeburn  6414:         my $courseurl = &courseid_to_courseurl($courseid);
                   6415:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  6416:         my $access_end = $env{'course.'.$courseid.
                   6417:                               '.default_enrollment_end_date'};
                   6418:         my $now = time;
                   6419:         foreach my $key (keys(%roleshash)) {
                   6420:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6421:                 my $group = $1;
                   6422:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6423:                     my $start = $2;
                   6424:                     my $end = $1;
                   6425:                     if ($start == -1) { next; } # deleted from group
                   6426:                     if (($start!=0) && ($start>$now)) { next; }
                   6427:                     if (($end!=0) && ($end<$now)) {
                   6428:                         if ($access_end && $access_end < $now) {
                   6429:                             if ($access_end - $end < 86400) {
                   6430:                                 push(@usersgroups,$group);
1.733     raeburn  6431:                             }
                   6432:                         }
1.817     raeburn  6433:                         next;
1.733     raeburn  6434:                     }
1.817     raeburn  6435:                     push(@usersgroups,$group);
1.683     raeburn  6436:                 }
                   6437:             }
                   6438:         }
1.817     raeburn  6439:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6440:         $grouplist = join(':',@usersgroups);
                   6441:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6442:     }
1.733     raeburn  6443:     return @usersgroups;
1.683     raeburn  6444: }
                   6445: 
                   6446: sub devalidate_getgroups_cache {
                   6447:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6448:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6449: 
1.683     raeburn  6450:     my $hashid="$udom:$uname:$courseid";
                   6451:     &devalidate_cache_new('getgroups',$hashid);
                   6452: }
                   6453: 
1.12      www      6454: # ------------------------------------------------------------------ Plain Text
                   6455: 
                   6456: sub plaintext {
1.988     raeburn  6457:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6458:     if ($short =~ m{^cr/}) {
1.758     albertel 6459: 	return (split('/',$short))[-1];
                   6460:     }
1.742     raeburn  6461:     if (!defined($cid)) {
                   6462:         $cid = $env{'request.course.id'};
                   6463:     }
                   6464:     my %rolenames = (
1.1008    raeburn  6465:                       Course    => 'std',
                   6466:                       Community => 'alt1',
1.742     raeburn  6467:                     );
1.1037    raeburn  6468:     if ($cid ne '') {
                   6469:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6470:             unless ($forcedefault) {
                   6471:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6472:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6473:                 return &Apache::lonlocal::mt($roletext);
                   6474:             }
                   6475:         }
                   6476:     }
                   6477:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6478:         (defined($rolenames{$type})) && 
                   6479:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6480:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6481:     } elsif ($cid ne '') {
                   6482:         my $crstype = $env{'course.'.$cid.'.type'};
                   6483:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6484:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6485:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6486:         }
1.742     raeburn  6487:     }
1.1037    raeburn  6488:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6489: }
                   6490: 
                   6491: # ----------------------------------------------------------------- Assign Role
                   6492: 
                   6493: sub assignrole {
1.957     raeburn  6494:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6495:         $context)=@_;
1.21      www      6496:     my $mrole;
                   6497:     if ($role =~ /^cr\//) {
1.393     www      6498:         my $cwosec=$url;
1.811     albertel 6499:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6500: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6501:            my $refused = 1;
                   6502:            if ($context eq 'requestcourses') {
                   6503:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6504:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6505:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6506:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6507:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6508:                            if ($crsenv{'internal.courseowner'} eq
                   6509:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6510:                                $refused = '';
                   6511:                            }
                   6512:                        }
                   6513:                    }
                   6514:                }
                   6515:            }
                   6516:            if ($refused) {
                   6517:                &logthis('Refused custom assignrole: '.
                   6518:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6519:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6520:                return 'refused';
                   6521:            }
1.104     www      6522:         }
1.21      www      6523:         $mrole='cr';
1.678     raeburn  6524:     } elsif ($role =~ /^gr\//) {
                   6525:         my $cwogrp=$url;
1.811     albertel 6526:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6527:         unless (&allowed('mdg',$cwogrp)) {
                   6528:             &logthis('Refused group assignrole: '.
                   6529:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6530:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6531:             return 'refused';
                   6532:         }
                   6533:         $mrole='gr';
1.21      www      6534:     } else {
1.82      www      6535:         my $cwosec=$url;
1.811     albertel 6536:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6537:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6538:             my $refused;
                   6539:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6540:                 if (!(&allowed('c'.$role,$url))) {
                   6541:                     $refused = 1;
                   6542:                 }
                   6543:             } else {
                   6544:                 $refused = 1;
                   6545:             }
1.947     raeburn  6546:             if ($refused) {
1.1045    raeburn  6547:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6548:                 if (!$selfenroll && $context eq 'course') {
                   6549:                     my %crsenv;
                   6550:                     if ($role eq 'cc' || $role eq 'co') {
                   6551:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6552:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6553:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6554:                                 if ($crsenv{'internal.courseowner'} eq 
                   6555:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6556:                                     $refused = '';
                   6557:                                 }
                   6558:                             }
                   6559:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6560:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6561:                                 if ($crsenv{'internal.courseowner'} eq 
                   6562:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6563:                                     $refused = '';
                   6564:                                 }
                   6565:                             }
                   6566:                         }
                   6567:                     }
                   6568:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6569:                     $refused = '';
1.1017    raeburn  6570:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6571:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6572:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6573:                         my $wrongcc;
                   6574:                         if ($cnum =~ /^$match_community$/) {
                   6575:                             $wrongcc = 1 if ($role eq 'cc');
                   6576:                         } else {
                   6577:                             $wrongcc = 1 if ($role eq 'co');
                   6578:                         }
                   6579:                         unless ($wrongcc) {
                   6580:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6581:                             if ($crsenv{'internal.courseowner'} eq 
                   6582:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6583:                                 $refused = '';
                   6584:                             }
1.1017    raeburn  6585:                         }
                   6586:                     }
                   6587:                 }
                   6588:                 if ($refused) {
1.947     raeburn  6589:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6590:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6591: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6592:                     return 'refused';
                   6593:                 }
1.932     raeburn  6594:             }
1.104     www      6595:         }
1.21      www      6596:         $mrole=$role;
                   6597:     }
1.620     albertel 6598:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6599:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6600:     if ($end) { $command.='_'.$end; }
1.21      www      6601:     if ($start) {
                   6602: 	if ($end) { 
1.81      www      6603:            $command.='_'.$start; 
1.21      www      6604:         } else {
1.81      www      6605:            $command.='_0_'.$start;
1.21      www      6606:         }
                   6607:     }
1.739     raeburn  6608:     my $origstart = $start;
                   6609:     my $origend = $end;
1.957     raeburn  6610:     my $delflag;
1.357     www      6611: # actually delete
                   6612:     if ($deleteflag) {
1.373     www      6613: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6614: # modify command to delete the role
1.620     albertel 6615:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6616:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6617: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6618: # set start and finish to negative values for userrolelog
                   6619:            $start=-1;
                   6620:            $end=-1;
1.957     raeburn  6621:            $delflag = 1;
1.357     www      6622:         }
                   6623:     }
                   6624: # send command
1.349     www      6625:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6626: # log new user role if status is ok
1.349     www      6627:     if ($answer eq 'ok') {
1.663     raeburn  6628: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6629: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6630:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6631:         unless ($role =~ /^gr/) {
                   6632:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6633:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6634:         }
1.1053    raeburn  6635:         if ($role eq 'cc') {
                   6636:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6637:         }
1.349     www      6638:     }
                   6639:     return $answer;
1.169     harris41 6640: }
                   6641: 
1.1053    raeburn  6642: sub autoupdate_coowners {
                   6643:     my ($url,$end,$start,$uname,$udom) = @_;
                   6644:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6645:     if (($cdom ne '') && ($cnum ne '')) {
                   6646:         my $now = time;
                   6647:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6648:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6649:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6650:             my $instcode = $coursehash{'internal.coursecode'};
                   6651:             if ($instcode ne '') {
1.1056    raeburn  6652:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6653:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6654:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6655:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6656:                         if ($result eq 'valid') {
                   6657:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6658:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6659:                                     push(@newcoowners,$coowner);
                   6660:                                 }
                   6661:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6662:                                     push(@newcoowners,$uname.':'.$udom);
                   6663:                                 }
                   6664:                                 @newcoowners = sort(@newcoowners);
                   6665:                             } else {
                   6666:                                 push(@newcoowners,$uname.':'.$udom);
                   6667:                             }
                   6668:                         } else {
                   6669:                             if ($coursehash{'internal.co-owners'}) {
                   6670:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6671:                                     unless ($coowner eq $uname.':'.$udom) {
                   6672:                                         push(@newcoowners,$coowner);
                   6673:                                     }
                   6674:                                 }
                   6675:                                 unless (@newcoowners > 0) {
                   6676:                                     $delcoowners = 1;
                   6677:                                     $coowners = '';
                   6678:                                 }
                   6679:                             }
                   6680:                         }
                   6681:                         if (@newcoowners || $delcoowners) {
                   6682:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6683:                                             $delcoowners,@newcoowners);
                   6684:                         }
                   6685:                     }
                   6686:                 }
                   6687:             }
                   6688:         }
                   6689:     }
                   6690: }
                   6691: 
                   6692: sub store_coowners {
                   6693:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6694:     my $cid = $cdom.'_'.$cnum;
                   6695:     my ($coowners,$delresult,$putresult);
                   6696:     if (@newcoowners) {
                   6697:         $coowners = join(',',@newcoowners);
                   6698:         my %coownershash = (
                   6699:                             'internal.co-owners' => $coowners,
                   6700:                            );
                   6701:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6702:         if ($putresult eq 'ok') {
                   6703:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6704:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6705:             }
                   6706:         }
                   6707:     }
                   6708:     if ($delcoowners) {
                   6709:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6710:         if ($delresult eq 'ok') {
                   6711:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6712:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6713:             }
                   6714:         }
                   6715:     }
                   6716:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6717:         my %crsinfo =
                   6718:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6719:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6720:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6721:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6722:         }
                   6723:     }
                   6724: }
                   6725: 
1.169     harris41 6726: # -------------------------------------------------- Modify user authentication
1.197     www      6727: # Overrides without validation
                   6728: 
1.169     harris41 6729: sub modifyuserauth {
                   6730:     my ($udom,$uname,$umode,$upass)=@_;
                   6731:     my $uhome=&homeserver($uname,$udom);
1.197     www      6732:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6733:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6734:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6735:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6736:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6737: 		     &escape($upass),$uhome);
1.620     albertel 6738:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6739:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6740:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6741:     &log($udom,,$uname,$uhome,
1.620     albertel 6742:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6743:                                      $env{'user.name'}.', '.$umode.
1.197     www      6744:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6745:     unless ($reply eq 'ok') {
1.197     www      6746:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6747: 	return 'error: '.$reply;
                   6748:     }   
1.170     harris41 6749:     return 'ok';
1.80      www      6750: }
                   6751: 
1.81      www      6752: # --------------------------------------------------------------- Modify a user
1.80      www      6753: 
1.81      www      6754: sub modifyuser {
1.206     matthew  6755:     my ($udom,    $uname, $uid,
                   6756:         $umode,   $upass, $first,
                   6757:         $middle,  $last,  $gene,
1.1056.4.1  raeburn  6758:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6759:     $udom= &LONCAPA::clean_domain($udom);
                   6760:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  raeburn  6761:     my $showcandelete = 'none';
                   6762:     if (ref($candelete) eq 'ARRAY') {
                   6763:         if (@{$candelete} > 0) {
                   6764:             $showcandelete = join(', ',@{$candelete});
                   6765:         }
                   6766:     }
1.81      www      6767:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6768:              $umode.', '.$first.', '.$middle.', '.
1.1056.4.1  raeburn  6769:              $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6770:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6771:                                      ' desiredhome not specified'). 
1.620     albertel 6772:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6773:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6774:     my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4  raeburn  6775:     my $newuser;
                   6776:     if ($uhome eq 'no_host') {
                   6777:         $newuser = 1;
                   6778:     }
                   6779: 
1.80      www      6780: # ----------------------------------------------------------------- Create User
1.406     albertel 6781:     if (($uhome eq 'no_host') && 
                   6782: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6783:         my $unhome='';
1.844     albertel 6784:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6785:             $unhome = $desiredhome;
1.620     albertel 6786: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6787: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6788:         } else { # load balancing routine for determining $unhome
1.81      www      6789:             my $loadm=10000000;
1.841     albertel 6790: 	    my %servers = &get_servers($udom,'library');
                   6791: 	    foreach my $tryserver (keys(%servers)) {
                   6792: 		my $answer=reply('load',$tryserver);
                   6793: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6794: 		    $loadm=$answer;
                   6795: 		    $unhome=$tryserver;
                   6796: 		}
1.80      www      6797: 	    }
                   6798:         }
                   6799:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6800: 	    return 'error: unable to find a home server for '.$uname.
                   6801:                    ' in domain '.$udom;
1.80      www      6802:         }
                   6803:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6804:                          &escape($upass),$unhome);
                   6805: 	unless ($reply eq 'ok') {
                   6806:             return 'error: '.$reply;
                   6807:         }   
1.230     stredwic 6808:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6809:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6810: 	    return 'error: unable verify users home machine.';
1.80      www      6811:         }
1.209     matthew  6812:     }   # End of creation of new user
1.80      www      6813: # ---------------------------------------------------------------------- Add ID
                   6814:     if ($uid) {
                   6815:        $uid=~tr/A-Z/a-z/;
                   6816:        my %uidhash=&idrget($udom,$uname);
1.196     www      6817:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6818:          && (!$forceid)) {
1.80      www      6819: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6820: 	      return 'error: user id "'.$uid.'" does not match '.
                   6821:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6822:           }
                   6823:        } else {
                   6824: 	  &idput($udom,($uname => $uid));
                   6825:        }
                   6826:     }
                   6827: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6828:     my @tmp=&get('environment',
1.899     raeburn  6829: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6830:                     'permanentemail','inststatus'],
1.134     albertel 6831: 		   $udom,$uname);
1.1056.4.4  raeburn  6832:     my (%names,%oldnames);
1.313     matthew  6833:     if ($tmp[0] =~ m/^error:.*/) { 
                   6834:         %names=(); 
                   6835:     } else {
                   6836:         %names = @tmp;
1.1056.4.4  raeburn  6837:         %oldnames = %names;
1.313     matthew  6838:     }
1.1056.4.1  raeburn  6839: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6840: # of users did not contain them), do not overwrite existing values
                   6841: # unless field is in $candelete array ref.  
                   6842: #
                   6843: 
                   6844:     my @fields = ('firstname','middlename','lastname','generation',
                   6845:                   'permanentemail','id');
                   6846:     my %newvalues;
                   6847:     if (ref($candelete) eq 'ARRAY') {
                   6848:         foreach my $field (@fields) {
                   6849:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6850:                 if ($field eq 'firstname') {
                   6851:                     $names{$field} = $first;
                   6852:                 } elsif ($field eq 'middlename') {
                   6853:                     $names{$field} = $middle;
                   6854:                 } elsif ($field eq 'lastname') {
                   6855:                     $names{$field} = $last;
                   6856:                 } elsif ($field eq 'generation') { 
                   6857:                     $names{$field} = $gene;
                   6858:                 } elsif ($field eq 'permanentemail') {
                   6859:                     $names{$field} = $email;
                   6860:                 } elsif ($field eq 'id') {
                   6861:                     $names{$field}  = $uid;
                   6862:                 }
                   6863:             }
                   6864:         }
                   6865:     }
1.388     www      6866:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6867:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6868:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6869:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6870:     if ($email) {
                   6871:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6872:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6873:     }
1.899     raeburn  6874:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6875:     if (defined($inststatus)) {
                   6876:         $names{'inststatus'} = '';
                   6877:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6878:         if (ref($usertypes) eq 'HASH') {
                   6879:             my @okstatuses; 
                   6880:             foreach my $item (split(/:/,$inststatus)) {
                   6881:                 if (defined($usertypes->{$item})) {
                   6882:                     push(@okstatuses,$item);  
                   6883:                 }
                   6884:             }
                   6885:             if (@okstatuses) {
                   6886:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6887:             }
                   6888:         }
                   6889:     }
1.134     albertel 6890:     my $reply = &put('environment', \%names, $udom,$uname);
                   6891:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  6892:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      6893:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.1056.4.4  raeburn  6894:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6895:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  raeburn  6896:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6897:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6898:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6899:     } else {
                   6900:         $logmsg .= ' during self creation';
                   6901:     }
1.1056.4.4  raeburn  6902:     my $changed;
                   6903:     if ($newuser) {
                   6904:         $changed = 1;
                   6905:     } else {
                   6906:         foreach my $field (@fields) {
                   6907:             if ($names{$field} ne $oldnames{$field}) {
                   6908:                 $changed = 1;
                   6909:                 last;
                   6910:             }
                   6911:         }
                   6912:     }
                   6913:     unless ($changed) {
                   6914:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6915:         &logthis($logmsg);
                   6916:         return 'ok';
                   6917:     }
                   6918:     my $reply = &put('environment', \%names, $udom,$uname);
                   6919:     if ($reply ne 'ok') {
                   6920:         return 'error: '.$reply;
                   6921:     }
                   6922:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6923:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6924:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6925:     &logthis($logmsg);
1.134     albertel 6926:     return 'ok';
1.80      www      6927: }
                   6928: 
1.81      www      6929: # -------------------------------------------------------------- Modify student
1.80      www      6930: 
1.81      www      6931: sub modifystudent {
                   6932:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6933:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6934:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6935:     if (!$cid) {
1.620     albertel 6936: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6937: 	    return 'not_in_class';
                   6938: 	}
1.80      www      6939:     }
                   6940: # --------------------------------------------------------------- Make the user
1.81      www      6941:     my $reply=&modifyuser
1.209     matthew  6942: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6943:          $desiredhome,$email,$inststatus);
1.80      www      6944:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6945:     # This will cause &modify_student_enrollment to get the uid from the
                   6946:     # students environment
                   6947:     $uid = undef if (!$forceid);
1.455     albertel 6948:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6949: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6950:     return $reply;
                   6951: }
                   6952: 
                   6953: sub modify_student_enrollment {
1.957     raeburn  6954:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6955:     my ($cdom,$cnum,$chome);
                   6956:     if (!$cid) {
1.620     albertel 6957: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6958: 	    return 'not_in_class';
                   6959: 	}
1.620     albertel 6960: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6961: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6962:     } else {
                   6963: 	($cdom,$cnum)=split(/_/,$cid);
                   6964:     }
1.620     albertel 6965:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6966:     if (!$chome) {
1.457     raeburn  6967: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6968:     }
1.455     albertel 6969:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6970:     # Make sure the user exists
1.81      www      6971:     my $uhome=&homeserver($uname,$udom);
                   6972:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6973: 	return 'error: no such user';
                   6974:     }
1.297     matthew  6975:     # Get student data if we were not given enough information
                   6976:     if (!defined($first)  || $first  eq '' || 
                   6977:         !defined($last)   || $last   eq '' || 
                   6978:         !defined($uid)    || $uid    eq '' || 
                   6979:         !defined($middle) || $middle eq '' || 
                   6980:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6981:         # They did not supply us with enough data to enroll the student, so
                   6982:         # we need to pick up more information.
1.297     matthew  6983:         my %tmp = &get('environment',
1.294     matthew  6984:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6985:                        ,$udom,$uname);
                   6986: 
1.800     albertel 6987:         #foreach my $key (keys(%tmp)) {
                   6988:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6989:         #}
1.294     matthew  6990:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6991:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6992:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6993:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6994:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6995:     }
1.556     albertel 6996:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6997:     my $reply=cput('classlist',
                   6998: 		   {"$uname:$udom" => 
1.515     raeburn  6999: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7000: 		   $cdom,$cnum);
1.81      www      7001:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7002: 	return 'error: '.$reply;
1.652     albertel 7003:     } else {
                   7004: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7005:     }
1.297     matthew  7006:     # Add student role to user
1.83      www      7007:     my $uurl='/'.$cid;
1.81      www      7008:     $uurl=~s/\_/\//g;
                   7009:     if ($usec) {
                   7010: 	$uurl.='/'.$usec;
                   7011:     }
1.957     raeburn  7012:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7013: }
                   7014: 
1.556     albertel 7015: sub format_name {
                   7016:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7017:     my $name;
                   7018:     if ($first ne 'lastname') {
                   7019: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7020:     } else {
                   7021: 	if ($lastname=~/\S/) {
                   7022: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7023: 	    $name=~s/\s+,/,/;
                   7024: 	} else {
                   7025: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7026: 	}
                   7027:     }
                   7028:     $name=~s/^\s+//;
                   7029:     $name=~s/\s+$//;
                   7030:     $name=~s/\s+/ /g;
                   7031:     return $name;
                   7032: }
                   7033: 
1.84      www      7034: # ------------------------------------------------- Write to course preferences
                   7035: 
                   7036: sub writecoursepref {
                   7037:     my ($courseid,%prefs)=@_;
                   7038:     $courseid=~s/^\///;
                   7039:     $courseid=~s/\_/\//g;
                   7040:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7041:     my $chome=homeserver($cnum,$cdomain);
                   7042:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7043: 	return 'error: no such course';
                   7044:     }
                   7045:     my $cstring='';
1.800     albertel 7046:     foreach my $pref (keys(%prefs)) {
                   7047: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7048:     }
1.84      www      7049:     $cstring=~s/\&$//;
                   7050:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7051: }
                   7052: 
                   7053: # ---------------------------------------------------------- Make/modify course
                   7054: 
                   7055: sub createcourse {
1.741     raeburn  7056:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7057:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7058:     $url=&declutter($url);
                   7059:     my $cid='';
1.1028    raeburn  7060:     if ($context eq 'requestcourses') {
                   7061:         my $can_create = 0;
                   7062:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7063:         if ($udom eq $ownerdom) {
                   7064:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7065:                                   $context)) {
                   7066:                 $can_create = 1;
                   7067:             }
                   7068:         } else {
                   7069:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7070:                                            $category);
                   7071:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7072:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7073:                 if (@curr > 0) {
                   7074:                     my @options = qw(approval validate autolimit);
                   7075:                     my $optregex = join('|',@options);
                   7076:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7077:                         $can_create = 1;
                   7078:                     }
                   7079:                 }
                   7080:             }
                   7081:         }
                   7082:         if ($can_create) {
                   7083:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7084:                 unless (&allowed('ccc',$udom)) {
                   7085:                     return 'refused'; 
                   7086:                 }
1.1017    raeburn  7087:             }
                   7088:         } else {
                   7089:             return 'refused';
                   7090:         }
1.1028    raeburn  7091:     } elsif (!&allowed('ccc',$udom)) {
                   7092:         return 'refused';
1.84      www      7093:     }
1.1011    raeburn  7094: # --------------------------------------------------------------- Get Unique ID
                   7095:     my $uname;
                   7096:     if ($cnum =~ /^$match_courseid$/) {
                   7097:         my $chome=&homeserver($cnum,$udom,'true');
                   7098:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7099:             $uname = $cnum;
                   7100:         } else {
1.1038    raeburn  7101:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7102:         }
                   7103:     } else {
1.1038    raeburn  7104:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7105:     }
                   7106:     return $uname if ($uname =~ /^error/);
                   7107: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7108:     if (!defined($course_server)) {
                   7109:         if (defined(&domain($udom,'primary'))) {
                   7110:             $course_server = &domain($udom,'primary');
                   7111:         } else {
                   7112:             $course_server = $env{'user.home'}; 
                   7113:         }
                   7114:     }
                   7115:     my %host_servers =
                   7116:         &Apache::lonnet::get_servers($udom,'library');
                   7117:     unless ($host_servers{$course_server}) {
                   7118:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7119:     }
1.84      www      7120: # ------------------------------------------------------------- Make the course
                   7121:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7122:                       $course_server);
1.84      www      7123:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7124:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7125:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7126: 	return 'error: no such course';
                   7127:     }
1.271     www      7128: # ----------------------------------------------------------------- Course made
1.516     raeburn  7129: # log existence
1.1029    raeburn  7130:     my $now = time;
1.918     raeburn  7131:     my $newcourse = {
                   7132:                     $udom.'_'.$uname => {
1.921     raeburn  7133:                                      description => $description,
                   7134:                                      inst_code   => $inst_code,
                   7135:                                      owner       => $course_owner,
                   7136:                                      type        => $crstype,
1.1029    raeburn  7137:                                      creator     => $env{'user.name'}.':'.
                   7138:                                                     $env{'user.domain'},
                   7139:                                      created     => $now,
                   7140:                                      context     => $context,
1.918     raeburn  7141:                                                 },
                   7142:                     };
1.921     raeburn  7143:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7144: # set toplevel url
1.271     www      7145:     my $topurl=$url;
                   7146:     unless ($nonstandard) {
                   7147: # ------------------------------------------ For standard courses, make top url
                   7148:         my $mapurl=&clutter($url);
1.278     www      7149:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7150:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7151: <map>
                   7152: <resource id="1" type="start"></resource>
                   7153: <resource id="2" src="$mapurl"></resource>
                   7154: <resource id="3" type="finish"></resource>
                   7155: <link index="1" from="1" to="2"></link>
                   7156: <link index="2" from="2" to="3"></link>
                   7157: </map>
                   7158: ENDINITMAP
                   7159:         $topurl=&declutter(
1.638     albertel 7160:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7161:                           );
                   7162:     }
                   7163: # ----------------------------------------------------------- Write preferences
1.84      www      7164:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7165:                      ('description'              => $description,
                   7166:                       'url'                      => $topurl,
                   7167:                       'internal.creator'         => $env{'user.name'}.':'.
                   7168:                                                     $env{'user.domain'},
                   7169:                       'internal.created'         => $now,
                   7170:                       'internal.creationcontext' => $context)
                   7171:                     );
1.84      www      7172:     return '/'.$udom.'/'.$uname;
                   7173: }
                   7174: 
1.1011    raeburn  7175: # ------------------------------------------------------------------- Create ID
                   7176: sub generate_coursenum {
1.1038    raeburn  7177:     my ($udom,$crstype) = @_;
1.1011    raeburn  7178:     my $domdesc = &domain($udom);
                   7179:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7180:     my $first;
                   7181:     if ($crstype eq 'Community') {
                   7182:         $first = '0';
                   7183:     } else {
                   7184:         $first = int(1+rand(9)); 
                   7185:     } 
                   7186:     my $uname=$first.
1.1011    raeburn  7187:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7188:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7189:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7190: # ----------------------------------------------- Make sure that does not exist
                   7191:     my $uhome=&homeserver($uname,$udom,'true');
                   7192:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7193:         if ($crstype eq 'Community') {
                   7194:             $first = '0';
                   7195:         } else {
                   7196:             $first = int(1+rand(9));
                   7197:         }
                   7198:         $uname=$first.
1.1011    raeburn  7199:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7200:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7201:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7202:         $uhome=&homeserver($uname,$udom,'true');
                   7203:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7204:             return 'error: unable to generate unique course-ID';
                   7205:         }
                   7206:     }
                   7207:     return $uname;
                   7208: }
                   7209: 
1.813     albertel 7210: sub is_course {
                   7211:     my ($cdom,$cnum) = @_;
                   7212:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7213: 				undef,'.');
1.813     albertel 7214:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7215:         return 1;
                   7216:     }
                   7217:     return 0;
                   7218: }
                   7219: 
1.1015    raeburn  7220: sub store_userdata {
                   7221:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7222:     my $result;
1.1016    raeburn  7223:     if ($datakey ne '') {
1.1013    raeburn  7224:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7225:             if ($udom eq '' || $uname eq '') {
                   7226:                 $udom = $env{'user.domain'};
                   7227:                 $uname = $env{'user.name'};
                   7228:             }
                   7229:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7230:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7231:                 $result = 'error: no_host';
                   7232:             } else {
                   7233:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7234:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7235: 
                   7236:                 my $namevalue='';
                   7237:                 foreach my $key (keys(%{$storehash})) {
                   7238:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7239:                 }
                   7240:                 $namevalue=~s/\&$//;
                   7241:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7242:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7243:             }
                   7244:         } else {
                   7245:             $result = 'error: data to store was not a hash reference'; 
                   7246:         }
                   7247:     } else {
                   7248:         $result= 'error: invalid requestkey'; 
                   7249:     }
                   7250:     return $result;
                   7251: }
                   7252: 
1.21      www      7253: # ---------------------------------------------------------- Assign Custom Role
                   7254: 
                   7255: sub assigncustomrole {
1.957     raeburn  7256:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7257:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7258:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7259: }
                   7260: 
                   7261: # ----------------------------------------------------------------- Revoke Role
                   7262: 
                   7263: sub revokerole {
1.957     raeburn  7264:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7265:     my $now=time;
1.965     raeburn  7266:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7267: }
                   7268: 
                   7269: # ---------------------------------------------------------- Revoke Custom Role
                   7270: 
                   7271: sub revokecustomrole {
1.957     raeburn  7272:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7273:     my $now=time;
1.357     www      7274:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7275:            $deleteflag,$selfenroll,$context);
1.17      www      7276: }
                   7277: 
1.533     banghart 7278: # ------------------------------------------------------------ Disk usage
1.535     albertel 7279: sub diskusage {
1.955     raeburn  7280:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7281:     $directorypath =~ s/\/$//;
                   7282:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7283:                        .&escape($getpropath).':'.&escape($uname).':'
                   7284:                        .&escape($udom),homeserver($uname,$udom));
                   7285:     if ($listing eq 'unknown_cmd') {
                   7286:         if ($getpropath) {
                   7287:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7288:         }
                   7289:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7290:     }
1.514     albertel 7291:     return $listing;
1.512     banghart 7292: }
                   7293: 
1.566     banghart 7294: sub is_locked {
                   7295:     my ($file_name, $domain, $user) = @_;
                   7296:     my @check;
                   7297:     my $is_locked;
                   7298:     push @check, $file_name;
1.613     albertel 7299:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7300: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7301:     my ($tmp)=keys(%locked);
                   7302:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7303:     
1.566     banghart 7304:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7305:         $is_locked = 'false';
                   7306:         foreach my $entry (@{$locked{$file_name}}) {
                   7307:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7308:                $is_locked = 'true';
                   7309:                last;
1.745     raeburn  7310:            }
                   7311:        }
1.566     banghart 7312:     } else {
                   7313:         $is_locked = 'false';
                   7314:     }
                   7315: }
                   7316: 
1.759     albertel 7317: sub declutter_portfile {
                   7318:     my ($file) = @_;
1.833     albertel 7319:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7320:     return $file;
                   7321: }
                   7322: 
1.559     banghart 7323: # ------------------------------------------------------------- Mark as Read Only
                   7324: 
                   7325: sub mark_as_readonly {
                   7326:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7327:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7328:     my ($tmp)=keys(%current_permissions);
                   7329:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7330:     foreach my $file (@{$files}) {
1.759     albertel 7331: 	$file = &declutter_portfile($file);
1.561     banghart 7332:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7333:     }
1.613     albertel 7334:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7335:     return;
                   7336: }
                   7337: 
1.572     banghart 7338: # ------------------------------------------------------------Save Selected Files
                   7339: 
                   7340: sub save_selected_files {
                   7341:     my ($user, $path, @files) = @_;
                   7342:     my $filename = $user."savedfiles";
1.573     banghart 7343:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7344:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7345:     foreach my $file (@files) {
1.620     albertel 7346:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7347:     }
                   7348:     foreach my $file (@other_files) {
1.574     banghart 7349:         print (OUT $file."\n");
1.572     banghart 7350:     }
1.574     banghart 7351:     close (OUT);
1.572     banghart 7352:     return 'ok';
                   7353: }
                   7354: 
1.574     banghart 7355: sub clear_selected_files {
                   7356:     my ($user) = @_;
                   7357:     my $filename = $user."savedfiles";
                   7358:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7359:     print (OUT undef);
                   7360:     close (OUT);
                   7361:     return ("ok");    
                   7362: }
                   7363: 
1.572     banghart 7364: sub files_in_path {
                   7365:     my ($user, $path) = @_;
                   7366:     my $filename = $user."savedfiles";
                   7367:     my %return_files;
1.574     banghart 7368:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7369:     while (my $line_in = <IN>) {
1.574     banghart 7370:         chomp ($line_in);
                   7371:         my @paths_and_file = split (m!/!, $line_in);
                   7372:         my $file_part = pop (@paths_and_file);
                   7373:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7374:         $path_part.='/';
                   7375:         my $path_and_file = $path_part.$file_part;
                   7376:         if ($path_part eq $path) {
                   7377:             $return_files{$file_part}= 'selected';
                   7378:         }
                   7379:     }
1.574     banghart 7380:     close (IN);
                   7381:     return (\%return_files);
1.572     banghart 7382: }
                   7383: 
                   7384: # called in portfolio select mode, to show files selected NOT in current directory
                   7385: sub files_not_in_path {
                   7386:     my ($user, $path) = @_;
                   7387:     my $filename = $user."savedfiles";
                   7388:     my @return_files;
                   7389:     my $path_part;
1.800     albertel 7390:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7391:     while (my $line = <IN>) {
1.572     banghart 7392:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7393:         my @paths_and_file = split(m|/|, $line);
                   7394:         my $file_part = pop(@paths_and_file);
                   7395:         chomp($file_part);
                   7396:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7397:         $path_part .= '/';
                   7398:         my $path_and_file = $path_part.$file_part;
                   7399:         if ($path_part ne $path) {
1.800     albertel 7400:             push(@return_files, ($path_and_file));
1.572     banghart 7401:         }
                   7402:     }
1.800     albertel 7403:     close(OUT);
1.574     banghart 7404:     return (@return_files);
1.572     banghart 7405: }
                   7406: 
1.745     raeburn  7407: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7408: 
1.745     raeburn  7409: sub get_portfile_permissions {
                   7410:     my ($domain,$user) = @_;
1.613     albertel 7411:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7412:     my ($tmp)=keys(%current_permissions);
                   7413:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7414:     return \%current_permissions;
                   7415: }
                   7416: 
                   7417: #---------------------------------------------Get portfolio file access controls
                   7418: 
1.749     raeburn  7419: sub get_access_controls {
1.745     raeburn  7420:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7421:     my %access;
                   7422:     my $real_file = $file;
                   7423:     $file =~ s/\.meta$//;
1.745     raeburn  7424:     if (defined($file)) {
1.749     raeburn  7425:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7426:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7427:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7428:             }
                   7429:         }
1.745     raeburn  7430:     } else {
1.749     raeburn  7431:         foreach my $key (keys(%{$current_permissions})) {
                   7432:             if ($key =~ /\0accesscontrol$/) {
                   7433:                 if (defined($group)) {
                   7434:                     if ($key !~ m-^\Q$group\E/-) {
                   7435:                         next;
                   7436:                     }
                   7437:                 }
                   7438:                 my ($fullpath) = split(/\0/,$key);
                   7439:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7440:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7441:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7442:                     }
                   7443:                 }
                   7444:             }
                   7445:         }
                   7446:     }
                   7447:     return %access;
                   7448: }
                   7449: 
                   7450: sub modify_access_controls {
                   7451:     my ($file_name,$changes,$domain,$user)=@_;
                   7452:     my ($outcome,$deloutcome);
                   7453:     my %store_permissions;
                   7454:     my %new_values;
                   7455:     my %new_control;
                   7456:     my %translation;
                   7457:     my @deletions = ();
                   7458:     my $now = time;
                   7459:     if (exists($$changes{'activate'})) {
                   7460:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7461:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7462:             my $numnew = scalar(@newitems);
                   7463:             for (my $i=0; $i<$numnew; $i++) {
                   7464:                 my $newkey = $newitems[$i];
                   7465:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7466:                 if ($newkey =~ /^\d+:/) { 
                   7467:                     $newkey =~ s/^(\d+)/$newid/;
                   7468:                     $translation{$1} = $newid;
                   7469:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7470:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7471:                     $translation{$1} = $newid;
                   7472:                 }
1.749     raeburn  7473:                 $new_values{$file_name."\0".$newkey} = 
                   7474:                                           $$changes{'activate'}{$newitems[$i]};
                   7475:                 $new_control{$newkey} = $now;
                   7476:             }
                   7477:         }
                   7478:     }
                   7479:     my %todelete;
                   7480:     my %changed_items;
                   7481:     foreach my $action ('delete','update') {
                   7482:         if (exists($$changes{$action})) {
                   7483:             if (ref($$changes{$action}) eq 'HASH') {
                   7484:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7485:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7486:                     if ($action eq 'delete') { 
                   7487:                         $todelete{$itemnum} = 1;
                   7488:                     } else {
                   7489:                         $changed_items{$itemnum} = $key;
                   7490:                     }
                   7491:                 }
1.745     raeburn  7492:             }
                   7493:         }
1.749     raeburn  7494:     }
                   7495:     # get lock on access controls for file.
                   7496:     my $lockhash = {
                   7497:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7498:                                                        ':'.$env{'user.domain'},
                   7499:                    }; 
                   7500:     my $tries = 0;
                   7501:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7502:    
                   7503:     while (($gotlock ne 'ok') && $tries <3) {
                   7504:         $tries ++;
                   7505:         sleep 1;
                   7506:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7507:     }
                   7508:     if ($gotlock eq 'ok') {
                   7509:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7510:         my ($tmp)=keys(%curr_permissions);
                   7511:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7512:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7513:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7514:             if (ref($curr_controls) eq 'HASH') {
                   7515:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7516:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7517:                     if (defined($todelete{$itemnum})) {
                   7518:                         push(@deletions,$file_name."\0".$control_item);
                   7519:                     } else {
                   7520:                         if (defined($changed_items{$itemnum})) {
                   7521:                             $new_control{$changed_items{$itemnum}} = $now;
                   7522:                             push(@deletions,$file_name."\0".$control_item);
                   7523:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7524:                         } else {
                   7525:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7526:                         }
                   7527:                     }
1.745     raeburn  7528:                 }
                   7529:             }
                   7530:         }
1.970     raeburn  7531:         my ($group);
                   7532:         if (&is_course($domain,$user)) {
                   7533:             ($group,my $file) = split(/\//,$file_name,2);
                   7534:         }
1.749     raeburn  7535:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7536:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7537:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7538:         #  remove lock
                   7539:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7540:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7541:         my $sqlresult =
1.970     raeburn  7542:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7543:                                     $group);
1.749     raeburn  7544:     } else {
                   7545:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7546:     }
1.749     raeburn  7547:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7548: }
                   7549: 
1.827     raeburn  7550: sub make_public_indefinitely {
                   7551:     my ($requrl) = @_;
                   7552:     my $now = time;
                   7553:     my $action = 'activate';
                   7554:     my $aclnum = 0;
                   7555:     if (&is_portfolio_url($requrl)) {
                   7556:         my (undef,$udom,$unum,$file_name,$group) =
                   7557:             &parse_portfolio_url($requrl);
                   7558:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7559:         my %access_controls = &get_access_controls($current_perms,
                   7560:                                                    $group,$file_name);
                   7561:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7562:             my ($num,$scope,$end,$start) = 
                   7563:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7564:             if ($scope eq 'public') {
                   7565:                 if ($start <= $now && $end == 0) {
                   7566:                     $action = 'none';
                   7567:                 } else {
                   7568:                     $action = 'update';
                   7569:                     $aclnum = $num;
                   7570:                 }
                   7571:                 last;
                   7572:             }
                   7573:         }
                   7574:         if ($action eq 'none') {
                   7575:              return 'ok';
                   7576:         } else {
                   7577:             my %changes;
                   7578:             my $newend = 0;
                   7579:             my $newstart = $now;
                   7580:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7581:             $changes{$action}{$newkey} = {
                   7582:                 type => 'public',
                   7583:                 time => {
                   7584:                     start => $newstart,
                   7585:                     end   => $newend,
                   7586:                 },
                   7587:             };
                   7588:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7589:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7590:             return $outcome;
                   7591:         }
                   7592:     } else {
                   7593:         return 'invalid';
                   7594:     }
                   7595: }
                   7596: 
1.745     raeburn  7597: #------------------------------------------------------Get Marked as Read Only
                   7598: 
                   7599: sub get_marked_as_readonly {
                   7600:     my ($domain,$user,$what,$group) = @_;
                   7601:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7602:     my @readonly_files;
1.629     banghart 7603:     my $cmp1=$what;
                   7604:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7605:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7606:         if (defined($group)) {
                   7607:             if ($file_name !~ m-^\Q$group\E/-) {
                   7608:                 next;
                   7609:             }
                   7610:         }
1.561     banghart 7611:         if (ref($value) eq "ARRAY"){
                   7612:             foreach my $stored_what (@{$value}) {
1.629     banghart 7613:                 my $cmp2=$stored_what;
1.759     albertel 7614:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7615:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7616:                 }
1.629     banghart 7617:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7618:                     push(@readonly_files, $file_name);
1.745     raeburn  7619:                     last;
1.563     banghart 7620:                 } elsif (!defined($what)) {
                   7621:                     push(@readonly_files, $file_name);
1.745     raeburn  7622:                     last;
1.561     banghart 7623:                 }
                   7624:             }
1.745     raeburn  7625:         }
1.561     banghart 7626:     }
                   7627:     return @readonly_files;
                   7628: }
1.577     banghart 7629: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7630: 
1.577     banghart 7631: sub get_marked_as_readonly_hash {
1.745     raeburn  7632:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7633:     my %readonly_files;
1.745     raeburn  7634:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7635:         if (defined($group)) {
                   7636:             if ($file_name !~ m-^\Q$group\E/-) {
                   7637:                 next;
                   7638:             }
                   7639:         }
1.577     banghart 7640:         if (ref($value) eq "ARRAY"){
                   7641:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7642:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7643:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7644:                         if ($lock_descriptor eq 'graded') {
                   7645:                             $readonly_files{$file_name} = 'graded';
                   7646:                         } elsif ($lock_descriptor eq 'handback') {
                   7647:                             $readonly_files{$file_name} = 'handback';
                   7648:                         } else {
                   7649:                             if (!exists($readonly_files{$file_name})) {
                   7650:                                 $readonly_files{$file_name} = 'locked';
                   7651:                             }
                   7652:                         }
1.745     raeburn  7653:                     }
1.750     banghart 7654:                 } 
1.577     banghart 7655:             }
                   7656:         } 
                   7657:     }
                   7658:     return %readonly_files;
                   7659: }
1.559     banghart 7660: # ------------------------------------------------------------ Unmark as Read Only
                   7661: 
                   7662: sub unmark_as_readonly {
1.629     banghart 7663:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7664:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7665:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7666:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7667:     my $symb_crs = $what;
                   7668:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7669:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7670:     my ($tmp)=keys(%current_permissions);
                   7671:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7672:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7673:     foreach my $file (@readonly_files) {
1.759     albertel 7674: 	my $clean_file = &declutter_portfile($file);
                   7675: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7676: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7677:         my @new_locks;
                   7678:         my @del_keys;
                   7679:         if (ref($current_locks) eq "ARRAY"){
                   7680:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7681:                 my $compare=$locker;
1.749     raeburn  7682:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7683:                     $compare=join('',@{$locker});
1.746     raeburn  7684:                     if ($compare ne $symb_crs) {
                   7685:                         push(@new_locks, $locker);
                   7686:                     }
1.563     banghart 7687:                 }
                   7688:             }
1.650     albertel 7689:             if (scalar(@new_locks) > 0) {
1.563     banghart 7690:                 $current_permissions{$file} = \@new_locks;
                   7691:             } else {
                   7692:                 push(@del_keys, $file);
1.613     albertel 7693:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7694:                 delete($current_permissions{$file});
1.563     banghart 7695:             }
                   7696:         }
1.561     banghart 7697:     }
1.613     albertel 7698:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7699:     return;
                   7700: }
1.512     banghart 7701: 
1.17      www      7702: # ------------------------------------------------------------ Directory lister
                   7703: 
                   7704: sub dirlist {
1.955     raeburn  7705:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7706:     $uri=~s/^\///;
                   7707:     $uri=~s/\/$//;
1.253     stredwic 7708:     my ($udom, $uname);
1.955     raeburn  7709:     if ($getuserdir) {
1.253     stredwic 7710:         $udom = $userdomain;
                   7711:         $uname = $username;
1.955     raeburn  7712:     } else {
                   7713:         (undef,$udom,$uname)=split(/\//,$uri);
                   7714:         if(defined($userdomain)) {
                   7715:             $udom = $userdomain;
                   7716:         }
                   7717:         if(defined($username)) {
                   7718:             $uname = $username;
                   7719:         }
1.253     stredwic 7720:     }
1.955     raeburn  7721:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7722: 
1.955     raeburn  7723:     $dirRoot = $perlvar{'lonDocRoot'};
                   7724:     if (defined($getpropath)) {
                   7725:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7726:         $dirRoot =~ s/\/$//;
1.955     raeburn  7727:     } elsif (defined($getuserdir)) {
                   7728:         my $subdir=$uname.'__';
                   7729:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7730:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7731:                    ."/$udom/$subdir/$uname";
                   7732:     } elsif (defined($alternateRoot)) {
                   7733:         $dirRoot = $alternateRoot;
1.751     banghart 7734:     }
1.253     stredwic 7735: 
                   7736:     if($udom) {
                   7737:         if($uname) {
1.955     raeburn  7738:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7739:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7740:                               .':'.&escape($uname).':'.&escape($udom),
                   7741:                               &homeserver($uname,$udom));
                   7742:             if ($listing eq 'unknown_cmd') {
                   7743:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7744:                                   &homeserver($uname,$udom));
                   7745:             } else {
                   7746:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7747:             }
1.605     matthew  7748:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7749:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7750: 				  &homeserver($uname,$udom));
1.605     matthew  7751:                 @listing_results = split(/:/,$listing);
                   7752:             } else {
                   7753:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7754:             }
                   7755:             return @listing_results;
1.955     raeburn  7756:         } elsif(!$alternateRoot) {
1.800     albertel 7757:             my %allusers;
1.841     albertel 7758: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7759:  	    foreach my $tryserver (keys(%servers)) {
                   7760:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7761:                                   &escape($udom),$tryserver);
                   7762:                 if ($listing eq 'unknown_cmd') {
                   7763: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7764: 				      $udom, $tryserver);
                   7765:                 } else {
                   7766:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7767:                 }
1.841     albertel 7768: 		if ($listing eq 'unknown_cmd') {
                   7769: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7770: 				      $udom, $tryserver);
                   7771: 		    @listing_results = split(/:/,$listing);
                   7772: 		} else {
                   7773: 		    @listing_results =
                   7774: 			map { &unescape($_); } split(/:/,$listing);
                   7775: 		}
                   7776: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7777: 		    $listing_results[0] ne 'empty'       &&
                   7778: 		    $listing_results[0] ne 'con_lost') {
                   7779: 		    foreach my $line (@listing_results) {
                   7780: 			my ($entry) = split(/&/,$line,2);
                   7781: 			$allusers{$entry} = 1;
                   7782: 		    }
                   7783: 		}
1.253     stredwic 7784:             }
                   7785:             my $alluserstr='';
1.800     albertel 7786:             foreach my $user (sort(keys(%allusers))) {
                   7787:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7788:             }
                   7789:             $alluserstr=~s/:$//;
                   7790:             return split(/:/,$alluserstr);
                   7791:         } else {
1.800     albertel 7792:             return ('missing user name');
1.253     stredwic 7793:         }
1.955     raeburn  7794:     } elsif(!defined($getpropath)) {
1.841     albertel 7795:         my @all_domains = sort(&all_domains());
1.955     raeburn  7796:         foreach my $domain (@all_domains) {
                   7797:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7798:         }
                   7799:         return @all_domains;
                   7800:     } else {
1.800     albertel 7801:         return ('missing domain');
1.275     stredwic 7802:     }
                   7803: }
                   7804: 
                   7805: # --------------------------------------------- GetFileTimestamp
                   7806: # This function utilizes dirlist and returns the date stamp for
                   7807: # when it was last modified.  It will also return an error of -1
                   7808: # if an error occurs
                   7809: 
                   7810: sub GetFileTimestamp {
1.955     raeburn  7811:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7812:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7813:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7814:     my ($fileStat) = 
                   7815:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7816:                                  undef,$getuserdir);
1.275     stredwic 7817:     my @stats = split('&', $fileStat);
                   7818:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7819:         # @stats contains first the filename, then the stat output
                   7820:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7821:     } else {
                   7822:         return -1;
1.253     stredwic 7823:     }
1.26      www      7824: }
                   7825: 
1.712     albertel 7826: sub stat_file {
                   7827:     my ($uri) = @_;
1.787     albertel 7828:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7829: 
1.955     raeburn  7830:     my ($udom,$uname,$file);
1.712     albertel 7831:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7832: 	($udom,$uname,$file) =
1.811     albertel 7833: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7834: 	$file = 'userfiles/'.$file;
                   7835:     }
                   7836:     if ($uri =~ m-^/res/-) {
                   7837: 	($udom,$uname) = 
1.807     albertel 7838: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7839: 	$file = $uri;
                   7840:     }
                   7841: 
                   7842:     if (!$udom || !$uname || !$file) {
                   7843: 	# unable to handle the uri
                   7844: 	return ();
                   7845:     }
1.956     raeburn  7846:     my $getpropath;
                   7847:     if ($file =~ /^userfiles\//) {
                   7848:         $getpropath = 1;
                   7849:     }
1.955     raeburn  7850:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7851:     my @stats = split('&', $result);
1.721     banghart 7852:     
1.712     albertel 7853:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7854: 	shift(@stats); #filename is first
                   7855: 	return @stats;
                   7856:     }
                   7857:     return ();
                   7858: }
                   7859: 
1.26      www      7860: # -------------------------------------------------------- Value of a Condition
                   7861: 
1.713     albertel 7862: # gets the value of a specific preevaluated condition
                   7863: #    stored in the string  $env{user.state.<cid>}
                   7864: # or looks up a condition reference in the bighash and if if hasn't
                   7865: # already been evaluated recurses into docondval to get the value of
                   7866: # the condition, then memoizing it to 
                   7867: #   $env{user.state.<cid>.<condition>}
1.40      www      7868: sub directcondval {
                   7869:     my $number=shift;
1.620     albertel 7870:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7871: 	&Apache::lonuserstate::evalstate();
                   7872:     }
1.713     albertel 7873:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7874: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7875:     } elsif ($number =~ /^_/) {
                   7876: 	my $sub_condition;
                   7877: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7878: 		&GDBM_READER(),0640)) {
                   7879: 	    $sub_condition=$bighash{'conditions'.$number};
                   7880: 	    untie(%bighash);
                   7881: 	}
                   7882: 	my $value = &docondval($sub_condition);
1.949     raeburn  7883: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7884: 	return $value;
                   7885:     }
1.620     albertel 7886:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7887:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7888:     } else {
                   7889:        return 2;
                   7890:     }
                   7891: }
                   7892: 
1.713     albertel 7893: # get the collection of conditions for this resource
1.26      www      7894: sub condval {
                   7895:     my $condidx=shift;
1.54      www      7896:     my $allpathcond='';
1.713     albertel 7897:     foreach my $cond (split(/\|/,$condidx)) {
                   7898: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7899: 	    $allpathcond.=
                   7900: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7901: 	}
1.191     harris41 7902:     }
1.54      www      7903:     $allpathcond=~s/\|$//;
1.713     albertel 7904:     return &docondval($allpathcond);
                   7905: }
                   7906: 
                   7907: #evaluates an expression of conditions
                   7908: sub docondval {
                   7909:     my ($allpathcond) = @_;
                   7910:     my $result=0;
                   7911:     if ($env{'request.course.id'}
                   7912: 	&& defined($allpathcond)) {
                   7913: 	my $operand='|';
                   7914: 	my @stack;
                   7915: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7916: 	    if ($chunk eq '(') {
                   7917: 		push @stack,($operand,$result);
                   7918: 	    } elsif ($chunk eq ')') {
                   7919: 		my $before=pop @stack;
                   7920: 		if (pop @stack eq '&') {
                   7921: 		    $result=$result>$before?$before:$result;
                   7922: 		} else {
                   7923: 		    $result=$result>$before?$result:$before;
                   7924: 		}
                   7925: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7926: 		$operand=$chunk;
                   7927: 	    } else {
                   7928: 		my $new=directcondval($chunk);
                   7929: 		if ($operand eq '&') {
                   7930: 		    $result=$result>$new?$new:$result;
                   7931: 		} else {
                   7932: 		    $result=$result>$new?$result:$new;
                   7933: 		}
                   7934: 	    }
                   7935: 	}
1.26      www      7936:     }
                   7937:     return $result;
1.421     albertel 7938: }
                   7939: 
                   7940: # ---------------------------------------------------- Devalidate courseresdata
                   7941: 
                   7942: sub devalidatecourseresdata {
                   7943:     my ($coursenum,$coursedomain)=@_;
                   7944:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7945:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7946: }
                   7947: 
1.763     www      7948: 
1.200     www      7949: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7950: #
                   7951: #  Parameters:
                   7952: #      $coursenum    - Number of the course.
                   7953: #      $coursedomain - Domain at which the course was created.
                   7954: #  Returns:
                   7955: #     A hash of the course parameters along (I think) with timestamps
                   7956: #     and version info.
1.877     foxr     7957: 
1.624     albertel 7958: sub get_courseresdata {
                   7959:     my ($coursenum,$coursedomain)=@_;
1.200     www      7960:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7961:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7962:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7963:     my %dumpreply;
1.417     albertel 7964:     unless (defined($cached)) {
1.624     albertel 7965: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7966: 	$result=\%dumpreply;
1.251     albertel 7967: 	my ($tmp) = keys(%dumpreply);
                   7968: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7969: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7970: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7971: 	    return $tmp;
1.416     albertel 7972: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7973: 	    $result=undef;
1.599     albertel 7974: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7975: 	}
                   7976:     }
1.624     albertel 7977:     return $result;
                   7978: }
                   7979: 
1.633     albertel 7980: sub devalidateuserresdata {
                   7981:     my ($uname,$udom)=@_;
                   7982:     my $hashid="$udom:$uname";
                   7983:     &devalidate_cache_new('userres',$hashid);
                   7984: }
                   7985: 
1.624     albertel 7986: sub get_userresdata {
                   7987:     my ($uname,$udom)=@_;
                   7988:     #most student don\'t have any data set, check if there is some data
                   7989:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7990: 
                   7991:     my $hashid="$udom:$uname";
                   7992:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7993:     if (!defined($cached)) {
                   7994: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7995: 	$result=\%resourcedata;
                   7996: 	&do_cache_new('userres',$hashid,$result,600);
                   7997:     }
                   7998:     my ($tmp)=keys(%$result);
                   7999:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8000: 	return $result;
                   8001:     }
                   8002:     #error 2 occurs when the .db doesn't exist
                   8003:     if ($tmp!~/error: 2 /) {
1.672     albertel 8004: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8005: 		 " Trying to get resource data for ".
                   8006: 		 $uname." at ".$udom.": ".
                   8007: 		 $tmp."</font>");
                   8008:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8009: 	#&EXT_cache_set($udom,$uname);
                   8010: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8011: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8012:     }
                   8013:     return $tmp;
                   8014: }
1.879     foxr     8015: #----------------------------------------------- resdata - return resource data
                   8016: #  Purpose:
                   8017: #    Return resource data for either users or for a course.
                   8018: #  Parameters:
                   8019: #     $name      - Course/user name.
                   8020: #     $domain    - Name of the domain the user/course is registered on.
                   8021: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8022: #     @which     - Array of names of resources desired.
                   8023: #  Returns:
                   8024: #     The value of the first reasource in @which that is found in the
                   8025: #     resource hash.
                   8026: #  Exceptional Conditions:
                   8027: #     If the $type passed in is not valid (not the string 'course' or 
                   8028: #     'user', an undefined  reference is returned.
                   8029: #     If none of the resources are found, an undef is returned
1.624     albertel 8030: sub resdata {
                   8031:     my ($name,$domain,$type,@which)=@_;
                   8032:     my $result;
                   8033:     if ($type eq 'course') {
                   8034: 	$result=&get_courseresdata($name,$domain);
                   8035:     } elsif ($type eq 'user') {
                   8036: 	$result=&get_userresdata($name,$domain);
                   8037:     }
                   8038:     if (!ref($result)) { return $result; }    
1.251     albertel 8039:     foreach my $item (@which) {
1.927     albertel 8040: 	if (defined($result->{$item->[0]})) {
                   8041: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8042: 	}
1.250     albertel 8043:     }
1.291     albertel 8044:     return undef;
1.200     www      8045: }
                   8046: 
1.379     matthew  8047: #
                   8048: # EXT resource caching routines
                   8049: #
                   8050: 
                   8051: sub clear_EXT_cache_status {
1.383     albertel 8052:     &delenv('cache.EXT.');
1.379     matthew  8053: }
                   8054: 
                   8055: sub EXT_cache_status {
                   8056:     my ($target_domain,$target_user) = @_;
1.383     albertel 8057:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8058:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8059:         # We know already the user has no data
                   8060:         return 1;
                   8061:     } else {
                   8062:         return 0;
                   8063:     }
                   8064: }
                   8065: 
                   8066: sub EXT_cache_set {
                   8067:     my ($target_domain,$target_user) = @_;
1.383     albertel 8068:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8069:     #&appenv({$cachename => time});
1.379     matthew  8070: }
                   8071: 
1.28      www      8072: # --------------------------------------------------------- Value of a Variable
1.58      www      8073: sub EXT {
1.715     albertel 8074: 
1.395     albertel 8075:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8076:     unless ($varname) { return ''; }
1.218     albertel 8077:     #get real user name/domain, courseid and symb
                   8078:     my $courseid;
1.359     albertel 8079:     my $publicuser;
1.427     www      8080:     if ($symbparm) {
                   8081: 	$symbparm=&get_symb_from_alias($symbparm);
                   8082:     }
1.218     albertel 8083:     if (!($uname && $udom)) {
1.790     albertel 8084:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8085:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8086:     } else {
1.620     albertel 8087: 	$courseid=$env{'request.course.id'};
1.218     albertel 8088:     }
1.48      www      8089:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8090:     my $rest;
1.320     albertel 8091:     if (defined($therest[0])) {
1.48      www      8092:        $rest=join('.',@therest);
                   8093:     } else {
                   8094:        $rest='';
                   8095:     }
1.320     albertel 8096: 
1.57      www      8097:     my $qualifierrest=$qualifier;
                   8098:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8099:     my $spacequalifierrest=$space;
                   8100:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8101:     if ($realm eq 'user') {
1.48      www      8102: # --------------------------------------------------------------- user.resource
                   8103: 	if ($space eq 'resource') {
1.651     albertel 8104: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8105: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8106: 		 &&
1.744     albertel 8107: 		 ($symbparm eq &symbread()) ) {	
                   8108: 		# if we are in the middle of processing the resource the
                   8109: 		# get the value we are planning on committing
                   8110:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8111:                     return $Apache::lonhomework::results{$qualifierrest};
                   8112:                 } else {
                   8113:                     return $Apache::lonhomework::history{$qualifierrest};
                   8114:                 }
1.335     albertel 8115: 	    } else {
1.359     albertel 8116: 		my %restored;
1.620     albertel 8117: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8118: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8119: 		} else {
                   8120: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8121: 		}
1.335     albertel 8122: 		return $restored{$qualifierrest};
                   8123: 	    }
1.48      www      8124: # ----------------------------------------------------------------- user.access
                   8125:         } elsif ($space eq 'access') {
1.218     albertel 8126: 	    # FIXME - not supporting calls for a specific user
1.48      www      8127:             return &allowed($qualifier,$rest);
                   8128: # ------------------------------------------ user.preferences, user.environment
                   8129:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8130: 	    if (($uname eq $env{'user.name'}) &&
                   8131: 		($udom eq $env{'user.domain'})) {
                   8132: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8133: 	    } else {
1.359     albertel 8134: 		my %returnhash;
                   8135: 		if (!$publicuser) {
                   8136: 		    %returnhash=&userenvironment($udom,$uname,
                   8137: 						 $qualifierrest);
                   8138: 		}
1.218     albertel 8139: 		return $returnhash{$qualifierrest};
                   8140: 	    }
1.48      www      8141: # ----------------------------------------------------------------- user.course
                   8142:         } elsif ($space eq 'course') {
1.218     albertel 8143: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8144:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8145: # ------------------------------------------------------------------- user.role
                   8146:         } elsif ($space eq 'role') {
1.218     albertel 8147: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8148:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8149:             if ($qualifier eq 'value') {
                   8150: 		return $role;
                   8151:             } elsif ($qualifier eq 'extent') {
                   8152:                 return $where;
                   8153:             }
                   8154: # ----------------------------------------------------------------- user.domain
                   8155:         } elsif ($space eq 'domain') {
1.218     albertel 8156:             return $udom;
1.48      www      8157: # ------------------------------------------------------------------- user.name
                   8158:         } elsif ($space eq 'name') {
1.218     albertel 8159:             return $uname;
1.48      www      8160: # ---------------------------------------------------- Any other user namespace
1.29      www      8161:         } else {
1.359     albertel 8162: 	    my %reply;
                   8163: 	    if (!$publicuser) {
                   8164: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8165: 	    }
                   8166: 	    return $reply{$qualifierrest};
1.48      www      8167:         }
1.236     www      8168:     } elsif ($realm eq 'query') {
                   8169: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8170:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8171: 						[$spacequalifierrest]);
1.620     albertel 8172: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8173:    } elsif ($realm eq 'request') {
1.48      www      8174: # ------------------------------------------------------------- request.browser
                   8175:         if ($space eq 'browser') {
1.430     www      8176: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8177: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8178: 		    return 1;
                   8179: 		} else {
                   8180: 		    return 0;
                   8181: 		}
                   8182: 	    } else {
1.620     albertel 8183: 		return $env{'browser.'.$qualifier};
1.430     www      8184: 	    }
1.57      www      8185: # ------------------------------------------------------------ request.filename
                   8186:         } else {
1.620     albertel 8187:             return $env{'request.'.$spacequalifierrest};
1.29      www      8188:         }
1.28      www      8189:     } elsif ($realm eq 'course') {
1.48      www      8190: # ---------------------------------------------------------- course.description
1.620     albertel 8191:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8192:     } elsif ($realm eq 'resource') {
1.165     www      8193: 
1.620     albertel 8194: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8195: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8196: 	}
1.693     albertel 8197: 
                   8198: 	if ($space eq 'title') {
                   8199: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8200: 	    return &gettitle($symbparm);
                   8201: 	}
                   8202: 	
                   8203: 	if ($space eq 'map') {
                   8204: 	    my ($map) = &decode_symb($symbparm);
                   8205: 	    return &symbread($map);
                   8206: 	}
1.905     albertel 8207: 	if ($space eq 'filename') {
                   8208: 	    if ($symbparm) {
                   8209: 		return &clutter((&decode_symb($symbparm))[2]);
                   8210: 	    }
                   8211: 	    return &hreflocation('',$env{'request.filename'});
                   8212: 	}
1.693     albertel 8213: 
                   8214: 	my ($section, $group, @groups);
1.593     albertel 8215: 	my ($courselevelm,$courselevel);
1.539     albertel 8216: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8217: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8218: 
1.218     albertel 8219: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8220: 
1.60      www      8221: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8222: 	    my $symbp=$symbparm;
1.735     albertel 8223: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8224: 
                   8225: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8226: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8227: 
1.620     albertel 8228: 	    if (($env{'user.name'} eq $uname) &&
                   8229: 		($env{'user.domain'} eq $udom)) {
                   8230: 		$section=$env{'request.course.sec'};
1.733     raeburn  8231:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8232:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8233: 	    } else {
1.539     albertel 8234: 		if (! defined($usection)) {
1.551     albertel 8235: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8236: 		} else {
                   8237: 		    $section = $usection;
                   8238: 		}
1.733     raeburn  8239:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8240: 	    }
                   8241: 
                   8242: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8243: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8244: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8245: 
1.593     albertel 8246: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8247: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8248: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8249: 
1.60      www      8250: # ----------------------------------------------------------- first, check user
1.624     albertel 8251: 
                   8252: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8253: 				       ([$courselevelr,'resource'],
                   8254: 					[$courselevelm,'map'     ],
                   8255: 					[$courselevel, 'course'  ]));
1.931     albertel 8256: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8257: 
1.594     albertel 8258: # ------------------------------------------------ second, check some of course
1.684     raeburn  8259:             my $coursereply;
1.691     raeburn  8260:             if (@groups > 0) {
                   8261:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8262:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8263:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8264:             }
1.96      www      8265: 
1.684     raeburn  8266: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8267: 				  $env{'course.'.$courseid.'.domain'},
                   8268: 				  'course',
                   8269: 				  ([$seclevelr,   'resource'],
                   8270: 				   [$seclevelm,   'map'     ],
                   8271: 				   [$seclevel,    'course'  ],
                   8272: 				   [$courselevelr,'resource']));
                   8273: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8274: 
1.60      www      8275: # ------------------------------------------------------ third, check map parms
1.218     albertel 8276: 	    my %parmhash=();
                   8277: 	    my $thisparm='';
                   8278: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8279: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8280: 		    &GDBM_READER(),0640)) {
1.218     albertel 8281: 		$thisparm=$parmhash{$symbparm};
                   8282: 		untie(%parmhash);
                   8283: 	    }
1.927     albertel 8284: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8285: 	}
1.594     albertel 8286: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8287: 
1.218     albertel 8288: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8289: 	my $filename;
                   8290: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8291: 	if ($symbparm) {
1.409     www      8292: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8293: 	} else {
1.620     albertel 8294: 	    $filename=$env{'request.filename'};
1.282     albertel 8295: 	}
                   8296: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8297: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8298: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8299: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8300: 
1.927     albertel 8301: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8302: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8303: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8304: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8305: 				     $env{'course.'.$courseid.'.domain'},
                   8306: 				     'course',
1.927     albertel 8307: 				     ([$courselevelm,'map'   ],
                   8308: 				      [$courselevel, 'course']));
                   8309: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8310: 	}
1.145     www      8311: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8312: 	unless ($space eq '0') {
1.336     albertel 8313: 	    my @parts=split(/_/,$space);
                   8314: 	    my $id=pop(@parts);
                   8315: 	    my $part=join('_',@parts);
                   8316: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8317: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8318: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8319: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8320: 	}
1.395     albertel 8321: 	if ($recurse) { return undef; }
                   8322: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8323: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8324: # ---------------------------------------------------- Any other user namespace
                   8325:     } elsif ($realm eq 'environment') {
                   8326: # ----------------------------------------------------------------- environment
1.620     albertel 8327: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8328: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8329: 	} else {
1.770     albertel 8330: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8331: 		return '';
                   8332: 	    }
1.219     albertel 8333: 	    my %returnhash=&userenvironment($udom,$uname,
                   8334: 					    $spacequalifierrest);
                   8335: 	    return $returnhash{$spacequalifierrest};
                   8336: 	}
1.28      www      8337:     } elsif ($realm eq 'system') {
1.48      www      8338: # ----------------------------------------------------------------- system.time
                   8339: 	if ($space eq 'time') {
                   8340: 	    return time;
                   8341:         }
1.696     albertel 8342:     } elsif ($realm eq 'server') {
                   8343: # ----------------------------------------------------------------- system.time
                   8344: 	if ($space eq 'name') {
                   8345: 	    return $ENV{'SERVER_NAME'};
                   8346:         }
1.28      www      8347:     }
1.48      www      8348:     return '';
1.61      www      8349: }
                   8350: 
1.927     albertel 8351: sub get_reply {
                   8352:     my ($reply_value) = @_;
1.940     raeburn  8353:     if (ref($reply_value) eq 'ARRAY') {
                   8354:         if (wantarray) {
                   8355: 	    return @$reply_value;
                   8356:         }
                   8357:         return $reply_value->[0];
                   8358:     } else {
                   8359:         return $reply_value;
1.927     albertel 8360:     }
                   8361: }
                   8362: 
1.691     raeburn  8363: sub check_group_parms {
                   8364:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8365:     my @groupitems = ();
                   8366:     my $resultitem;
1.927     albertel 8367:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8368:     foreach my $group (@{$groups}) {
                   8369:         foreach my $level (@levels) {
1.927     albertel 8370:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8371:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8372:         }
                   8373:     }
                   8374:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8375:                             $env{'course.'.$courseid.'.domain'},
                   8376:                                      'course',@groupitems);
                   8377:     return $coursereply;
                   8378: }
                   8379: 
                   8380: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8381:     my ($courseid,@groups) = @_;
                   8382:     @groups = sort(@groups);
1.691     raeburn  8383:     return @groups;
                   8384: }
                   8385: 
1.395     albertel 8386: sub packages_tab_default {
                   8387:     my ($uri,$varname)=@_;
                   8388:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8389: 
                   8390:     my (@extension,@specifics,$do_default);
                   8391:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8392: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8393: 	if ($pack_type eq 'default') {
                   8394: 	    $do_default=1;
                   8395: 	} elsif ($pack_type eq 'extension') {
                   8396: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8397: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8398: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8399: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8400: 	}
                   8401:     }
                   8402:     # first look for a package that matches the requested part id
                   8403:     foreach my $package (@specifics) {
                   8404: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8405: 	next if ($pack_part ne $part);
                   8406: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8407: 	    return $packagetab{"$pack_type&$name&default"};
                   8408: 	}
                   8409:     }
                   8410:     # look for any possible matching non extension_ package
                   8411:     foreach my $package (@specifics) {
                   8412: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8413: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8414: 	    return $packagetab{"$pack_type&$name&default"};
                   8415: 	}
1.585     albertel 8416: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8417: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8418: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8419: 	}
                   8420:     }
1.738     albertel 8421:     # look for any posible extension_ match
                   8422:     foreach my $package (@extension) {
                   8423: 	my ($package,$pack_type)=@{$package};
                   8424: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8425: 	    return $packagetab{"$pack_type&$name&default"};
                   8426: 	}
                   8427: 	if (defined($packagetab{$package."&$name&default"})) {
                   8428: 	    return $packagetab{$package."&$name&default"};
                   8429: 	}
                   8430:     }
                   8431:     # look for a global default setting
                   8432:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8433: 	return $packagetab{"default&$name&default"};
                   8434:     }
1.395     albertel 8435:     return undef;
                   8436: }
                   8437: 
1.334     albertel 8438: sub add_prefix_and_part {
                   8439:     my ($prefix,$part)=@_;
                   8440:     my $keyroot;
                   8441:     if (defined($prefix) && $prefix !~ /^__/) {
                   8442: 	# prefix that has a part already
                   8443: 	$keyroot=$prefix;
                   8444:     } elsif (defined($prefix)) {
                   8445: 	# prefix that is missing a part
                   8446: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8447:     } else {
                   8448: 	# no prefix at all
                   8449: 	if (defined($part)) { $keyroot='_'.$part; }
                   8450:     }
                   8451:     return $keyroot;
                   8452: }
                   8453: 
1.71      www      8454: # ---------------------------------------------------------------- Get metadata
                   8455: 
1.599     albertel 8456: my %metaentry;
1.71      www      8457: sub metadata {
1.176     www      8458:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8459:     $uri=&declutter($uri);
1.288     albertel 8460:     # if it is a non metadata possible uri return quickly
1.529     albertel 8461:     if (($uri eq '') || 
                   8462: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8463: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8464:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8465: 	return undef;
                   8466:     }
                   8467:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8468: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8469: 	return undef;
1.288     albertel 8470:     }
1.73      www      8471:     my $filename=$uri;
                   8472:     $uri=~s/\.meta$//;
1.172     www      8473: #
                   8474: # Is the metadata already cached?
1.177     www      8475: # Look at timestamp of caching
1.172     www      8476: # Everything is cached by the main uri, libraries are never directly cached
                   8477: #
1.428     albertel 8478:     if (!defined($liburi)) {
1.599     albertel 8479: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8480: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8481:     }
                   8482:     {
1.172     www      8483: #
                   8484: # Is this a recursive call for a library?
                   8485: #
1.599     albertel 8486: #	if (! exists($metacache{$uri})) {
                   8487: #	    $metacache{$uri}={};
                   8488: #	}
1.924     albertel 8489: 	my $cachetime = 60*60;
1.171     www      8490:         if ($liburi) {
                   8491: 	    $liburi=&declutter($liburi);
                   8492:             $filename=$liburi;
1.401     bowersj2 8493:         } else {
1.599     albertel 8494: 	    &devalidate_cache_new('meta',$uri);
                   8495: 	    undef(%metaentry);
1.401     bowersj2 8496: 	}
1.140     www      8497:         my %metathesekeys=();
1.73      www      8498:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8499: 	my $metastring;
1.924     albertel 8500: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8501: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8502: 	    $metastring = 
1.929     albertel 8503: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8504: 					  ('grade_target' => 'meta'));
                   8505: 	    $cachetime = 1; # only want this cached in the child not long term
                   8506: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8507: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8508: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8509: 	    $metastring=&getfile($file);
1.489     albertel 8510: 	}
1.208     albertel 8511:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8512:         my $token;
1.140     www      8513:         undef %metathesekeys;
1.71      www      8514:         while ($token=$parser->get_token) {
1.339     albertel 8515: 	    if ($token->[0] eq 'S') {
                   8516: 		if (defined($token->[2]->{'package'})) {
1.172     www      8517: #
                   8518: # This is a package - get package info
                   8519: #
1.339     albertel 8520: 		    my $package=$token->[2]->{'package'};
                   8521: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8522: 		    if (defined($token->[2]->{'id'})) { 
                   8523: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8524: 		    }
1.599     albertel 8525: 		    if ($metaentry{':packages'}) {
                   8526: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8527: 		    } else {
1.599     albertel 8528: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8529: 		    }
1.736     albertel 8530: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8531: 			my $part=$keyroot;
                   8532: 			$part=~s/^\_//;
1.736     albertel 8533: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8534: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8535: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8536: 			    # ignore package.tab specified default values
                   8537:                             # here &package_tab_default() will fetch those
                   8538: 			    if ($subp eq 'default') { next; }
1.736     albertel 8539: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8540: 			    my $unikey;
                   8541: 			    if ($pack =~ /_0$/) {
                   8542: 				$unikey='parameter_0_'.$name;
                   8543: 				$part=0;
                   8544: 			    } else {
                   8545: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8546: 			    }
1.339     albertel 8547: 			    if ($subp eq 'display') {
                   8548: 				$value.=' [Part: '.$part.']';
                   8549: 			    }
1.599     albertel 8550: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8551: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8552: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8553: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8554: 			    }
1.599     albertel 8555: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8556: 				$metaentry{':'.$unikey}=
                   8557: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8558: 			    }
1.339     albertel 8559: 			}
                   8560: 		    }
                   8561: 		} else {
1.172     www      8562: #
                   8563: # This is not a package - some other kind of start tag
1.339     albertel 8564: #
                   8565: 		    my $entry=$token->[1];
                   8566: 		    my $unikey;
                   8567: 		    if ($entry eq 'import') {
                   8568: 			$unikey='';
                   8569: 		    } else {
                   8570: 			$unikey=$entry;
                   8571: 		    }
                   8572: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8573: 
                   8574: 		    if (defined($token->[2]->{'id'})) { 
                   8575: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8576: 		    }
1.175     www      8577: 
1.339     albertel 8578: 		    if ($entry eq 'import') {
1.175     www      8579: #
                   8580: # Importing a library here
1.339     albertel 8581: #
                   8582: 			if ($depthcount<20) {
                   8583: 			    my $location=$parser->get_text('/import');
                   8584: 			    my $dir=$filename;
                   8585: 			    $dir=~s|[^/]*$||;
                   8586: 			    $location=&filelocation($dir,$location);
1.736     albertel 8587: 			    my $metadata = 
                   8588: 				&metadata($uri,'keys', $location,$unikey,
                   8589: 					  $depthcount+1);
                   8590: 			    foreach my $meta (split(',',$metadata)) {
                   8591: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8592: 				$metathesekeys{$meta}=1;
1.339     albertel 8593: 			    }
                   8594: 			}
                   8595: 		    } else { 
                   8596: 			
                   8597: 			if (defined($token->[2]->{'name'})) { 
                   8598: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8599: 			}
                   8600: 			$metathesekeys{$unikey}=1;
1.736     albertel 8601: 			foreach my $param (@{$token->[3]}) {
                   8602: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8603: 				$token->[2]->{$param};
1.339     albertel 8604: 			}
                   8605: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8606: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8607: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8608: 		 # only ws inside the tag, and not in default, so use default
                   8609: 		 # as value
1.599     albertel 8610: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8611: 			} elsif ( $internaltext =~ /\S/ ) {
                   8612: 		  # something interesting inside the tag
                   8613: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8614: 			} else {
1.908     albertel 8615: 		  # no interesting values, don't set a default
1.339     albertel 8616: 			}
1.172     www      8617: # end of not-a-package not-a-library import
1.339     albertel 8618: 		    }
1.172     www      8619: # end of not-a-package start tag
1.339     albertel 8620: 		}
1.172     www      8621: # the next is the end of "start tag"
1.339     albertel 8622: 	    }
                   8623: 	}
1.483     albertel 8624: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8625: 	$extension = lc($extension);
                   8626: 	if ($extension eq 'htm') { $extension='html'; }
                   8627: 
1.737     albertel 8628: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8629: 	    #no specific packages #how's our extension
                   8630: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8631: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8632: 					 \%metathesekeys);
                   8633: 	}
1.883     albertel 8634: 
                   8635: 	if (!exists($metaentry{':packages'})
                   8636: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8637: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8638: 		#no specific packages well let's get default then
                   8639: 		if ($key!~/^default&/) { next; }
1.488     albertel 8640: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8641: 					     \%metathesekeys);
                   8642: 	    }
                   8643: 	}
1.338     www      8644: # are there custom rights to evaluate
1.599     albertel 8645: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8646: 
1.338     www      8647:     #
                   8648:     # Importing a rights file here
1.339     albertel 8649:     #
                   8650: 	    unless ($depthcount) {
1.599     albertel 8651: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8652: 		my $dir=$filename;
                   8653: 		$dir=~s|[^/]*$||;
                   8654: 		$location=&filelocation($dir,$location);
1.736     albertel 8655: 		my $rights_metadata =
                   8656: 		    &metadata($uri,'keys',$location,'_rights',
                   8657: 			      $depthcount+1);
                   8658: 		foreach my $rights (split(',',$rights_metadata)) {
                   8659: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8660: 		    $metathesekeys{$rights}=1;
1.339     albertel 8661: 		}
                   8662: 	    }
                   8663: 	}
1.737     albertel 8664: 	# uniqifiy package listing
                   8665: 	my %seen;
                   8666: 	my @uniq_packages =
                   8667: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8668: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8669: 
                   8670: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8671: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8672: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8673: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8674: # this is the end of "was not already recently cached
1.71      www      8675:     }
1.599     albertel 8676:     return $metaentry{':'.$what};
1.261     albertel 8677: }
                   8678: 
1.488     albertel 8679: sub metadata_create_package_def {
1.483     albertel 8680:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8681:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8682:     if ($subp eq 'default') { next; }
                   8683:     
1.599     albertel 8684:     if (defined($metaentry{':packages'})) {
                   8685: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8686:     } else {
1.599     albertel 8687: 	$metaentry{':packages'}=$package;
1.483     albertel 8688:     }
                   8689:     my $value=$packagetab{$key};
                   8690:     my $unikey;
                   8691:     $unikey='parameter_0_'.$name;
1.599     albertel 8692:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8693:     $$metathesekeys{$unikey}=1;
1.599     albertel 8694:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8695: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8696:     }
1.599     albertel 8697:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8698: 	$metaentry{':'.$unikey}=
                   8699: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8700:     }
                   8701: }
                   8702: 
1.261     albertel 8703: sub metadata_generate_part0 {
                   8704:     my ($metadata,$metacache,$uri) = @_;
                   8705:     my %allnames;
1.737     albertel 8706:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8707: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8708: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8709: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8710: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8711: 	    $allnames{$name}=$part;
                   8712: 	  }
                   8713: 	}
                   8714:     }
                   8715:     foreach my $name (keys(%allnames)) {
                   8716:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8717:       my $key=":parameter_0_$name";
1.261     albertel 8718:       $$metacache{"$key.part"}='0';
                   8719:       $$metacache{"$key.name"}=$name;
1.428     albertel 8720:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8721: 					   $allnames{$name}.'_'.$name.
                   8722: 					   '.type'};
1.428     albertel 8723:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8724: 			     '.display'};
1.644     www      8725:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8726:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8727:       $$metacache{"$key.display"}=$olddis;
                   8728:     }
1.71      www      8729: }
                   8730: 
1.764     albertel 8731: # ------------------------------------------------------ Devalidate title cache
                   8732: 
                   8733: sub devalidate_title_cache {
                   8734:     my ($url)=@_;
                   8735:     if (!$env{'request.course.id'}) { return; }
                   8736:     my $symb=&symbread($url);
                   8737:     if (!$symb) { return; }
                   8738:     my $key=$env{'request.course.id'}."\0".$symb;
                   8739:     &devalidate_cache_new('title',$key);
                   8740: }
                   8741: 
1.1014    droeschl 8742: # ------------------------------------------------- Get the title of a course
                   8743: 
                   8744: sub current_course_title {
                   8745:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8746: }
1.301     www      8747: # ------------------------------------------------- Get the title of a resource
                   8748: 
                   8749: sub gettitle {
                   8750:     my $urlsymb=shift;
                   8751:     my $symb=&symbread($urlsymb);
1.534     albertel 8752:     if ($symb) {
1.620     albertel 8753: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8754: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8755: 	if (defined($cached)) { 
                   8756: 	    return $result;
                   8757: 	}
1.534     albertel 8758: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8759: 	my $title='';
1.907     albertel 8760: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8761: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8762: 	} else {
                   8763: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8764: 		    &GDBM_READER(),0640)) {
                   8765: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8766: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8767: 		untie(%bighash);
                   8768: 	    }
1.534     albertel 8769: 	}
                   8770: 	$title=~s/\&colon\;/\:/gs;
                   8771: 	if ($title) {
1.599     albertel 8772: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8773: 	}
                   8774: 	$urlsymb=$url;
                   8775:     }
                   8776:     my $title=&metadata($urlsymb,'title');
                   8777:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8778:     return $title;
1.301     www      8779: }
1.613     albertel 8780: 
1.614     albertel 8781: sub get_slot {
                   8782:     my ($which,$cnum,$cdom)=@_;
                   8783:     if (!$cnum || !$cdom) {
1.790     albertel 8784: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8785: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8786: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8787:     }
1.703     albertel 8788:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8789:     my %slotinfo;
                   8790:     if (exists($remembered{$key})) {
                   8791: 	$slotinfo{$which} = $remembered{$key};
                   8792:     } else {
                   8793: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8794: 	&Apache::lonhomework::showhash(%slotinfo);
                   8795: 	my ($tmp)=keys(%slotinfo);
                   8796: 	if ($tmp=~/^error:/) { return (); }
                   8797: 	$remembered{$key} = $slotinfo{$which};
                   8798:     }
1.616     albertel 8799:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8800: 	return %{$slotinfo{$which}};
                   8801:     }
                   8802:     return $slotinfo{$which};
1.614     albertel 8803: }
1.31      www      8804: # ------------------------------------------------- Update symbolic store links
                   8805: 
                   8806: sub symblist {
                   8807:     my ($mapname,%newhash)=@_;
1.438     www      8808:     $mapname=&deversion(&declutter($mapname));
1.31      www      8809:     my %hash;
1.620     albertel 8810:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8811:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8812:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8813: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8814: 		next if ($url eq 'last_known'
                   8815: 			 && $env{'form.no_update_last_known'});
                   8816: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8817: 						    $newhash{$url}->[1],
                   8818: 						    $newhash{$url}->[0]);
1.191     harris41 8819:             }
1.31      www      8820:             if (untie(%hash)) {
                   8821: 		return 'ok';
                   8822:             }
                   8823:         }
                   8824:     }
                   8825:     return 'error';
1.212     www      8826: }
                   8827: 
                   8828: # --------------------------------------------------------------- Verify a symb
                   8829: 
                   8830: sub symbverify {
1.510     www      8831:     my ($symb,$thisurl)=@_;
                   8832:     my $thisfn=$thisurl;
1.439     www      8833:     $thisfn=&declutter($thisfn);
1.215     www      8834: # direct jump to resource in page or to a sequence - will construct own symbs
                   8835:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8836: # check URL part
1.409     www      8837:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8838: 
1.431     www      8839:     unless ($url eq $thisfn) { return 0; }
1.213     www      8840: 
1.216     www      8841:     $symb=&symbclean($symb);
1.510     www      8842:     $thisurl=&deversion($thisurl);
1.439     www      8843:     $thisfn=&deversion($thisfn);
1.213     www      8844: 
                   8845:     my %bighash;
                   8846:     my $okay=0;
1.431     www      8847: 
1.620     albertel 8848:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8849:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8850:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8851:             $thisurl =~ s/\?.+$//;
                   8852:         }
1.510     www      8853:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8854:         unless ($ids) { 
1.510     www      8855:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8856:         }
                   8857:         if ($ids) {
                   8858: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8859: 	    foreach my $id (split(/\,/,$ids)) {
                   8860: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8861:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8862:                    $symb =~ s/\?.+$//;
                   8863:                }
1.216     www      8864:                if (
                   8865:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8866:    eq $symb) { 
1.620     albertel 8867: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8868: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8869: 		       $okay=1; 
                   8870: 		   }
                   8871: 	       }
1.216     www      8872: 	   }
                   8873:         }
1.213     www      8874: 	untie(%bighash);
                   8875:     }
                   8876:     return $okay;
1.31      www      8877: }
                   8878: 
1.210     www      8879: # --------------------------------------------------------------- Clean-up symb
                   8880: 
                   8881: sub symbclean {
                   8882:     my $symb=shift;
1.568     albertel 8883:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8884: # remove version from map
                   8885:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8886: 
1.210     www      8887: # remove version from URL
                   8888:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8889: 
1.507     www      8890: # remove wrapper
                   8891: 
1.510     www      8892:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8893:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8894:     return $symb;
1.409     www      8895: }
                   8896: 
                   8897: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8898: 
                   8899: sub encode_symb {
                   8900:     my ($map,$resid,$url)=@_;
                   8901:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8902: }
1.409     www      8903: 
                   8904: sub decode_symb {
1.568     albertel 8905:     my $symb=shift;
                   8906:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8907:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8908:     return (&fixversion($map),$resid,&fixversion($url));
                   8909: }
                   8910: 
                   8911: sub fixversion {
                   8912:     my $fn=shift;
1.609     banghart 8913:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8914:     my %bighash;
                   8915:     my $uri=&clutter($fn);
1.620     albertel 8916:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8917: # is this cached?
1.599     albertel 8918:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8919:     if (defined($cached)) { return $result; }
                   8920: # unfortunately not cached, or expired
1.620     albertel 8921:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8922: 	    &GDBM_READER(),0640)) {
                   8923:  	if ($bighash{'version_'.$uri}) {
                   8924:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8925:  	    unless (($version eq 'mostrecent') || 
                   8926: 		    ($version==&getversion($uri))) {
1.440     www      8927:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8928:  	    }
                   8929:  	}
                   8930:  	untie %bighash;
1.413     www      8931:     }
1.599     albertel 8932:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8933: }
                   8934: 
                   8935: sub deversion {
                   8936:     my $url=shift;
                   8937:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8938:     return $url;
1.210     www      8939: }
                   8940: 
1.31      www      8941: # ------------------------------------------------------ Return symb list entry
                   8942: 
                   8943: sub symbread {
1.249     www      8944:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8945:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8946:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8947: # no filename provided? try from environment
1.44      www      8948:     unless ($thisfn) {
1.620     albertel 8949:         if ($env{'request.symb'}) {
                   8950: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8951: 	}
1.620     albertel 8952: 	$thisfn=$env{'request.filename'};
1.44      www      8953:     }
1.569     albertel 8954:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8955: # is that filename actually a symb? Verify, clean, and return
                   8956:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8957: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8958: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8959: 	}
1.242     www      8960:     }
1.44      www      8961:     $thisfn=declutter($thisfn);
1.31      www      8962:     my %hash;
1.37      www      8963:     my %bighash;
                   8964:     my $syval='';
1.620     albertel 8965:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8966:         my $targetfn = $thisfn;
1.609     banghart 8967:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8968:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8969:         }
1.687     albertel 8970: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8971: 	    $targetfn=$1;
                   8972: 	}
1.620     albertel 8973:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8974:                       &GDBM_READER(),0640)) {
1.481     raeburn  8975: 	    $syval=$hash{$targetfn};
1.37      www      8976:             untie(%hash);
                   8977:         }
                   8978: # ---------------------------------------------------------- There was an entry
                   8979:         if ($syval) {
1.601     albertel 8980: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8981: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8982: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8983: 		    #return $env{$cache_str}='';
1.601     albertel 8984: 		#}    
                   8985: 		#$syval.=$1;
                   8986: 	    #}
1.37      www      8987:         } else {
                   8988: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8989:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8990:                             &GDBM_READER(),0640)) {
1.37      www      8991: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8992:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8993:               unless ($ids) { 
                   8994:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8995:               }
                   8996:               unless ($ids) {
                   8997: # alias?
                   8998: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8999:               }
1.37      www      9000:               if ($ids) {
                   9001: # ------------------------------------------------------------------- Has ID(s)
                   9002:                  my @possibilities=split(/\,/,$ids);
1.39      www      9003:                  if ($#possibilities==0) {
                   9004: # ----------------------------------------------- There is only one possibility
1.37      www      9005: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9006: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9007: 						    $resid,$thisfn);
1.249     www      9008:                  } elsif (!$donotrecurse) {
1.39      www      9009: # ------------------------------------------ There is more than one possibility
                   9010:                      my $realpossible=0;
1.800     albertel 9011:                      foreach my $id (@possibilities) {
                   9012: 			 my $file=$bighash{'src_'.$id};
1.39      www      9013:                          if (&allowed('bre',$file)) {
1.800     albertel 9014:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9015:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9016: 				$realpossible++;
1.626     albertel 9017:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9018: 						    $resid,$thisfn);
1.39      www      9019:                             }
                   9020: 			 }
1.191     harris41 9021:                      }
1.39      www      9022: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9023:                  } else {
                   9024:                      $syval='';
1.37      www      9025:                  }
                   9026: 	      }
                   9027:               untie(%bighash)
1.481     raeburn  9028:            }
1.31      www      9029:         }
1.62      www      9030:         if ($syval) {
1.620     albertel 9031: 	    return $env{$cache_str}=$syval;
1.62      www      9032:         }
1.31      www      9033:     }
1.949     raeburn  9034:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9035:     return $env{$cache_str}='';
1.31      www      9036: }
                   9037: 
                   9038: # ---------------------------------------------------------- Return random seed
                   9039: 
1.32      www      9040: sub numval {
                   9041:     my $txt=shift;
                   9042:     $txt=~tr/A-J/0-9/;
                   9043:     $txt=~tr/a-j/0-9/;
                   9044:     $txt=~tr/K-T/0-9/;
                   9045:     $txt=~tr/k-t/0-9/;
                   9046:     $txt=~tr/U-Z/0-5/;
                   9047:     $txt=~tr/u-z/0-5/;
                   9048:     $txt=~s/\D//g;
1.564     albertel 9049:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9050:     return int($txt);
1.368     albertel 9051: }
                   9052: 
1.484     albertel 9053: sub numval2 {
                   9054:     my $txt=shift;
                   9055:     $txt=~tr/A-J/0-9/;
                   9056:     $txt=~tr/a-j/0-9/;
                   9057:     $txt=~tr/K-T/0-9/;
                   9058:     $txt=~tr/k-t/0-9/;
                   9059:     $txt=~tr/U-Z/0-5/;
                   9060:     $txt=~tr/u-z/0-5/;
                   9061:     $txt=~s/\D//g;
                   9062:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9063:     my $total;
                   9064:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9065:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9066:     return int($total);
                   9067: }
                   9068: 
1.575     albertel 9069: sub numval3 {
                   9070:     use integer;
                   9071:     my $txt=shift;
                   9072:     $txt=~tr/A-J/0-9/;
                   9073:     $txt=~tr/a-j/0-9/;
                   9074:     $txt=~tr/K-T/0-9/;
                   9075:     $txt=~tr/k-t/0-9/;
                   9076:     $txt=~tr/U-Z/0-5/;
                   9077:     $txt=~tr/u-z/0-5/;
                   9078:     $txt=~s/\D//g;
                   9079:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9080:     my $total;
                   9081:     foreach my $val (@txts) { $total+=$val; }
                   9082:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9083:     return $total;
                   9084: }
                   9085: 
1.675     albertel 9086: sub digest {
                   9087:     my ($data)=@_;
                   9088:     my $digest=&Digest::MD5::md5($data);
                   9089:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9090:     my ($e,$f);
                   9091:     {
                   9092:         use integer;
                   9093:         $e=($a+$b);
                   9094:         $f=($c+$d);
                   9095:         if ($_64bit) {
                   9096:             $e=(($e<<32)>>32);
                   9097:             $f=(($f<<32)>>32);
                   9098:         }
                   9099:     }
                   9100:     if (wantarray) {
                   9101: 	return ($e,$f);
                   9102:     } else {
                   9103: 	my $g;
                   9104: 	{
                   9105: 	    use integer;
                   9106: 	    $g=($e+$f);
                   9107: 	    if ($_64bit) {
                   9108: 		$g=(($g<<32)>>32);
                   9109: 	    }
                   9110: 	}
                   9111: 	return $g;
                   9112:     }
                   9113: }
                   9114: 
1.368     albertel 9115: sub latest_rnd_algorithm_id {
1.675     albertel 9116:     return '64bit5';
1.366     albertel 9117: }
1.32      www      9118: 
1.503     albertel 9119: sub get_rand_alg {
                   9120:     my ($courseid)=@_;
1.790     albertel 9121:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9122:     if ($courseid) {
1.620     albertel 9123: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9124:     }
                   9125:     return &latest_rnd_algorithm_id();
                   9126: }
                   9127: 
1.562     albertel 9128: sub validCODE {
                   9129:     my ($CODE)=@_;
                   9130:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9131:     return 0;
                   9132: }
                   9133: 
1.491     albertel 9134: sub getCODE {
1.620     albertel 9135:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9136:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9137: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9138: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9139: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9140:     }
                   9141:     return undef;
                   9142: }
                   9143: 
1.31      www      9144: sub rndseed {
1.155     albertel 9145:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9146:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9147:     if (!defined($symb)) {
1.366     albertel 9148: 	unless ($symb=$wsymb) { return time; }
                   9149:     }
                   9150:     if (!$courseid) { $courseid=$wcourseid; }
                   9151:     if (!$domain) { $domain=$wdomain; }
                   9152:     if (!$username) { $username=$wusername }
1.503     albertel 9153:     my $which=&get_rand_alg();
1.803     albertel 9154: 
1.491     albertel 9155:     if (defined(&getCODE())) {
1.675     albertel 9156: 	if ($which eq '64bit5') {
                   9157: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9158: 	} elsif ($which eq '64bit4') {
1.575     albertel 9159: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9160: 	} else {
                   9161: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9162: 	}
1.675     albertel 9163:     } elsif ($which eq '64bit5') {
                   9164: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9165:     } elsif ($which eq '64bit4') {
                   9166: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9167:     } elsif ($which eq '64bit3') {
                   9168: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9169:     } elsif ($which eq '64bit2') {
                   9170: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9171:     } elsif ($which eq '64bit') {
                   9172: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9173:     }
                   9174:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9175: }
                   9176: 
                   9177: sub rndseed_32bit {
                   9178:     my ($symb,$courseid,$domain,$username)=@_;
                   9179:     {
                   9180: 	use integer;
                   9181: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9182: 	my $symbseed=numval($symb) << 22;
                   9183: 	my $namechck=unpack("%32C*",$username) << 17;
                   9184: 	my $nameseed=numval($username) << 12;
                   9185: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9186: 	my $courseseed=unpack("%32C*",$courseid);
                   9187: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9188: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9189: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9190: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9191: 	return $num;
                   9192:     }
                   9193: }
                   9194: 
                   9195: sub rndseed_64bit {
                   9196:     my ($symb,$courseid,$domain,$username)=@_;
                   9197:     {
                   9198: 	use integer;
                   9199: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9200: 	my $symbseed=numval($symb) << 10;
                   9201: 	my $namechck=unpack("%32S*",$username);
                   9202: 	
                   9203: 	my $nameseed=numval($username) << 21;
                   9204: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9205: 	my $courseseed=unpack("%32S*",$courseid);
                   9206: 	
                   9207: 	my $num1=$symbchck+$symbseed+$namechck;
                   9208: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9209: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9210: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9211: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9212: 	return "$num1,$num2";
1.155     albertel 9213:     }
1.366     albertel 9214: }
                   9215: 
1.443     albertel 9216: sub rndseed_64bit2 {
                   9217:     my ($symb,$courseid,$domain,$username)=@_;
                   9218:     {
                   9219: 	use integer;
                   9220: 	# strings need to be an even # of cahracters long, it it is odd the
                   9221:         # last characters gets thrown away
                   9222: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9223: 	my $symbseed=numval($symb) << 10;
                   9224: 	my $namechck=unpack("%32S*",$username.' ');
                   9225: 	
                   9226: 	my $nameseed=numval($username) << 21;
1.501     albertel 9227: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9228: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9229: 	
                   9230: 	my $num1=$symbchck+$symbseed+$namechck;
                   9231: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9232: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9233: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9234: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9235: 	return "$num1,$num2";
                   9236:     }
                   9237: }
                   9238: 
                   9239: sub rndseed_64bit3 {
                   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=numval2($symb) << 10;
                   9247: 	my $namechck=unpack("%32S*",$username.' ');
                   9248: 	
                   9249: 	my $nameseed=numval2($username) << 21;
1.443     albertel 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.564     albertel 9257: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9258: 	
1.503     albertel 9259: 	return "$num1:$num2";
1.443     albertel 9260:     }
                   9261: }
                   9262: 
1.575     albertel 9263: sub rndseed_64bit4 {
                   9264:     my ($symb,$courseid,$domain,$username)=@_;
                   9265:     {
                   9266: 	use integer;
                   9267: 	# strings need to be an even # of cahracters long, it it is odd the
                   9268:         # last characters gets thrown away
                   9269: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9270: 	my $symbseed=numval3($symb) << 10;
                   9271: 	my $namechck=unpack("%32S*",$username.' ');
                   9272: 	
                   9273: 	my $nameseed=numval3($username) << 21;
                   9274: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9275: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9276: 	
                   9277: 	my $num1=$symbchck+$symbseed+$namechck;
                   9278: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9279: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9280: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9281: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9282: 	
                   9283: 	return "$num1:$num2";
                   9284:     }
                   9285: }
                   9286: 
1.675     albertel 9287: sub rndseed_64bit5 {
                   9288:     my ($symb,$courseid,$domain,$username)=@_;
                   9289:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9290:     return "$num1:$num2";
                   9291: }
                   9292: 
1.366     albertel 9293: sub rndseed_CODE_64bit {
                   9294:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9295:     {
1.366     albertel 9296: 	use integer;
1.443     albertel 9297: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9298: 	my $symbseed=numval2($symb);
1.491     albertel 9299: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9300: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9301: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9302: 	my $num1=$symbseed+$CODEchck;
                   9303: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9304: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9305: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9306: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9307: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9308: 	return "$num1:$num2";
1.366     albertel 9309:     }
                   9310: }
                   9311: 
1.575     albertel 9312: sub rndseed_CODE_64bit4 {
                   9313:     my ($symb,$courseid,$domain,$username)=@_;
                   9314:     {
                   9315: 	use integer;
                   9316: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9317: 	my $symbseed=numval3($symb);
                   9318: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9319: 	my $CODEseed=numval3(&getCODE());
                   9320: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9321: 	my $num1=$symbseed+$CODEchck;
                   9322: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9323: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9324: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9325: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9326: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9327: 	return "$num1:$num2";
                   9328:     }
                   9329: }
                   9330: 
1.675     albertel 9331: sub rndseed_CODE_64bit5 {
                   9332:     my ($symb,$courseid,$domain,$username)=@_;
                   9333:     my $code = &getCODE();
                   9334:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9335:     return "$num1:$num2";
                   9336: }
                   9337: 
1.366     albertel 9338: sub setup_random_from_rndseed {
                   9339:     my ($rndseed)=@_;
1.503     albertel 9340:     if ($rndseed =~/([,:])/) {
                   9341: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9342: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9343:     } else {
                   9344: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9345:     }
1.36      albertel 9346: }
                   9347: 
1.474     albertel 9348: sub latest_receipt_algorithm_id {
1.835     albertel 9349:     return 'receipt3';
1.474     albertel 9350: }
                   9351: 
1.480     www      9352: sub recunique {
                   9353:     my $fucourseid=shift;
                   9354:     my $unique;
1.835     albertel 9355:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9356: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9357: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9358:     } else {
                   9359: 	$unique=$perlvar{'lonReceipt'};
                   9360:     }
                   9361:     return unpack("%32C*",$unique);
                   9362: }
                   9363: 
                   9364: sub recprefix {
                   9365:     my $fucourseid=shift;
                   9366:     my $prefix;
1.835     albertel 9367:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9368: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9369: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9370:     } else {
                   9371: 	$prefix=$perlvar{'lonHostID'};
                   9372:     }
                   9373:     return unpack("%32C*",$prefix);
                   9374: }
                   9375: 
1.76      www      9376: sub ireceipt {
1.474     albertel 9377:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9378: 
                   9379:     my $return =&recprefix($fucourseid).'-';
                   9380: 
                   9381:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9382: 	$env{'request.state'} eq 'construct') {
                   9383: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9384: 	return $return;
                   9385:     }
                   9386: 
1.76      www      9387:     my $cuname=unpack("%32C*",$funame);
                   9388:     my $cudom=unpack("%32C*",$fudom);
                   9389:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9390:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9391:     my $cunique=&recunique($fucourseid);
1.474     albertel 9392:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9393:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9394: 
1.790     albertel 9395: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9396: 			       
                   9397: 	$return.= ($cunique%$cuname+
                   9398: 		   $cunique%$cudom+
                   9399: 		   $cusymb%$cuname+
                   9400: 		   $cusymb%$cudom+
                   9401: 		   $cucourseid%$cuname+
                   9402: 		   $cucourseid%$cudom+
                   9403: 		   $cpart%$cuname+
                   9404: 		   $cpart%$cudom);
                   9405:     } else {
                   9406: 	$return.= ($cunique%$cuname+
                   9407: 		   $cunique%$cudom+
                   9408: 		   $cusymb%$cuname+
                   9409: 		   $cusymb%$cudom+
                   9410: 		   $cucourseid%$cuname+
                   9411: 		   $cucourseid%$cudom);
                   9412:     }
                   9413:     return $return;
1.76      www      9414: }
                   9415: 
                   9416: sub receipt {
1.474     albertel 9417:     my ($part)=@_;
1.790     albertel 9418:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9419:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9420: }
1.260     ng       9421: 
1.790     albertel 9422: sub whichuser {
                   9423:     my ($passedsymb)=@_;
                   9424:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9425:     if (defined($env{'form.grade_symb'})) {
                   9426: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9427: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9428: 	if (!$allowed &&
                   9429: 	    exists($env{'request.course.sec'}) &&
                   9430: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9431: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9432: 			      '/'.$env{'request.course.sec'});
                   9433: 	}
                   9434: 	if ($allowed) {
                   9435: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9436: 	    $courseid=$tmp_courseid;
                   9437: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9438: 	    ($name)=&get_env_multiple('form.grade_username');
                   9439: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9440: 	}
                   9441:     }
                   9442:     if (!$passedsymb) {
                   9443: 	$symb=&symbread();
                   9444:     } else {
                   9445: 	$symb=$passedsymb;
                   9446:     }
                   9447:     $courseid=$env{'request.course.id'};
                   9448:     $domain=$env{'user.domain'};
                   9449:     $name=$env{'user.name'};
                   9450:     if ($name eq 'public' && $domain eq 'public') {
                   9451: 	if (!defined($env{'form.username'})) {
                   9452: 	    $env{'form.username'}.=time.rand(10000000);
                   9453: 	}
                   9454: 	$name.=$env{'form.username'};
                   9455:     }
                   9456:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9457: 
                   9458: }
                   9459: 
1.36      albertel 9460: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9461: # returns either the contents of the file or 
                   9462: # -1 if the file doesn't exist
1.481     raeburn  9463: #
                   9464: # if the target is a file that was uploaded via DOCS, 
                   9465: # a check will be made to see if a current copy exists on the local server,
                   9466: # if it does this will be served, otherwise a copy will be retrieved from
                   9467: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9468: # the local server.   
1.472     albertel 9469: 
1.36      albertel 9470: sub getfile {
1.538     albertel 9471:     my ($file) = @_;
1.609     banghart 9472:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9473:     &repcopy($file);
                   9474:     return &readfile($file);
                   9475: }
                   9476: 
                   9477: sub repcopy_userfile {
                   9478:     my ($file)=@_;
1.609     banghart 9479:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9480:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9481:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9482: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9483:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9484:     if (-e "$file") {
1.828     www      9485: # we already have a local copy, check it out
1.538     albertel 9486: 	my @fileinfo = stat($file);
1.828     www      9487: 	my $rtncode;
                   9488: 	my $info;
1.538     albertel 9489: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9490: 	if ($lwpresp ne 'ok') {
1.828     www      9491: # there is no such file anymore, even though we had a local copy
1.482     albertel 9492: 	    if ($rtncode eq '404') {
1.538     albertel 9493: 		unlink($file);
1.482     albertel 9494: 	    }
                   9495: 	    return -1;
                   9496: 	}
                   9497: 	if ($info < $fileinfo[9]) {
1.828     www      9498: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9499: 	    return 'ok';
1.828     www      9500: 	} else {
                   9501: # the file is outdated, get rid of it
                   9502: 	    unlink($file);
1.482     albertel 9503: 	}
1.828     www      9504:     }
                   9505: # one way or the other, at this point, we don't have the file
                   9506: # construct the correct path for the file
                   9507:     my @parts = ($cdom,$cnum); 
                   9508:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9509: 	push @parts, split(/\//,$1);
                   9510:     }
                   9511:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9512:     foreach my $part (@parts) {
                   9513: 	$path .= '/'.$part;
                   9514: 	if (!-e $path) {
                   9515: 	    mkdir($path,0770);
1.482     albertel 9516: 	}
                   9517:     }
1.828     www      9518: # now the path exists for sure
                   9519: # get a user agent
                   9520:     my $ua=new LWP::UserAgent;
                   9521:     my $transferfile=$file.'.in.transfer';
                   9522: # FIXME: this should flock
                   9523:     if (-e $transferfile) { return 'ok'; }
                   9524:     my $request;
                   9525:     $uri=~s/^\///;
1.980     raeburn  9526:     my $homeserver = &homeserver($cnum,$cdom);
                   9527:     my $protocol = $protocol{$homeserver};
                   9528:     $protocol = 'http' if ($protocol ne 'https');
                   9529:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9530:     my $response=$ua->request($request,$transferfile);
                   9531: # did it work?
                   9532:     if ($response->is_error()) {
                   9533: 	unlink($transferfile);
                   9534: 	&logthis("Userfile repcopy failed for $uri");
                   9535: 	return -1;
                   9536:     }
                   9537: # worked, rename the transfer file
                   9538:     rename($transferfile,$file);
1.607     raeburn  9539:     return 'ok';
1.481     raeburn  9540: }
                   9541: 
1.517     albertel 9542: sub tokenwrapper {
                   9543:     my $uri=shift;
1.980     raeburn  9544:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9545:     $uri=~s|^/||;
1.620     albertel 9546:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9547:     my $token=$1;
1.552     albertel 9548:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9549:     if ($udom && $uname && $file) {
                   9550: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9551:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9552:         my $homeserver = &homeserver($uname,$udom);
                   9553:         my $protocol = $protocol{$homeserver};
                   9554:         $protocol = 'http' if ($protocol ne 'https');
                   9555:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9556:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9557:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9558:     } else {
                   9559:         return '/adm/notfound.html';
                   9560:     }
                   9561: }
                   9562: 
1.828     www      9563: # call with reqtype HEAD: get last modification time
                   9564: # call with reqtype GET: get the file contents
                   9565: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9566: #
1.481     raeburn  9567: sub getuploaded {
                   9568:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9569:     $uri=~s/^\///;
1.980     raeburn  9570:     my $homeserver = &homeserver($cnum,$cdom);
                   9571:     my $protocol = $protocol{$homeserver};
                   9572:     $protocol = 'http' if ($protocol ne 'https');
                   9573:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9574:     my $ua=new LWP::UserAgent;
                   9575:     my $request=new HTTP::Request($reqtype,$uri);
                   9576:     my $response=$ua->request($request);
                   9577:     $$rtncode = $response->code;
1.482     albertel 9578:     if (! $response->is_success()) {
                   9579: 	return 'failed';
                   9580:     }      
                   9581:     if ($reqtype eq 'HEAD') {
1.486     www      9582: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9583:     } elsif ($reqtype eq 'GET') {
                   9584: 	$$info = $response->content;
1.472     albertel 9585:     }
1.482     albertel 9586:     return 'ok';
1.36      albertel 9587: }
                   9588: 
1.481     raeburn  9589: sub readfile {
                   9590:     my $file = shift;
                   9591:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9592:     my $fh;
                   9593:     open($fh,"<$file");
                   9594:     my $a='';
1.800     albertel 9595:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9596:     return $a;
                   9597: }
                   9598: 
1.36      albertel 9599: sub filelocation {
1.590     banghart 9600:     my ($dir,$file) = @_;
                   9601:     my $location;
                   9602:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9603: 
                   9604:     if ($file =~ m-^/adm/-) {
                   9605: 	$file=~s-^/adm/wrapper/-/-;
                   9606: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9607:     }
1.882     albertel 9608: 
1.590     banghart 9609:     if ($file=~m:^/~:) { # is a contruction space reference
                   9610:         $location = $file;
                   9611:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9612:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9613: 	# is a correct contruction space reference
                   9614:         $location = $file;
1.956     raeburn  9615:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9616:         $location = $file;
1.609     banghart 9617:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9618:         my ($udom,$uname,$filename)=
1.811     albertel 9619:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9620:         my $home=&homeserver($uname,$udom);
                   9621:         my $is_me=0;
                   9622:         my @ids=&current_machine_ids();
                   9623:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9624:         if ($is_me) {
1.955     raeburn  9625:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9626:         } else {
                   9627:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9628:   	      $udom.'/'.$uname.'/'.$filename;
                   9629:         }
1.882     albertel 9630:     } elsif ($file =~ m-^/adm/-) {
                   9631: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9632:     } else {
                   9633:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9634:         $file=~s:^/res/:/:;
                   9635:         if ( !( $file =~ m:^/:) ) {
                   9636:             $location = $dir. '/'.$file;
                   9637:         } else {
                   9638:             $location = '/home/httpd/html/res'.$file;
                   9639:         }
1.59      albertel 9640:     }
1.590     banghart 9641:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9642:     while ($location=~m{/\.\./}) {
                   9643: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9644: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9645: 	} else {
                   9646: 	    $location=~ s{/\.\./}{/}g;
                   9647: 	}
                   9648:     } #remove dir/..
1.590     banghart 9649:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9650:     return $location;
1.46      www      9651: }
1.36      albertel 9652: 
1.46      www      9653: sub hreflocation {
                   9654:     my ($dir,$file)=@_;
1.980     raeburn  9655:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9656: 	$file=filelocation($dir,$file);
1.700     albertel 9657:     } elsif ($file=~m-^/adm/-) {
                   9658: 	$file=~s-^/adm/wrapper/-/-;
                   9659: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9660:     }
                   9661:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9662: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9663:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9664: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9665:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9666: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9667: 	    -/uploaded/$1/$2/-x;
1.46      www      9668:     }
1.913     albertel 9669:     if ($file=~ m{^/userfiles/}) {
                   9670: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9671:     }
1.462     albertel 9672:     return $file;
1.465     albertel 9673: }
                   9674: 
                   9675: sub current_machine_domains {
1.853     albertel 9676:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9677: }
                   9678: 
                   9679: sub machine_domains {
                   9680:     my ($hostname) = @_;
1.465     albertel 9681:     my @domains;
1.838     albertel 9682:     my %hostname = &all_hostnames();
1.465     albertel 9683:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9684: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9685: 	if ($hostname eq $name) {
1.844     albertel 9686: 	    push(@domains,&host_domain($id));
1.465     albertel 9687: 	}
                   9688:     }
                   9689:     return @domains;
                   9690: }
                   9691: 
                   9692: sub current_machine_ids {
1.853     albertel 9693:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9694: }
                   9695: 
                   9696: sub machine_ids {
                   9697:     my ($hostname) = @_;
                   9698:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9699:     my @ids;
1.888     albertel 9700:     my %name_to_host = &all_names();
1.889     albertel 9701:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9702: 	return @{ $name_to_host{$hostname} };
                   9703:     }
                   9704:     return;
1.31      www      9705: }
                   9706: 
1.824     raeburn  9707: sub additional_machine_domains {
                   9708:     my @domains;
                   9709:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9710:     while( my $line = <$fh>) {
                   9711:         $line =~ s/\s//g;
                   9712:         push(@domains,$line);
                   9713:     }
                   9714:     return @domains;
                   9715: }
                   9716: 
                   9717: sub default_login_domain {
                   9718:     my $domain = $perlvar{'lonDefDomain'};
                   9719:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9720:     foreach my $posdom (&current_machine_domains(),
                   9721:                         &additional_machine_domains()) {
                   9722:         if (lc($posdom) eq lc($testdomain)) {
                   9723:             $domain=$posdom;
                   9724:             last;
                   9725:         }
                   9726:     }
                   9727:     return $domain;
                   9728: }
                   9729: 
1.31      www      9730: # ------------------------------------------------------------- Declutters URLs
                   9731: 
                   9732: sub declutter {
                   9733:     my $thisfn=shift;
1.569     albertel 9734:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9735:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9736:     $thisfn=~s/^\///;
1.697     albertel 9737:     $thisfn=~s|^adm/wrapper/||;
                   9738:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9739:     $thisfn=~s/^res\///;
1.1032    raeburn  9740:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9741:         $thisfn=~s/\?.+$//;
                   9742:     }
1.268     www      9743:     return $thisfn;
                   9744: }
                   9745: 
                   9746: # ------------------------------------------------------------- Clutter up URLs
                   9747: 
                   9748: sub clutter {
                   9749:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9750:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9751: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9752:        $thisfn='/res'.$thisfn; 
                   9753:     }
1.1031    raeburn  9754:     if ($thisfn !~m|^/adm|) {
                   9755: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9756: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9757: 	} else {
                   9758: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9759: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9760: 	    if ($embstyle eq 'ssi'
                   9761: 		|| ($embstyle eq 'hdn')
                   9762: 		|| ($embstyle eq 'rat')
                   9763: 		|| ($embstyle eq 'prv')
                   9764: 		|| ($embstyle eq 'ign')) {
                   9765: 		#do nothing with these
                   9766: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9767: 		|| ($embstyle eq 'emb')
                   9768: 		|| ($embstyle eq 'wrp')) {
                   9769: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9770: 	    } elsif ($embstyle eq 'unk'
                   9771: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9772: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9773: 	    } else {
1.718     www      9774: #		&logthis("Got a blank emb style");
1.695     albertel 9775: 	    }
1.694     albertel 9776: 	}
                   9777:     }
1.31      www      9778:     return $thisfn;
1.12      www      9779: }
                   9780: 
1.787     albertel 9781: sub clutter_with_no_wrapper {
                   9782:     my $uri = &clutter(shift);
                   9783:     if ($uri =~ m-^/adm/-) {
                   9784: 	$uri =~ s-^/adm/wrapper/-/-;
                   9785: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9786:     }
                   9787:     return $uri;
                   9788: }
                   9789: 
1.557     albertel 9790: sub freeze_escape {
                   9791:     my ($value)=@_;
                   9792:     if (ref($value)) {
                   9793: 	$value=&nfreeze($value);
                   9794: 	return '__FROZEN__'.&escape($value);
                   9795:     }
                   9796:     return &escape($value);
                   9797: }
                   9798: 
1.11      www      9799: 
1.557     albertel 9800: sub thaw_unescape {
                   9801:     my ($value)=@_;
                   9802:     if ($value =~ /^__FROZEN__/) {
                   9803: 	substr($value,0,10,undef);
                   9804: 	$value=&unescape($value);
                   9805: 	return &thaw($value);
                   9806:     }
                   9807:     return &unescape($value);
                   9808: }
                   9809: 
1.436     albertel 9810: sub correct_line_ends {
                   9811:     my ($result)=@_;
                   9812:     $$result =~s/\r\n/\n/mg;
                   9813:     $$result =~s/\r/\n/mg;
1.415     albertel 9814: }
1.1       albertel 9815: # ================================================================ Main Program
                   9816: 
1.184     www      9817: sub goodbye {
1.204     albertel 9818:    &logthis("Starting Shut down");
1.443     albertel 9819: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9820:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9821: #converted
1.599     albertel 9822: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9823:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9824: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9825: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9826: #1.1 only
1.870     albertel 9827: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9828: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9829: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9830: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9831:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9832:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9833:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9834:    &flushcourselogs();
                   9835:    &logthis("Shutting down");
                   9836: }
                   9837: 
1.852     albertel 9838: sub get_dns {
1.869     albertel 9839:     my ($url,$func,$ignore_cache) = @_;
                   9840:     if (!$ignore_cache) {
                   9841: 	my ($content,$cached)=
                   9842: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9843: 	if ($cached) {
                   9844: 	    &$func($content);
                   9845: 	    return;
                   9846: 	}
                   9847:     }
                   9848: 
                   9849:     my %alldns;
1.852     albertel 9850:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9851:     foreach my $dns (<$config>) {
                   9852: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9853:         my $line = $1;
                   9854:         my ($host,$protocol) = split(/:/,$line);
                   9855:         if ($protocol ne 'https') {
                   9856:             $protocol = 'http';
                   9857:         }
                   9858: 	$alldns{$host} = $protocol;
1.869     albertel 9859:     }
                   9860:     while (%alldns) {
                   9861: 	my ($dns) = keys(%alldns);
1.852     albertel 9862: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9863: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9864: 	my $response=$ua->request($request);
1.979     raeburn  9865:         delete($alldns{$dns});
1.852     albertel 9866: 	next if ($response->is_error());
                   9867: 	my @content = split("\n",$response->content);
1.869     albertel 9868: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9869: 	&$func(\@content);
1.869     albertel 9870: 	return;
1.852     albertel 9871:     }
                   9872:     close($config);
1.871     albertel 9873:     my $which = (split('/',$url))[3];
                   9874:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9875:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9876:     my @content = <$config>;
                   9877:     &$func(\@content);
                   9878:     return;
1.852     albertel 9879: }
1.327     albertel 9880: # ------------------------------------------------------------ Read domain file
                   9881: {
1.852     albertel 9882:     my $loaded;
1.846     albertel 9883:     my %domain;
                   9884: 
1.852     albertel 9885:     sub parse_domain_tab {
                   9886: 	my ($lines) = @_;
                   9887: 	foreach my $line (@$lines) {
                   9888: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9889: 
1.846     albertel 9890: 	    chomp($line);
1.852     albertel 9891: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9892: 	    my %this_domain;
                   9893: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9894: 			       'lang_def', 'city', 'longi', 'lati',
                   9895: 			       'primary') {
                   9896: 		$this_domain{$field} = shift(@elements);
                   9897: 	    }
                   9898: 	    $domain{$name} = \%this_domain;
1.852     albertel 9899: 	}
                   9900:     }
1.864     albertel 9901: 
                   9902:     sub reset_domain_info {
                   9903: 	undef($loaded);
                   9904: 	undef(%domain);
                   9905:     }
                   9906: 
1.852     albertel 9907:     sub load_domain_tab {
1.869     albertel 9908: 	my ($ignore_cache) = @_;
                   9909: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9910: 	my $fh;
                   9911: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9912: 	    my @lines = <$fh>;
                   9913: 	    &parse_domain_tab(\@lines);
1.448     albertel 9914: 	}
1.852     albertel 9915: 	close($fh);
                   9916: 	$loaded = 1;
1.327     albertel 9917:     }
1.846     albertel 9918: 
                   9919:     sub domain {
1.852     albertel 9920: 	&load_domain_tab() if (!$loaded);
                   9921: 
1.846     albertel 9922: 	my ($name,$what) = @_;
                   9923: 	return if ( !exists($domain{$name}) );
                   9924: 
                   9925: 	if (!$what) {
                   9926: 	    return $domain{$name}{'description'};
                   9927: 	}
                   9928: 	return $domain{$name}{$what};
                   9929:     }
1.974     raeburn  9930: 
                   9931:     sub domain_info {
                   9932:         &load_domain_tab() if (!$loaded);
                   9933:         return %domain;
                   9934:     }
                   9935: 
1.327     albertel 9936: }
                   9937: 
                   9938: 
1.1       albertel 9939: # ------------------------------------------------------------- Read hosts file
                   9940: {
1.838     albertel 9941:     my %hostname;
1.844     albertel 9942:     my %hostdom;
1.845     albertel 9943:     my %libserv;
1.852     albertel 9944:     my $loaded;
1.888     albertel 9945:     my %name_to_host;
1.852     albertel 9946: 
                   9947:     sub parse_hosts_tab {
                   9948: 	my ($file) = @_;
                   9949: 	foreach my $configline (@$file) {
                   9950: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9951: 	    next if ($configline =~ /^\^/);
                   9952: 	    chomp($configline);
1.968     raeburn  9953: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 9954: 	    $name=~s/\s//g;
                   9955: 	    if ($id && $domain && $role && $name) {
                   9956: 		$hostname{$id}=$name;
1.888     albertel 9957: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9958: 		$hostdom{$id}=$domain;
                   9959: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9960:                 if (defined($protocol)) {
                   9961:                     if ($protocol eq 'https') {
                   9962:                         $protocol{$id} = $protocol;
                   9963:                     } else {
                   9964:                         $protocol{$id} = 'http'; 
                   9965:                     }
1.968     raeburn  9966:                 } else {
1.969     raeburn  9967:                     $protocol{$id} = 'http';
1.968     raeburn  9968:                 }
1.852     albertel 9969: 	    }
                   9970: 	}
                   9971:     }
1.864     albertel 9972:     
                   9973:     sub reset_hosts_info {
1.897     albertel 9974: 	&purge_remembered();
1.864     albertel 9975: 	&reset_domain_info();
                   9976: 	&reset_hosts_ip_info();
1.892     albertel 9977: 	undef(%name_to_host);
1.864     albertel 9978: 	undef(%hostname);
                   9979: 	undef(%hostdom);
                   9980: 	undef(%libserv);
                   9981: 	undef($loaded);
                   9982:     }
1.1       albertel 9983: 
1.852     albertel 9984:     sub load_hosts_tab {
1.869     albertel 9985: 	my ($ignore_cache) = @_;
                   9986: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9987: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9988: 	my @config = <$config>;
                   9989: 	&parse_hosts_tab(\@config);
                   9990: 	close($config);
                   9991: 	$loaded=1;
1.1       albertel 9992:     }
1.852     albertel 9993: 
1.838     albertel 9994:     sub hostname {
1.852     albertel 9995: 	&load_hosts_tab() if (!$loaded);
                   9996: 
1.838     albertel 9997: 	my ($lonid) = @_;
                   9998: 	return $hostname{$lonid};
                   9999:     }
1.845     albertel 10000: 
1.838     albertel 10001:     sub all_hostnames {
1.852     albertel 10002: 	&load_hosts_tab() if (!$loaded);
                   10003: 
1.838     albertel 10004: 	return %hostname;
                   10005:     }
1.845     albertel 10006: 
1.888     albertel 10007:     sub all_names {
                   10008: 	&load_hosts_tab() if (!$loaded);
                   10009: 
                   10010: 	return %name_to_host;
                   10011:     }
                   10012: 
1.974     raeburn  10013:     sub all_host_domain {
                   10014:         &load_hosts_tab() if (!$loaded);
                   10015:         return %hostdom;
                   10016:     }
                   10017: 
1.845     albertel 10018:     sub is_library {
1.852     albertel 10019: 	&load_hosts_tab() if (!$loaded);
                   10020: 
1.845     albertel 10021: 	return exists($libserv{$_[0]});
                   10022:     }
                   10023: 
                   10024:     sub all_library {
1.852     albertel 10025: 	&load_hosts_tab() if (!$loaded);
                   10026: 
1.845     albertel 10027: 	return %libserv;
                   10028:     }
                   10029: 
1.1056.4.2  raeburn  10030:     sub unique_library {
                   10031:         #2x reverse removes all hostnames that appear more than once
                   10032:         my %unique = reverse &all_library();
                   10033:         return reverse %unique;
                   10034:     }
                   10035: 
1.841     albertel 10036:     sub get_servers {
1.852     albertel 10037: 	&load_hosts_tab() if (!$loaded);
                   10038: 
1.841     albertel 10039: 	my ($domain,$type) = @_;
                   10040: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10041: 	                                          : %hostname;
                   10042: 	my %result;
1.842     albertel 10043: 	if (ref($domain) eq 'ARRAY') {
                   10044: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10045: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10046: 		    $result{$host} = $hostname;
                   10047: 		}
                   10048: 	    }
                   10049: 	} else {
                   10050: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10051: 		if ($hostdom{$host} eq $domain) {
                   10052: 		    $result{$host} = $hostname;
                   10053: 		}
1.841     albertel 10054: 	    }
                   10055: 	}
                   10056: 	return %result;
                   10057:     }
1.845     albertel 10058: 
1.1056.4.2  raeburn  10059:     sub get_unique_servers {
                   10060:         my %unique = reverse &get_servers(@_);
                   10061:         return reverse %unique;
                   10062:     }
                   10063: 
1.844     albertel 10064:     sub host_domain {
1.852     albertel 10065: 	&load_hosts_tab() if (!$loaded);
                   10066: 
1.844     albertel 10067: 	my ($lonid) = @_;
                   10068: 	return $hostdom{$lonid};
                   10069:     }
                   10070: 
1.841     albertel 10071:     sub all_domains {
1.852     albertel 10072: 	&load_hosts_tab() if (!$loaded);
                   10073: 
1.841     albertel 10074: 	my %seen;
                   10075: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10076: 	return @uniq;
                   10077:     }
1.1056.4.3  raeburn  10078: 
                   10079:     sub internet_dom {
                   10080:         &load_hosts_tab() if (!$loaded);
                   10081: 
                   10082:         my ($lonid) = @_;
                   10083:         return $internetdom{$lonid};
                   10084:     }
                   10085: 
1.1       albertel 10086: }
                   10087: 
1.847     albertel 10088: { 
                   10089:     my %iphost;
1.856     albertel 10090:     my %name_to_ip;
                   10091:     my %lonid_to_ip;
1.869     albertel 10092: 
1.847     albertel 10093:     sub get_hosts_from_ip {
                   10094: 	my ($ip) = @_;
                   10095: 	my %iphosts = &get_iphost();
                   10096: 	if (ref($iphosts{$ip})) {
                   10097: 	    return @{$iphosts{$ip}};
                   10098: 	}
                   10099: 	return;
1.839     albertel 10100:     }
1.864     albertel 10101:     
                   10102:     sub reset_hosts_ip_info {
                   10103: 	undef(%iphost);
                   10104: 	undef(%name_to_ip);
                   10105: 	undef(%lonid_to_ip);
                   10106:     }
1.856     albertel 10107: 
                   10108:     sub get_host_ip {
                   10109: 	my ($lonid) = @_;
                   10110: 	if (exists($lonid_to_ip{$lonid})) {
                   10111: 	    return $lonid_to_ip{$lonid};
                   10112: 	}
                   10113: 	my $name=&hostname($lonid);
                   10114:    	my $ip = gethostbyname($name);
                   10115: 	return if (!$ip || length($ip) ne 4);
                   10116: 	$ip=inet_ntoa($ip);
                   10117: 	$name_to_ip{$name}   = $ip;
                   10118: 	$lonid_to_ip{$lonid} = $ip;
                   10119: 	return $ip;
                   10120:     }
1.847     albertel 10121:     
                   10122:     sub get_iphost {
1.869     albertel 10123: 	my ($ignore_cache) = @_;
1.894     albertel 10124: 
1.869     albertel 10125: 	if (!$ignore_cache) {
                   10126: 	    if (%iphost) {
                   10127: 		return %iphost;
                   10128: 	    }
                   10129: 	    my ($ip_info,$cached)=
                   10130: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10131: 	    if ($cached) {
                   10132: 		%iphost      = %{$ip_info->[0]};
                   10133: 		%name_to_ip  = %{$ip_info->[1]};
                   10134: 		%lonid_to_ip = %{$ip_info->[2]};
                   10135: 		return %iphost;
                   10136: 	    }
                   10137: 	}
1.894     albertel 10138: 
                   10139: 	# get yesterday's info for fallback
                   10140: 	my %old_name_to_ip;
                   10141: 	my ($ip_info,$cached)=
                   10142: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10143: 	if ($cached) {
                   10144: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10145: 	}
                   10146: 
1.888     albertel 10147: 	my %name_to_host = &all_names();
                   10148: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10149: 	    my $ip;
                   10150: 	    if (!exists($name_to_ip{$name})) {
                   10151: 		$ip = gethostbyname($name);
                   10152: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10153: 		    if (defined($old_name_to_ip{$name})) {
                   10154: 			$ip = $old_name_to_ip{$name};
                   10155: 			&logthis("Can't find $name defaulting to old $ip");
                   10156: 		    } else {
                   10157: 			&logthis("Name $name no IP found");
                   10158: 			next;
                   10159: 		    }
                   10160: 		} else {
                   10161: 		    $ip=inet_ntoa($ip);
1.847     albertel 10162: 		}
                   10163: 		$name_to_ip{$name} = $ip;
                   10164: 	    } else {
                   10165: 		$ip = $name_to_ip{$name};
1.653     albertel 10166: 	    }
1.888     albertel 10167: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10168: 		$lonid_to_ip{$id} = $ip;
                   10169: 	    }
                   10170: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10171: 	}
1.869     albertel 10172: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10173: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10174: 				      48*60*60);
1.869     albertel 10175: 
1.847     albertel 10176: 	return %iphost;
1.598     albertel 10177:     }
                   10178: 
1.992     raeburn  10179:     #
                   10180:     #  Given a DNS returns the loncapa host name for that DNS 
                   10181:     # 
                   10182:     sub host_from_dns {
                   10183:         my ($dns) = @_;
                   10184:         my @hosts;
                   10185:         my $ip;
                   10186: 
1.993     raeburn  10187:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10188:             $ip = $name_to_ip{$dns};
                   10189:         }
                   10190:         if (!$ip) {
                   10191:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10192:             if (length($ip) == 4) { 
                   10193: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10194:             }
                   10195:         }
                   10196:         if ($ip) {
                   10197: 	    @hosts = get_hosts_from_ip($ip);
                   10198: 	    return $hosts[0];
                   10199:         }
                   10200:         return undef;
1.986     foxr     10201:     }
1.992     raeburn  10202: 
1.1056.4.3  raeburn  10203:     sub get_internet_names {
                   10204:         my ($lonid) = @_;
                   10205:         return if ($lonid eq '');
                   10206:         my ($idnref,$cached)=
                   10207:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10208:         if ($cached) {
                   10209:             return $idnref;
                   10210:         }
                   10211:         my $ip = &get_host_ip($lonid);
                   10212:         my @hosts = &get_hosts_from_ip($ip);
                   10213:         my %iphost = &get_iphost();
                   10214:         my (@idns,%seen);
                   10215:         foreach my $id (@hosts) {
                   10216:             my $dom = &host_domain($id);
                   10217:             my $prim_id = &domain($dom,'primary');
                   10218:             my $prim_ip = &get_host_ip($prim_id);
                   10219:             next if ($seen{$prim_ip});
                   10220:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10221:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10222:                     my $intdom = &internet_dom($id);
                   10223:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10224:                         push(@idns,$intdom);
                   10225:                     }
                   10226:                 }
                   10227:             }
                   10228:             $seen{$prim_ip} = 1;
                   10229:         }
                   10230:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10231:     }
                   10232: 
                   10233: }
                   10234: 
                   10235: sub all_loncaparevs {
                   10236:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
1.986     foxr     10237: }
                   10238: 
1.862     albertel 10239: BEGIN {
                   10240: 
                   10241: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10242:     unless ($readit) {
                   10243: {
                   10244:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10245:     %perlvar = (%perlvar,%{$configvars});
                   10246: }
                   10247: 
                   10248: 
1.1       albertel 10249: # ------------------------------------------------------ Read spare server file
                   10250: {
1.448     albertel 10251:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10252: 
                   10253:     while (my $configline=<$config>) {
                   10254:        chomp($configline);
1.284     matthew  10255:        if ($configline) {
1.784     albertel 10256: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10257: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10258: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10259:        }
                   10260:     }
1.448     albertel 10261:     close($config);
1.1       albertel 10262: }
1.11      www      10263: # ------------------------------------------------------------ Read permissions
                   10264: {
1.448     albertel 10265:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10266: 
                   10267:     while (my $configline=<$config>) {
1.448     albertel 10268: 	chomp($configline);
                   10269: 	if ($configline) {
                   10270: 	    my ($role,$perm)=split(/ /,$configline);
                   10271: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10272: 	}
1.11      www      10273:     }
1.448     albertel 10274:     close($config);
1.11      www      10275: }
                   10276: 
                   10277: # -------------------------------------------- Read plain texts for permissions
                   10278: {
1.448     albertel 10279:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10280: 
                   10281:     while (my $configline=<$config>) {
1.448     albertel 10282: 	chomp($configline);
                   10283: 	if ($configline) {
1.742     raeburn  10284: 	    my ($short,@plain)=split(/:/,$configline);
                   10285:             %{$prp{$short}} = ();
                   10286: 	    if (@plain > 0) {
                   10287:                 $prp{$short}{'std'} = $plain[0];
                   10288:                 for (my $i=1; $i<@plain; $i++) {
                   10289:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10290:                 }
                   10291:             }
1.448     albertel 10292: 	}
1.135     www      10293:     }
1.448     albertel 10294:     close($config);
1.135     www      10295: }
                   10296: 
                   10297: # ---------------------------------------------------------- Read package table
                   10298: {
1.448     albertel 10299:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10300: 
                   10301:     while (my $configline=<$config>) {
1.483     albertel 10302: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10303: 	chomp($configline);
                   10304: 	my ($short,$plain)=split(/:/,$configline);
                   10305: 	my ($pack,$name)=split(/\&/,$short);
                   10306: 	if ($plain ne '') {
                   10307: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10308: 	    $packagetab{$short}=$plain; 
                   10309: 	}
1.11      www      10310:     }
1.448     albertel 10311:     close($config);
1.329     matthew  10312: }
                   10313: 
1.1056.4.3  raeburn  10314: # ---------------------------------------------------------- Read loncaparev table
                   10315: {
                   10316:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10317:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10318:             while (my $configline=<$config>) {
                   10319:                 chomp($configline);
                   10320:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10321:                 $loncaparevs{$hostid}=$loncaparev;
                   10322:             }
                   10323:             close($config);
                   10324:         }
                   10325:     }
                   10326: }
                   10327: 
                   10328: # ---------------------------------------------------------- Read serverhostID table
                   10329: {
                   10330:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10331:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10332:             while (my $configline=<$config>) {
                   10333:                 chomp($configline);
                   10334:                 my ($name,$id)=split(/:/,$configline);
                   10335:                 $serverhomeIDs{$name}=$id;
                   10336:             }
                   10337:             close($config);
                   10338:         }
                   10339:     }
                   10340: }
                   10341: 
1.1056.4.5! raeburn  10342: {
        !          10343:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
        !          10344:     if (-e $file) {
        !          10345:         my $parser = HTML::LCParser->new($file);
        !          10346:         while (my $token = $parser->get_token()) {
        !          10347:             if ($token->[0] eq 'S') {
        !          10348:                 my $item = $token->[1];
        !          10349:                 my $name = $token->[2]{'name'};
        !          10350:                 my $value = $token->[2]{'value'};
        !          10351:                 if ($item ne '' && $name ne '' && $value ne '') {
        !          10352:                     my $release = $parser->get_text();
        !          10353:                     $release =~ s/(^\s*|\s*$ )//gx;
        !          10354:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
        !          10355:                 }
        !          10356:             }
        !          10357:         }
        !          10358:     }
        !          10359: }
        !          10360: 
1.329     matthew  10361: # ------------- set up temporary directory
                   10362: {
                   10363:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10364: 
1.11      www      10365: }
                   10366: 
1.794     albertel 10367: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10368: 				'compress_threshold'=> 20_000,
                   10369:  			        });
1.185     www      10370: 
1.281     www      10371: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10372: $dumpcount=0;
1.958     www      10373: $locknum=0;
1.22      www      10374: 
1.163     harris41 10375: &logtouch();
1.672     albertel 10376: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10377: $readit=1;
1.564     albertel 10378:     {
                   10379: 	use integer;
                   10380: 	my $test=(2**32)+1;
1.568     albertel 10381: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10382: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10383:     }
1.195     www      10384: }
1.1       albertel 10385: }
1.179     www      10386: 
1.1       albertel 10387: 1;
1.191     harris41 10388: __END__
                   10389: 
1.243     albertel 10390: =pod
                   10391: 
1.191     harris41 10392: =head1 NAME
                   10393: 
1.243     albertel 10394: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10395: 
                   10396: =head1 SYNOPSIS
                   10397: 
1.243     albertel 10398: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10399: 
                   10400:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10401: 
1.243     albertel 10402: Common parameters:
                   10403: 
                   10404: =over 4
                   10405: 
                   10406: =item *
                   10407: 
                   10408: $uname : an internal username (if $cname expecting a course Id specifically)
                   10409: 
                   10410: =item *
                   10411: 
                   10412: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10413: 
                   10414: =item *
                   10415: 
                   10416: $symb : a resource instance identifier
                   10417: 
                   10418: =item *
                   10419: 
                   10420: $namespace : the name of a .db file that contains the data needed or
                   10421: being set.
                   10422: 
                   10423: =back
                   10424: 
1.394     bowersj2 10425: =head1 OVERVIEW
1.191     harris41 10426: 
1.394     bowersj2 10427: lonnet provides subroutines which interact with the
                   10428: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10429: about classes, users, and resources.
1.243     albertel 10430: 
                   10431: For many of these objects you can also use this to store data about
                   10432: them or modify them in various ways.
1.191     harris41 10433: 
1.394     bowersj2 10434: =head2 Symbs
1.191     harris41 10435: 
1.394     bowersj2 10436: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10437: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10438: map, the resource number of the resource in the map, and the URL of
                   10439: the resource itself. The latter is somewhat redundant, but might help
                   10440: if maps change.
                   10441: 
                   10442: An example is
                   10443: 
                   10444:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10445: 
                   10446: The respective map entry is
                   10447: 
                   10448:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10449:   title="Problem 2">
                   10450:  </resource>
                   10451: 
                   10452: Symbs are used by the random number generator, as well as to store and
                   10453: restore data specific to a certain instance of for example a problem.
                   10454: 
                   10455: =head2 Storing And Retrieving Data
                   10456: 
                   10457: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10458: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10459: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10460: is is the non-critical message twin of cstore. These functions are for
                   10461: handlers to store a perl hash to a user's permanent data space in an
                   10462: easy manner, and to retrieve it again on another call. It is expected
                   10463: that a handler would use this once at the beginning to retrieve data,
                   10464: and then again once at the end to send only the new data back.
                   10465: 
                   10466: The data is stored in the user's data directory on the user's
                   10467: homeserver under the ID of the course.
                   10468: 
                   10469: The hash that is returned by restore will have all of the previous
                   10470: value for all of the elements of the hash.
                   10471: 
                   10472: Example:
                   10473: 
                   10474:  #creating a hash
                   10475:  my %hash;
                   10476:  $hash{'foo'}='bar';
                   10477: 
                   10478:  #storing it
                   10479:  &Apache::lonnet::cstore(\%hash);
                   10480: 
                   10481:  #changing a value
                   10482:  $hash{'foo'}='notbar';
                   10483: 
                   10484:  #adding a new value
                   10485:  $hash{'bar'}='foo';
                   10486:  &Apache::lonnet::cstore(\%hash);
                   10487: 
                   10488:  #retrieving the hash
                   10489:  my %history=&Apache::lonnet::restore();
                   10490: 
                   10491:  #print the hash
                   10492:  foreach my $key (sort(keys(%history))) {
                   10493:    print("\%history{$key} = $history{$key}");
                   10494:  }
                   10495: 
                   10496: Will print out:
1.191     harris41 10497: 
1.394     bowersj2 10498:  %history{1:foo} = bar
                   10499:  %history{1:keys} = foo:timestamp
                   10500:  %history{1:timestamp} = 990455579
                   10501:  %history{2:bar} = foo
                   10502:  %history{2:foo} = notbar
                   10503:  %history{2:keys} = foo:bar:timestamp
                   10504:  %history{2:timestamp} = 990455580
                   10505:  %history{bar} = foo
                   10506:  %history{foo} = notbar
                   10507:  %history{timestamp} = 990455580
                   10508:  %history{version} = 2
                   10509: 
                   10510: Note that the special hash entries C<keys>, C<version> and
                   10511: C<timestamp> were added to the hash. C<version> will be equal to the
                   10512: total number of versions of the data that have been stored. The
                   10513: C<timestamp> attribute will be the UNIX time the hash was
                   10514: stored. C<keys> is available in every historical section to list which
                   10515: keys were added or changed at a specific historical revision of a
                   10516: hash.
                   10517: 
                   10518: B<Warning>: do not store the hash that restore returns directly. This
                   10519: will cause a mess since it will restore the historical keys as if the
                   10520: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10521: 
1.394     bowersj2 10522: Calling convention:
1.191     harris41 10523: 
1.394     bowersj2 10524:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10525:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10526: 
1.394     bowersj2 10527: For more detailed information, see lonnet specific documentation.
1.191     harris41 10528: 
1.394     bowersj2 10529: =head1 RETURN MESSAGES
1.191     harris41 10530: 
1.394     bowersj2 10531: =over 4
1.191     harris41 10532: 
1.394     bowersj2 10533: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10534: 
1.394     bowersj2 10535: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10536: when the connection is brought back up
1.191     harris41 10537: 
1.394     bowersj2 10538: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10539: for later delivery
1.191     harris41 10540: 
1.967     bisitz   10541: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10542: 
1.394     bowersj2 10543: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10544: that was requested
1.191     harris41 10545: 
1.243     albertel 10546: =back
1.191     harris41 10547: 
1.243     albertel 10548: =head1 PUBLIC SUBROUTINES
1.191     harris41 10549: 
1.243     albertel 10550: =head2 Session Environment Functions
1.191     harris41 10551: 
1.243     albertel 10552: =over 4
1.191     harris41 10553: 
1.394     bowersj2 10554: =item * 
                   10555: X<appenv()>
1.949     raeburn  10556: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10557: the user envirnoment file, and will be restored for each access this
1.620     albertel 10558: user makes during this session, also modifies the %env for the current
1.949     raeburn  10559: process. Optional rolesarrayref - if defined contains a reference to an array
                   10560: of roles which are exempt from the restriction on modifying user.role entries 
                   10561: in the user's environment.db and in %env.    
1.191     harris41 10562: 
                   10563: =item *
1.394     bowersj2 10564: X<delenv()>
1.987     raeburn  10565: B<delenv($delthis,$regexp)>: removes all items from the session
                   10566: environment file that begin with $delthis. If the 
                   10567: optional second arg - $regexp - is true, $delthis is treated as a 
                   10568: regular expression, otherwise \Q$delthis\E is used. 
                   10569: The values are also deleted from the current processes %env.
1.191     harris41 10570: 
1.795     albertel 10571: =item * get_env_multiple($name) 
                   10572: 
                   10573: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10574: values may be defined and end up as an array ref.
                   10575: 
                   10576: returns an array of values
                   10577: 
1.243     albertel 10578: =back
                   10579: 
                   10580: =head2 User Information
1.191     harris41 10581: 
1.243     albertel 10582: =over 4
1.191     harris41 10583: 
                   10584: =item *
1.394     bowersj2 10585: X<queryauthenticate()>
                   10586: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10587: authentication scheme
                   10588: 
                   10589: =item *
1.394     bowersj2 10590: X<authenticate()>
1.1056.4.3  raeburn  10591: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10592: authenticate user from domain's lib servers (first use the current
                   10593: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10594: $checkdefauth is optional (value is 1 if a check should be made to
                   10595:    authenticate user using default authentication method, and allow
                   10596:    account creation if username does not have account in the domain).
                   10597: $clientcancheckhost is optional (value is 1 if checking whether the
                   10598:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10599: 
                   10600: =item *
1.394     bowersj2 10601: X<homeserver()>
                   10602: B<homeserver($uname,$udom)>: find the server which has
                   10603: the user's directory and files (there must be only one), this caches
                   10604: the answer, and also caches if there is a borken connection.
1.191     harris41 10605: 
                   10606: =item *
1.394     bowersj2 10607: X<idget()>
                   10608: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10609: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10610: username, and only 1 username per ID in a specific domain) (returns
                   10611: hash: id=>name,id=>name)
1.191     harris41 10612: 
                   10613: =item *
1.394     bowersj2 10614: X<idrget()>
                   10615: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10616: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10617: 
                   10618: =item *
1.394     bowersj2 10619: X<idput()>
                   10620: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10621: 
                   10622: =item *
1.394     bowersj2 10623: X<rolesinit()>
                   10624: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10625: 
                   10626: =item *
1.551     albertel 10627: X<getsection()>
                   10628: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10629: course $cname, return section name/number or '' for "not in course"
                   10630: and '-1' for "no section"
                   10631: 
                   10632: =item *
1.394     bowersj2 10633: X<userenvironment()>
                   10634: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10635: passed in @what from the requested user's environment, returns a hash
                   10636: 
1.858     raeburn  10637: =item * 
                   10638: X<userlog_query()>
1.859     albertel 10639: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10640: activity.log file. %filters defines filters applied when parsing the
                   10641: log file. These can be start or end timestamps, or the type of action
                   10642: - log to look for Login or Logout events, check for Checkin or
                   10643: Checkout, role for role selection. The response is in the form
                   10644: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10645: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10646: 
1.243     albertel 10647: =back
                   10648: 
                   10649: =head2 User Roles
                   10650: 
                   10651: =over 4
                   10652: 
                   10653: =item *
                   10654: 
1.810     raeburn  10655: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10656:  F: full access
                   10657:  U,I,K: authentication modes (cxx only)
                   10658:  '': forbidden
                   10659:  1: user needs to choose course
                   10660:  2: browse allowed
1.766     albertel 10661:  A: passphrase authentication needed
1.243     albertel 10662: 
                   10663: =item *
                   10664: 
                   10665: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10666: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10667: and course level
                   10668: 
                   10669: =item *
                   10670: 
1.988     raeburn  10671: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10672: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10673: $type is Course (default) or Community.
1.988     raeburn  10674: If $forcedefault evaluates to true, text returned will be default 
                   10675: text for $type. Otherwise, if this is a course, the text returned 
                   10676: will be a custom name for the role (if defined in the course's 
                   10677: environment).  If no custom name is defined the default is returned.
                   10678:    
1.832     raeburn  10679: =item *
                   10680: 
1.935     raeburn  10681: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10682: All arguments are optional. Returns a hash of a roles, either for
                   10683: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10684: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10685: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10686: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10687: For each key, value is set to colon-separated start and end times for
                   10688: the role.  If no username and domain are specified, will default to
1.934     raeburn  10689: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10690: of role statuses (active, future or previous), roles 
                   10691: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10692: to restrict the list of roles reported. If no array ref is 
                   10693: provided for types, will default to return only active roles.
1.834     albertel 10694: 
1.243     albertel 10695: =back
                   10696: 
                   10697: =head2 User Modification
                   10698: 
                   10699: =over 4
                   10700: 
                   10701: =item *
                   10702: 
1.957     raeburn  10703: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10704: user for the level given by URL.  Optional start and end dates (leave empty
                   10705: string or zero for "no date")
1.191     harris41 10706: 
                   10707: =item *
                   10708: 
1.243     albertel 10709: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10710: change a users, password, possible return values are: ok,
                   10711: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10712: refused
1.191     harris41 10713: 
                   10714: =item *
                   10715: 
1.243     albertel 10716: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10717: 
                   10718: =item *
                   10719: 
1.1056.4.1  raeburn  10720: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10721:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10722: 
                   10723: will update user information (firstname,middlename,lastname,generation,
                   10724: permanentemail), and if forceid is true, student/employee ID also.
                   10725: A user's institutional affiliation(s) can also be updated.
                   10726: User information fields will not be overwritten with empty entries 
                   10727: unless the field is included in the $candelete array reference.
                   10728: This array is included when a single user is modified via "Manage Users",
                   10729: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10730: 
                   10731: =item *
                   10732: 
1.286     matthew  10733: modifystudent
                   10734: 
1.957     raeburn  10735: modify a student's enrollment and identification information.
1.286     matthew  10736: The course id is resolved based on the current users environment.  
                   10737: This means the envoking user must be a course coordinator or otherwise
                   10738: associated with a course.
                   10739: 
1.297     matthew  10740: This call is essentially a wrapper for lonnet::modifyuser and
                   10741: lonnet::modify_student_enrollment
1.286     matthew  10742: 
                   10743: Inputs: 
                   10744: 
                   10745: =over 4
                   10746: 
1.957     raeburn  10747: =item B<$udom> Student's loncapa domain
1.286     matthew  10748: 
1.957     raeburn  10749: =item B<$uname> Student's loncapa login name
1.286     matthew  10750: 
1.964     bisitz   10751: =item B<$uid> Student/Employee ID
1.286     matthew  10752: 
1.957     raeburn  10753: =item B<$umode> Student's authentication mode
1.286     matthew  10754: 
1.957     raeburn  10755: =item B<$upass> Student's password
1.286     matthew  10756: 
1.957     raeburn  10757: =item B<$first> Student's first name
1.286     matthew  10758: 
1.957     raeburn  10759: =item B<$middle> Student's middle name
1.286     matthew  10760: 
1.957     raeburn  10761: =item B<$last> Student's last name
1.286     matthew  10762: 
1.957     raeburn  10763: =item B<$gene> Student's generation
1.286     matthew  10764: 
1.957     raeburn  10765: =item B<$usec> Student's section in course
1.286     matthew  10766: 
                   10767: =item B<$end> Unix time of the roles expiration
                   10768: 
                   10769: =item B<$start> Unix time of the roles start date
                   10770: 
                   10771: =item B<$forceid> If defined, allow $uid to be changed
                   10772: 
                   10773: =item B<$desiredhome> server to use as home server for student
                   10774: 
1.957     raeburn  10775: =item B<$email> Student's permanent e-mail address
                   10776: 
                   10777: =item B<$type> Type of enrollment (auto or manual)
                   10778: 
1.963     raeburn  10779: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10780: 
                   10781: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10782: 
1.963     raeburn  10783: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10784: 
1.963     raeburn  10785: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10786: 
1.963     raeburn  10787: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10788: 
1.286     matthew  10789: =back
1.297     matthew  10790: 
                   10791: =item *
                   10792: 
                   10793: modify_student_enrollment
                   10794: 
                   10795: Change a students enrollment status in a class.  The environment variable
                   10796: 'role.request.course' must be defined for this function to proceed.
                   10797: 
                   10798: Inputs:
                   10799: 
                   10800: =over 4
                   10801: 
                   10802: =item $udom, students domain
                   10803: 
                   10804: =item $uname, students name
                   10805: 
                   10806: =item $uid, students user id
                   10807: 
                   10808: =item $first, students first name
                   10809: 
                   10810: =item $middle
                   10811: 
                   10812: =item $last
                   10813: 
                   10814: =item $gene
                   10815: 
                   10816: =item $usec
                   10817: 
                   10818: =item $end
                   10819: 
                   10820: =item $start
                   10821: 
1.957     raeburn  10822: =item $type
                   10823: 
                   10824: =item $locktype
                   10825: 
                   10826: =item $cid
                   10827: 
                   10828: =item $selfenroll
                   10829: 
                   10830: =item $context
                   10831: 
1.297     matthew  10832: =back
                   10833: 
1.191     harris41 10834: 
                   10835: =item *
                   10836: 
1.243     albertel 10837: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10838: custom role; give a custom role to a user for the level given by URL.  Specify
                   10839: name and domain of role author, and role name
1.191     harris41 10840: 
                   10841: =item *
                   10842: 
1.243     albertel 10843: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10844: 
                   10845: =item *
                   10846: 
1.243     albertel 10847: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10848: 
                   10849: =back
                   10850: 
                   10851: =head2 Course Infomation
                   10852: 
                   10853: =over 4
1.191     harris41 10854: 
                   10855: =item *
                   10856: 
1.631     albertel 10857: coursedescription($courseid) : returns a hash of information about the
                   10858: specified course id, including all environment settings for the
                   10859: course, the description of the course will be in the hash under the
                   10860: key 'description'
1.191     harris41 10861: 
                   10862: =item *
                   10863: 
1.624     albertel 10864: resdata($name,$domain,$type,@which) : request for current parameter
                   10865: setting for a specific $type, where $type is either 'course' or 'user',
                   10866: @what should be a list of parameters to ask about. This routine caches
                   10867: answers for 5 minutes.
1.243     albertel 10868: 
1.877     foxr     10869: =item *
                   10870: 
                   10871: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10872: data base, returning a hash that is keyed by the resource name and has
                   10873: values that are the resource value.  I believe that the timestamps and
                   10874: versions are also returned.
                   10875: 
                   10876: 
1.243     albertel 10877: =back
                   10878: 
                   10879: =head2 Course Modification
                   10880: 
                   10881: =over 4
1.191     harris41 10882: 
                   10883: =item *
                   10884: 
1.243     albertel 10885: writecoursepref($courseid,%prefs) : write preferences (environment
                   10886: database) for a course
1.191     harris41 10887: 
                   10888: =item *
                   10889: 
1.1011    raeburn  10890: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10891: 
                   10892: =item *
                   10893: 
1.1038    raeburn  10894: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10895: 
                   10896: =back
                   10897: 
                   10898: =head2 Resource Subroutines
                   10899: 
                   10900: =over 4
1.191     harris41 10901: 
                   10902: =item *
                   10903: 
1.243     albertel 10904: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10905: 
                   10906: =item *
                   10907: 
1.243     albertel 10908: repcopy($filename) : subscribes to the requested file, and attempts to
                   10909: replicate from the owning library server, Might return
1.607     raeburn  10910: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10911: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10912: resource. Expects the local filesystem pathname
                   10913: (/home/httpd/html/res/....)
                   10914: 
                   10915: =back
                   10916: 
                   10917: =head2 Resource Information
                   10918: 
                   10919: =over 4
1.191     harris41 10920: 
                   10921: =item *
                   10922: 
1.243     albertel 10923: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10924: a vairety of different possible values, $varname should be a request
                   10925: string, and the other parameters can be used to specify who and what
                   10926: one is asking about.
                   10927: 
                   10928: Possible values for $varname are environment.lastname (or other item
                   10929: from the envirnment hash), user.name (or someother aspect about the
                   10930: user), resource.0.maxtries (or some other part and parameter of a
                   10931: resource)
1.204     albertel 10932: 
                   10933: =item *
                   10934: 
1.243     albertel 10935: directcondval($number) : get current value of a condition; reads from a state
                   10936: string
1.204     albertel 10937: 
                   10938: =item *
                   10939: 
1.243     albertel 10940: condval($condidx) : value of condition index based on state
1.204     albertel 10941: 
                   10942: =item *
                   10943: 
1.243     albertel 10944: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10945: resource's metadata, $what should be either a specific key, or either
                   10946: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10947: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10948: 
                   10949: this function automatically caches all requests
1.191     harris41 10950: 
                   10951: =item *
                   10952: 
1.243     albertel 10953: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10954: network of library servers; returns file handle of where SQL and regex results
                   10955: will be stored for query
1.191     harris41 10956: 
                   10957: =item *
                   10958: 
1.243     albertel 10959: symbread($filename) : return symbolic list entry (filename argument optional);
                   10960: returns the data handle
1.191     harris41 10961: 
                   10962: =item *
                   10963: 
1.243     albertel 10964: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10965: a possible symb for the URL in $thisfn, and if is an encryypted
                   10966: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10967: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10968: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10969: 
1.191     harris41 10970: 
                   10971: =item *
                   10972: 
1.243     albertel 10973: symbclean($symb) : removes versions numbers from a symb, returns the
                   10974: cleaned symb
1.191     harris41 10975: 
                   10976: =item *
                   10977: 
1.243     albertel 10978: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10979: course map, user must be in a course for it to work.
1.191     harris41 10980: 
                   10981: =item *
                   10982: 
1.243     albertel 10983: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10984: 
                   10985: =item *
                   10986: 
1.243     albertel 10987: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10988: a random seed, all arguments are optional, if they aren't sent it uses the
                   10989: environment to derive them. Note: if symb isn't sent and it can't get one
                   10990: from &symbread it will use the current time as its return value
1.191     harris41 10991: 
                   10992: =item *
                   10993: 
1.243     albertel 10994: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10995: unfakeable, receipt
1.191     harris41 10996: 
                   10997: =item *
                   10998: 
1.620     albertel 10999: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11000: 
                   11001: =item *
                   11002: 
1.243     albertel 11003: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11004: 
                   11005: =item *
                   11006: 
1.243     albertel 11007: 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 11008: 
                   11009: =item *
                   11010: 
1.243     albertel 11011: 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 11012: 
                   11013: =item *
                   11014: 
1.243     albertel 11015: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11016: 
                   11017: =item *
                   11018: 
1.243     albertel 11019: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11020: forcing spreadsheet to reevaluate the resource scores next time.
                   11021: 
                   11022: =back
                   11023: 
                   11024: =head2 Storing/Retreiving Data
                   11025: 
                   11026: =over 4
1.191     harris41 11027: 
                   11028: =item *
                   11029: 
1.243     albertel 11030: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11031: for this url; hashref needs to be given and should be a \%hashname; the
                   11032: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11033: be derived from the env
1.191     harris41 11034: 
                   11035: =item *
                   11036: 
1.243     albertel 11037: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11038: uses critical subroutine
1.191     harris41 11039: 
                   11040: =item *
                   11041: 
1.243     albertel 11042: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11043: all args are optional
1.191     harris41 11044: 
                   11045: =item *
                   11046: 
1.717     albertel 11047: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11048: dumps the complete (or key matching regexp) namespace into a hash
                   11049: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11050: normally &store()ed into
                   11051: 
                   11052: $range should be either an integer '100' (give me the first 100
                   11053:                                            matching records)
                   11054:               or be  two integers sperated by a - with no spaces
                   11055:                  '30-50' (give me the 30th through the 50th matching
                   11056:                           records)
                   11057: 
                   11058: 
                   11059: =item *
                   11060: 
                   11061: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11062: replaces a &store() version of data with a replacement set of data
                   11063: for a particular resource in a namespace passed in the $storehash hash 
                   11064: reference
                   11065: 
                   11066: =item *
                   11067: 
1.243     albertel 11068: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11069: works very similar to store/cstore, but all data is stored in a
                   11070: temporary location and can be reset using tmpreset, $storehash should
                   11071: be a hash reference, returns nothing on success
1.191     harris41 11072: 
                   11073: =item *
                   11074: 
1.243     albertel 11075: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11076: similar to restore, but all data is stored in a temporary location and
                   11077: can be reset using tmpreset. Returns a hash of values on success,
                   11078: error string otherwise.
1.191     harris41 11079: 
                   11080: =item *
                   11081: 
1.243     albertel 11082: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11083: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11084: 
                   11085: =item *
                   11086: 
1.243     albertel 11087: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11088: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11089: 
                   11090: =item *
                   11091: 
1.243     albertel 11092: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11093: namesp ($udom and $uname are optional)
1.191     harris41 11094: 
                   11095: =item *
                   11096: 
1.702     albertel 11097: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11098: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11099: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11100: 
1.702     albertel 11101: $range should be either an integer '100' (give me the first 100
                   11102:                                            matching records)
                   11103:               or be  two integers sperated by a - with no spaces
                   11104:                  '30-50' (give me the 30th through the 50th matching
                   11105:                           records)
1.449     matthew  11106: =item *
                   11107: 
                   11108: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11109: $store can be a scalar, an array reference, or if the amount to be 
                   11110: incremented is > 1, a hash reference.
                   11111: 
                   11112: ($udom and $uname are optional)
1.191     harris41 11113: 
                   11114: =item *
                   11115: 
1.243     albertel 11116: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11117: ($udom and $uname are optional)
1.191     harris41 11118: 
                   11119: =item *
                   11120: 
1.243     albertel 11121: cput($namespace,$storehash,$udom,$uname) : critical put
                   11122: ($udom and $uname are optional)
1.191     harris41 11123: 
                   11124: =item *
                   11125: 
1.748     albertel 11126: newput($namespace,$storehash,$udom,$uname) :
                   11127: 
                   11128: Attempts to store the items in the $storehash, but only if they don't
                   11129: currently exist, if this succeeds you can be certain that you have 
                   11130: successfully created a new key value pair in the $namespace db.
                   11131: 
                   11132: 
                   11133: Args:
                   11134:  $namespace: name of database to store values to
                   11135:  $storehash: hashref to store to the db
                   11136:  $udom: (optional) domain of user containing the db
                   11137:  $uname: (optional) name of user caontaining the db
                   11138: 
                   11139: Returns:
                   11140:  'ok' -> succeeded in storing all keys of $storehash
                   11141:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11142:                         least <key> already existed in the db (other
                   11143:                         requested keys may also already exist)
1.967     bisitz   11144:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11145:  'con_lost' -> unable to contact request server
                   11146:  'refused' -> action was not allowed by remote machine
                   11147: 
                   11148: 
                   11149: =item *
                   11150: 
1.243     albertel 11151: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11152: reference filled in from namesp (encrypts the return communication)
                   11153: ($udom and $uname are optional)
1.191     harris41 11154: 
                   11155: =item *
                   11156: 
1.243     albertel 11157: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11158: critical subroutine
                   11159: 
1.806     raeburn  11160: =item *
                   11161: 
1.860     raeburn  11162: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11163: array reference filled in from namespace found in domain level on either
                   11164: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11165: 
                   11166: =item *
                   11167: 
1.860     raeburn  11168: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11169: domain level either on specified domain server ($uhome) or primary domain 
                   11170: server ($udom and $uhome are optional)
1.806     raeburn  11171: 
1.943     raeburn  11172: =item * 
                   11173: 
                   11174: get_domain_defaults($target_domain) : returns hash with defaults for
                   11175: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11176: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11177: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11178: Values are retrieved from cache (if current), or from domain's configuration.db
                   11179: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11180: or lonTabs/domain.tab. 
                   11181: 
                   11182: %domdefaults = &get_auth_defaults($target_domain);
                   11183: 
1.243     albertel 11184: =back
                   11185: 
                   11186: =head2 Network Status Functions
                   11187: 
                   11188: =over 4
1.191     harris41 11189: 
                   11190: =item *
                   11191: 
                   11192: dirlist($uri) : return directory list based on URI
                   11193: 
                   11194: =item *
                   11195: 
1.243     albertel 11196: spareserver() : find server with least workload from spare.tab
                   11197: 
1.986     foxr     11198: 
                   11199: =item *
                   11200: 
                   11201: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11202: if there is no corresponding loncapa host.
                   11203: 
1.243     albertel 11204: =back
                   11205: 
1.986     foxr     11206: 
1.243     albertel 11207: =head2 Apache Request
                   11208: 
                   11209: =over 4
1.191     harris41 11210: 
                   11211: =item *
                   11212: 
1.243     albertel 11213: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11214: localhost, posts hash
                   11215: 
                   11216: =back
                   11217: 
                   11218: =head2 Data to String to Data
                   11219: 
                   11220: =over 4
1.191     harris41 11221: 
                   11222: =item *
                   11223: 
1.243     albertel 11224: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11225: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11226: 
                   11227: =item *
                   11228: 
1.243     albertel 11229: hashref2str($hashref) : convert a hashref into a string complete with
                   11230: escaping and '=' and '&' separators, supports elements that are
                   11231: arrayrefs and hashrefs
1.191     harris41 11232: 
                   11233: =item *
                   11234: 
1.243     albertel 11235: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11236: with escaping and '&' separators, supports elements that are arrayrefs
                   11237: and hashrefs
1.191     harris41 11238: 
                   11239: =item *
                   11240: 
1.243     albertel 11241: str2hash($string) : convert string to hash using unescaping and
                   11242: splitting on '=' and '&', supports elements that are arrayrefs and
                   11243: hashrefs
1.191     harris41 11244: 
                   11245: =item *
                   11246: 
1.243     albertel 11247: str2array($string) : convert string to hash using unescaping and
                   11248: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11249: 
                   11250: =back
                   11251: 
                   11252: =head2 Logging Routines
                   11253: 
                   11254: =over 4
                   11255: 
                   11256: These routines allow one to make log messages in the lonnet.log and
                   11257: lonnet.perm logfiles.
1.191     harris41 11258: 
                   11259: =item *
                   11260: 
1.243     albertel 11261: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11262: 
                   11263: =item *
                   11264: 
1.243     albertel 11265: logthis() : append message to the normal lonnet.log file, it gets
                   11266: preiodically rolled over and deleted.
1.191     harris41 11267: 
                   11268: =item *
                   11269: 
1.243     albertel 11270: logperm() : append a permanent message to lonnet.perm.log, this log
                   11271: file never gets deleted by any automated portion of the system, only
                   11272: messages of critical importance should go in here.
                   11273: 
                   11274: =back
                   11275: 
                   11276: =head2 General File Helper Routines
                   11277: 
                   11278: =over 4
1.191     harris41 11279: 
                   11280: =item *
                   11281: 
1.481     raeburn  11282: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11283: (a) files in /uploaded
                   11284:   (i) If a local copy of the file exists - 
                   11285:       compares modification date of local copy with last-modified date for 
                   11286:       definitive version stored on home server for course. If local copy is 
                   11287:       stale, requests a new version from the home server and stores it. 
                   11288:       If the original has been removed from the home server, then local copy 
                   11289:       is unlinked.
                   11290:   (ii) If local copy does not exist -
                   11291:       requests the file from the home server and stores it. 
                   11292:   
                   11293:   If $caller is 'uploadrep':  
                   11294:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11295:     for request for files originally uploaded via DOCS. 
                   11296:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11297:   
                   11298:   Otherwise:
                   11299:      This indicates a call from the content generation phase of the request.
                   11300:      -  returns the entire contents of the file or -1.
                   11301:      
                   11302: (b) files in /res
                   11303:    - returns the entire contents of a file or -1; 
                   11304:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11305: 
1.712     albertel 11306: 
                   11307: =item *
                   11308: 
                   11309: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11310:                   reference
                   11311: 
                   11312: returns either a stat() list of data about the file or an empty list
                   11313: if the file doesn't exist or couldn't find out about it (connection
                   11314: problems or user unknown)
                   11315: 
1.191     harris41 11316: =item *
                   11317: 
1.243     albertel 11318: filelocation($dir,$file) : returns file system location of a file
                   11319: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11320: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11321: and a file of ../bob will become /a/bob)
1.191     harris41 11322: 
                   11323: =item *
                   11324: 
                   11325: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11326: filelocation except for hrefs
                   11327: 
                   11328: =item *
                   11329: 
                   11330: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11331: 
1.243     albertel 11332: =back
                   11333: 
1.608     albertel 11334: =head2 Usererfile file routines (/uploaded*)
                   11335: 
                   11336: =over 4
                   11337: 
                   11338: =item *
                   11339: 
                   11340: userfileupload(): main rotine for putting a file in a user or course's
                   11341:                   filespace, arguments are,
                   11342: 
1.620     albertel 11343:  formname - required - this is the name of the element in $env where the
1.608     albertel 11344:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11345:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11346:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 11347:  coursedoc - if true, store the file in the course of the active role
                   11348:              of the current user
                   11349:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11350:          if undefined, it will be placed in "unknown"
                   11351: 
                   11352:  (This routine calls clean_filename() to remove any dangerous
                   11353:  characters from the filename, and then calls finuserfileupload() to
                   11354:  complete the transaction)
                   11355: 
                   11356:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11357:  and /adm/notfound.html if unsuccessful
                   11358: 
                   11359: =item *
                   11360: 
                   11361: clean_filename(): routine for cleaing a filename up for storage in
                   11362:                  userfile space, argument is:
                   11363: 
                   11364:  filename - proposed filename
                   11365: 
                   11366: returns: the new clean filename
                   11367: 
                   11368: =item *
                   11369: 
                   11370: finishuserfileupload(): routine that creaes and sends the file to
                   11371: userspace, probably shouldn't be called directly
                   11372: 
                   11373:   docuname: username or courseid of destination for the file
                   11374:   docudom: domain of user/course of destination for the file
                   11375:   formname: same as for userfileupload()
                   11376:   fname: filename (inculding subdirectories) for the file
                   11377: 
                   11378:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11379:  and /adm/notfound.html if unsuccessful
                   11380: 
                   11381: =item *
                   11382: 
                   11383: renameuserfile(): renames an existing userfile to a new name
                   11384: 
                   11385:   Args:
                   11386:    docuname: username or courseid of destination for the file
                   11387:    docudom: domain of user/course of destination for the file
                   11388:    old: current file name (including any subdirs under userfiles)
                   11389:    new: desired file name (including any subdirs under userfiles)
                   11390: 
                   11391: =item *
                   11392: 
                   11393: mkdiruserfile(): creates a directory is a userfiles dir
                   11394: 
                   11395:   Args:
                   11396:    docuname: username or courseid of destination for the file
                   11397:    docudom: domain of user/course of destination for the file
                   11398:    dir: dir to create (including any subdirs under userfiles)
                   11399: 
                   11400: =item *
                   11401: 
                   11402: removeuserfile(): removes a file that exists in userfiles
                   11403: 
                   11404:   Args:
                   11405:    docuname: username or courseid of destination for the file
                   11406:    docudom: domain of user/course of destination for the file
                   11407:    fname: filname to delete (including any subdirs under userfiles)
                   11408: 
                   11409: =item *
                   11410: 
                   11411: removeuploadedurl(): convience function for removeuserfile()
                   11412: 
                   11413:   Args:
                   11414:    url:  a full /uploaded/... url to delete
                   11415: 
1.747     albertel 11416: =item * 
                   11417: 
                   11418: get_portfile_permissions():
                   11419:   Args:
                   11420:     domain: domain of user or course contain the portfolio files
                   11421:     user: name of user or num of course contain the portfolio files
                   11422:   Returns:
                   11423:     hashref of a dump of the proper file_permissions.db
                   11424:    
                   11425: 
                   11426: =item * 
                   11427: 
                   11428: get_access_controls():
                   11429: 
                   11430: Args:
                   11431:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11432:   group: (optional) the group you want the files associated with
                   11433:   file: (optional) the file you want access info on
                   11434: 
                   11435: Returns:
1.749     raeburn  11436:     a hash (keys are file names) of hashes containing
                   11437:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11438:         values are XML containing access control settings (see below) 
1.747     albertel 11439: 
                   11440: Internal notes:
                   11441: 
1.749     raeburn  11442:  access controls are stored in file_permissions.db as key=value pairs.
                   11443:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11444:         where scope -> public,guest,course,group,domains or users.
                   11445:               end -> UNIX time for end of access (0 -> no end date)
                   11446:               start -> UNIX time for start of access
                   11447: 
                   11448:     value -> XML description of access control
                   11449:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11450:             <start></start>
                   11451:             <end></end>
                   11452: 
                   11453:             <password></password>  for scope type = guest
                   11454: 
                   11455:             <domain></domain>     for scope type = course or group
                   11456:             <number></number>
                   11457:             <roles id="">
                   11458:              <role></role>
                   11459:              <access></access>
                   11460:              <section></section>
                   11461:              <group></group>
                   11462:             </roles>
                   11463: 
                   11464:             <dom></dom>         for scope type = domains
                   11465: 
                   11466:             <users>             for scope type = users
                   11467:              <user>
                   11468:               <uname></uname>
                   11469:               <udom></udom>
                   11470:              </user>
                   11471:             </users>
                   11472:            </scope> 
                   11473:               
                   11474:  Access data is also aggregated for each file in an additional key=value pair:
                   11475:  key -> path to file/file_name\0accesscontrol 
                   11476:  value -> reference to hash
                   11477:           hash contains key = value pairs
                   11478:           where key = uniqueID:scope_end_start
                   11479:                 value = UNIX time record was last updated
                   11480: 
                   11481:           Used to improve speed of look-ups of access controls for each file.  
                   11482:  
                   11483:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11484: 
                   11485: modify_access_controls():
                   11486: 
                   11487: Modifies access controls for a portfolio file
                   11488: Args
                   11489: 1. file name
                   11490: 2. reference to hash of required changes,
                   11491: 3. domain
                   11492: 4. username
                   11493:   where domain,username are the domain of the portfolio owner 
                   11494:   (either a user or a course) 
                   11495: 
                   11496: Returns:
                   11497: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11498: 2. result of deletions ('ok' or 'error', with error message).
                   11499: 3. reference to hash of any new or updated access controls.
                   11500: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11501:    key = integer (inbound ID)
                   11502:    value = uniqueID  
1.747     albertel 11503: 
1.608     albertel 11504: =back
                   11505: 
1.243     albertel 11506: =head2 HTTP Helper Routines
                   11507: 
                   11508: =over 4
                   11509: 
1.191     harris41 11510: =item *
                   11511: 
                   11512: escape() : unpack non-word characters into CGI-compatible hex codes
                   11513: 
                   11514: =item *
                   11515: 
                   11516: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11517: 
1.243     albertel 11518: =back
                   11519: 
                   11520: =head1 PRIVATE SUBROUTINES
                   11521: 
                   11522: =head2 Underlying communication routines (Shouldn't call)
                   11523: 
                   11524: =over 4
                   11525: 
                   11526: =item *
                   11527: 
                   11528: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11529: 
                   11530: =item *
                   11531: 
                   11532: reply() : uses subreply to send a message to remote machine, logs all failures
                   11533: 
                   11534: =item *
                   11535: 
                   11536: critical() : passes a critical message to another server; if cannot
                   11537: get through then place message in connection buffer directory and
                   11538: returns con_delayed, if incapable of saving message, returns
                   11539: con_failed
                   11540: 
                   11541: =item *
                   11542: 
                   11543: reconlonc() : tries to reconnect lonc client processes.
                   11544: 
                   11545: =back
                   11546: 
                   11547: =head2 Resource Access Logging
                   11548: 
                   11549: =over 4
                   11550: 
                   11551: =item *
                   11552: 
                   11553: flushcourselogs() : flush (save) buffer logs and access logs
                   11554: 
                   11555: =item *
                   11556: 
                   11557: courselog($what) : save message for course in hash
                   11558: 
                   11559: =item *
                   11560: 
                   11561: courseacclog($what) : save message for course using &courselog().  Perform
                   11562: special processing for specific resource types (problems, exams, quizzes, etc).
                   11563: 
1.191     harris41 11564: =item *
                   11565: 
                   11566: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11567: as a PerlChildExitHandler
1.243     albertel 11568: 
                   11569: =back
                   11570: 
                   11571: =head2 Other
                   11572: 
                   11573: =over 4
                   11574: 
                   11575: =item *
                   11576: 
                   11577: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11578: 
                   11579: =back
                   11580: 
                   11581: =cut
1.877     foxr     11582: 

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