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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.29! raeburn     4: # $Id: lonnet.pm,v 1.1056.4.28 2011/07/28 18:30:16 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.1056.4.13  raeburn    98: use File::Copy;
1.676     albertel   99: 
1.195     www       100: my $readit;
1.550     foxr      101: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  102: 
1.619     albertel  103: require Exporter;
                    104: 
                    105: our @ISA = qw (Exporter);
                    106: our @EXPORT = qw(%env);
                    107: 
1.449     matthew   108: 
1.1       albertel  109: # --------------------------------------------------------------------- Logging
1.729     www       110: {
                    111:     my $logid;
                    112:     sub instructor_log {
1.957     raeburn   113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    114:         if (($cnum eq '') || ($cdom eq '')) {
                    115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    117:         }
1.729     www       118: 	$logid++;
1.957     raeburn   119:         my $now = time();
                    120: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       122: 				    { $id => {
                    123: 					'exe_uname' => $env{'user.name'},
                    124: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   125: 					'exe_time'  => $now,
1.730     www       126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    127: 					'delflag'   => $delflag,
                    128: 					'logentry'  => $storehash,
                    129: 					'uname'     => $uname,
                    130: 					'udom'      => $udom,
                    131: 				    }
1.957     raeburn   132: 				  },$cdom,$cnum);
1.729     www       133:     }
                    134: }
1.1       albertel  135: 
1.163     harris41  136: sub logtouch {
                    137:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  138:     unless (-e "$execdir/logs/lonnet.log") {	
                    139: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  140: 	close $fh;
                    141:     }
                    142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    144: }
                    145: 
1.1       albertel  146: sub logthis {
                    147:     my $message=shift;
                    148:     my $execdir=$perlvar{'lonDaemons'};
                    149:     my $now=time;
                    150:     my $local=localtime($now);
1.448     albertel  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    153: 	print $fh $logstring;
1.448     albertel  154: 	close($fh);
                    155:     }
1.1       albertel  156:     return 1;
                    157: }
                    158: 
                    159: sub logperm {
                    160:     my $message=shift;
                    161:     my $execdir=$perlvar{'lonDaemons'};
                    162:     my $now=time;
                    163:     my $local=localtime($now);
1.448     albertel  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    165: 	print $fh "$now:$message:$local\n";
                    166: 	close($fh);
                    167:     }
1.1       albertel  168:     return 1;
                    169: }
                    170: 
1.850     albertel  171: sub create_connection {
1.853     albertel  172:     my ($hostname,$lonid) = @_;
1.851     albertel  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  174: 				     Type    => SOCK_STREAM,
                    175: 				     Timeout => 10);
                    176:     return 0 if (!$client);
1.890     albertel  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  178:     my $result = <$client>;
                    179:     chomp($result);
                    180:     return 1 if ($result eq 'done');
                    181:     return 0;
                    182: }
                    183: 
1.983     raeburn   184: sub get_server_timezone {
                    185:     my ($cnum,$cdom) = @_;
                    186:     my $home=&homeserver($cnum,$cdom);
                    187:     if ($home ne 'no_host') {
                    188:         my $cachetime = 24*3600;
                    189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    190:         if (defined($cached)) {
                    191:             return $timezone;
                    192:         } else {
                    193:             my $timezone = &reply('servertimezone',$home);
                    194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    195:         }
                    196:     }
                    197: }
1.850     albertel  198: 
1.1056.4.25  raeburn   199: sub get_server_distarch {
                    200:     my ($lonhost,$ignore_cache) = @_;
                    201:     if (defined($lonhost)) {
                    202:         if (!defined(&hostname($lonhost))) {
                    203:             return;
                    204:         }
                    205:         my $cachetime = 12*3600;
                    206:         if (!$ignore_cache) {
                    207:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    208:             if (defined($cached)) {
                    209:                 return $distarch;
                    210:             }
                    211:         }
                    212:         my $rep = &reply('serverdistarch',$lonhost);
                    213:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    214:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    215:                 $rep eq '') {
                    216:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    217:         }
                    218:     }
                    219:     return;
                    220: }
                    221: 
1.993     raeburn   222: sub get_server_loncaparev {
1.1056.4.3  raeburn   223:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   224:     if (defined($lonhost)) {
                    225:         if (!defined(&hostname($lonhost))) {
                    226:             undef($lonhost);
                    227:         }
                    228:     }
                    229:     if (!defined($lonhost)) {
                    230:         if (defined(&domain($dom,'primary'))) {
                    231:             $lonhost=&domain($dom,'primary');
                    232:             if ($lonhost eq 'no_host') {
                    233:                 undef($lonhost);
                    234:             }
                    235:         }
                    236:     }
                    237:     if (defined($lonhost)) {
1.1056.4.3  raeburn   238:         my $cachetime = 12*3600;
                    239:         if (!$ignore_cache) {
                    240:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    241:             if (defined($cached)) {
                    242:                 return $loncaparev;
                    243:             }
                    244:         }
                    245:         my ($answer,$loncaparev);
                    246:         my @ids=&current_machine_ids();
                    247:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    248:             $answer = $perlvar{'lonVersion'};
1.1056.4.7  raeburn   249:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   250:                 $loncaparev = $1;
                    251:             }
                    252:         } else {
                    253:             $answer = &reply('serverloncaparev',$lonhost);
                    254:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    255:                 if ($caller eq 'loncron') {
                    256:                     my $ua=new LWP::UserAgent;
1.1056.4.8  raeburn   257:                     $ua->timeout(4);
1.1056.4.3  raeburn   258:                     my $protocol = $protocol{$lonhost};
                    259:                     $protocol = 'http' if ($protocol ne 'https');
                    260:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    261:                     my $request=new HTTP::Request('GET',$url);
                    262:                     my $response=$ua->request($request);
                    263:                     unless ($response->is_error()) {
                    264:                         my $content = $response->content;
1.1056.4.7  raeburn   265:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3  raeburn   266:                             $loncaparev = $1;
                    267:                         }
                    268:                     }
                    269:                 } else {
                    270:                     $loncaparev = $loncaparevs{$lonhost};
                    271:                 }
1.1056.4.7  raeburn   272:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   273:                 $loncaparev = $1;
                    274:             }
                    275:         }
                    276:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    277:     }
                    278: }
                    279: 
                    280: sub get_server_homeID {
                    281:     my ($hostname,$ignore_cache,$caller) = @_;
                    282:     unless ($ignore_cache) {
                    283:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993     raeburn   284:         if (defined($cached)) {
1.1056.4.3  raeburn   285:             return $serverhomeID;
                    286:         }
                    287:     }
                    288:     my $cachetime = 12*3600;
                    289:     my $serverhomeID;
                    290:     if ($caller eq 'loncron') {
                    291:         my @machine_ids = &machine_ids($hostname);
                    292:         foreach my $id (@machine_ids) {
                    293:             my $response = &reply('serverhomeID',$id);
                    294:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    295:                 $serverhomeID = $response;
                    296:                 last;
                    297:             }
1.993     raeburn   298:         }
1.1056.4.3  raeburn   299:         if ($serverhomeID eq '') {
                    300:             $serverhomeID = $machine_ids[-1];
                    301:         }
                    302:     } else {
                    303:         $serverhomeID = $serverhomeIDs{$hostname};
1.993     raeburn   304:     }
1.1056.4.3  raeburn   305:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993     raeburn   306: }
                    307: 
1.1       albertel  308: # -------------------------------------------------- Non-critical communication
                    309: sub subreply {
                    310:     my ($cmd,$server)=@_;
1.838     albertel  311:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      312:     #
                    313:     #  With loncnew process trimming, there's a timing hole between lonc server
                    314:     #  process exit and the master server picking up the listen on the AF_UNIX
                    315:     #  socket.  In that time interval, a lock file will exist:
                    316: 
                    317:     my $lockfile=$peerfile.".lock";
                    318:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    319: 	sleep(1);
                    320:     }
                    321:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      322:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      323:     #
1.550     foxr      324:     #   We'll give the connection a few tries before abandoning it.  If
                    325:     #   connection is not possible, we'll con_lost back to the client.
                    326:     #   
                    327:     my $client;
                    328:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    329: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    330: 				      Type    => SOCK_STREAM,
                    331: 				      Timeout => 10);
1.869     albertel  332: 	if ($client) {
1.550     foxr      333: 	    last;		# Connected!
1.850     albertel  334: 	} else {
1.853     albertel  335: 	    &create_connection(&hostname($server),$server);
1.550     foxr      336: 	}
1.850     albertel  337:         sleep(1);		# Try again later if failed connection.
1.550     foxr      338:     }
                    339:     my $answer;
                    340:     if ($client) {
1.704     albertel  341: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      342: 	$answer=<$client>;
                    343: 	if (!$answer) { $answer="con_lost"; }
                    344: 	chomp($answer);
                    345:     } else {
                    346: 	$answer = 'con_lost';	# Failed connection.
                    347:     }
1.1       albertel  348:     return $answer;
                    349: }
                    350: 
                    351: sub reply {
                    352:     my ($cmd,$server)=@_;
1.838     albertel  353:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  354:     my $answer=subreply($cmd,$server);
1.65      www       355:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  356:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       357:                 " $cmd to $server returned $answer</font>");
                    358:     }
1.1       albertel  359:     return $answer;
                    360: }
                    361: 
                    362: # ----------------------------------------------------------- Send USR1 to lonc
                    363: 
                    364: sub reconlonc {
1.891     albertel  365:     my ($lonid) = @_;
                    366:     my $hostname = &hostname($lonid);
                    367:     if ($lonid) {
                    368: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    369: 	if ($hostname && -e $peerfile) {
                    370: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    371: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    372: 					     Type    => SOCK_STREAM,
                    373: 					     Timeout => 10);
                    374: 	    if ($client) {
                    375: 		print $client ("reset_retries\n");
                    376: 		my $answer=<$client>;
                    377: 		#reset just this one.
                    378: 	    }
                    379: 	}
                    380: 	return;
                    381:     }
                    382: 
1.836     www       383:     &logthis("Trying to reconnect lonc");
1.1       albertel  384:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  385:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  386: 	my $loncpid=<$fh>;
                    387:         chomp($loncpid);
                    388:         if (kill 0 => $loncpid) {
                    389: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    390:             kill USR1 => $loncpid;
                    391:             sleep 1;
1.836     www       392:          } else {
1.12      www       393: 	    &logthis(
1.672     albertel  394:                "<font color=\"blue\">WARNING:".
1.12      www       395:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  396:         }
                    397:     } else {
1.836     www       398: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  399:     }
                    400: }
                    401: 
                    402: # ------------------------------------------------------ Critical communication
1.12      www       403: 
1.1       albertel  404: sub critical {
                    405:     my ($cmd,$server)=@_;
1.838     albertel  406:     unless (&hostname($server)) {
1.672     albertel  407:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       408:                " Critical message to unknown server ($server)</font>");
                    409:         return 'no_such_host';
                    410:     }
1.1       albertel  411:     my $answer=reply($cmd,$server);
                    412:     if ($answer eq 'con_lost') {
                    413: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  414: 	my $answer=reply($cmd,$server);
1.1       albertel  415:         if ($answer eq 'con_lost') {
                    416:             my $now=time;
                    417:             my $middlename=$cmd;
1.5       www       418:             $middlename=substr($middlename,0,16);
1.1       albertel  419:             $middlename=~s/\W//g;
                    420:             my $dfilename=
1.305     www       421:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    422:             $dumpcount++;
1.1       albertel  423:             {
1.448     albertel  424: 		my $dfh;
                    425: 		if (open($dfh,">$dfilename")) {
                    426: 		    print $dfh "$cmd\n"; 
                    427: 		    close($dfh);
                    428: 		}
1.1       albertel  429:             }
                    430:             sleep 2;
                    431:             my $wcmd='';
                    432:             {
1.448     albertel  433: 		my $dfh;
                    434: 		if (open($dfh,"<$dfilename")) {
                    435: 		    $wcmd=<$dfh>; 
                    436: 		    close($dfh);
                    437: 		}
1.1       albertel  438:             }
                    439:             chomp($wcmd);
1.7       www       440:             if ($wcmd eq $cmd) {
1.672     albertel  441: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       442:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  443:                 &logperm("D:$server:$cmd");
                    444: 	        return 'con_delayed';
                    445:             } else {
1.672     albertel  446:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       447:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  448:                 &logperm("F:$server:$cmd");
                    449:                 return 'con_failed';
                    450:             }
                    451:         }
                    452:     }
                    453:     return $answer;
1.405     albertel  454: }
                    455: 
1.755     albertel  456: # ------------------------------------------- check if return value is an error
                    457: 
                    458: sub error {
                    459:     my ($result) = @_;
1.756     albertel  460:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  461: 	if ($2 == 2) { return undef; }
                    462: 	return $1;
                    463:     }
                    464:     return undef;
                    465: }
                    466: 
1.783     albertel  467: sub convert_and_load_session_env {
                    468:     my ($lonidsdir,$handle)=@_;
                    469:     my @profile;
                    470:     {
1.917     albertel  471: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    472: 	if (!$opened) {
1.915     albertel  473: 	    return 0;
                    474: 	}
1.783     albertel  475: 	flock($idf,LOCK_SH);
                    476: 	@profile=<$idf>;
                    477: 	close($idf);
                    478:     }
                    479:     my %temp_env;
                    480:     foreach my $line (@profile) {
1.786     albertel  481: 	if ($line !~ m/=/) {
                    482: 	    return 0;
                    483: 	}
1.783     albertel  484: 	chomp($line);
                    485: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    486: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    487:     }
                    488:     unlink("$lonidsdir/$handle.id");
                    489:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    490: 	    0640)) {
                    491: 	%disk_env = %temp_env;
                    492: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    493: 	untie(%disk_env);
                    494:     }
1.786     albertel  495:     return 1;
1.783     albertel  496: }
                    497: 
1.374     www       498: # ------------------------------------------- Transfer profile into environment
1.780     albertel  499: my $env_loaded;
                    500: sub transfer_profile_to_env {
1.788     albertel  501:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    502:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       503: 
1.720     albertel  504:     if (!defined($lonidsdir)) {
                    505: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    506:     }
                    507:     if (!defined($handle)) {
                    508:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    509:     }
                    510: 
1.786     albertel  511:     my $convert;
                    512:     {
1.917     albertel  513:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    514: 	if (!$opened) {
1.915     albertel  515: 	    return;
                    516: 	}
1.786     albertel  517: 	flock($idf,LOCK_SH);
                    518: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    519: 		&GDBM_READER(),0640)) {
                    520: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    521: 	    untie(%disk_env);
                    522: 	} else {
                    523: 	    $convert = 1;
                    524: 	}
                    525:     }
                    526:     if ($convert) {
                    527: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    528: 	    &logthis("Failed to load session, or convert session.");
                    529: 	}
1.374     www       530:     }
1.783     albertel  531: 
1.786     albertel  532:     my %remove;
1.783     albertel  533:     while ( my $envname = each(%env) ) {
1.433     matthew   534:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    535:             if ($time < time-300) {
1.783     albertel  536:                 $remove{$key}++;
1.433     matthew   537:             }
                    538:         }
                    539:     }
1.783     albertel  540: 
1.619     albertel  541:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  542:     $env_loaded=1;
1.783     albertel  543:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   544:         &delenv($expired_key);
1.374     www       545:     }
1.1       albertel  546: }
                    547: 
1.916     albertel  548: # ---------------------------------------------------- Check for valid session 
                    549: sub check_for_valid_session {
                    550:     my ($r) = @_;
                    551:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    552:     my $lonid=$cookies{'lonID'};
                    553:     return undef if (!$lonid);
                    554: 
                    555:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    556:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    557:     return undef if (!-e "$lonidsdir/$handle.id");
                    558: 
1.917     albertel  559:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    560:     return undef if (!$opened);
1.916     albertel  561: 
                    562:     flock($idf,LOCK_SH);
                    563:     my %disk_env;
                    564:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    565: 	    &GDBM_READER(),0640)) {
                    566: 	return undef;	
                    567:     }
                    568: 
                    569:     if (!defined($disk_env{'user.name'})
                    570: 	|| !defined($disk_env{'user.domain'})) {
                    571: 	return undef;
                    572:     }
                    573:     return $handle;
                    574: }
                    575: 
1.830     albertel  576: sub timed_flock {
                    577:     my ($file,$lock_type) = @_;
                    578:     my $failed=0;
                    579:     eval {
                    580: 	local $SIG{__DIE__}='DEFAULT';
                    581: 	local $SIG{ALRM}=sub {
                    582: 	    $failed=1;
                    583: 	    die("failed lock");
                    584: 	};
                    585: 	alarm(13);
                    586: 	flock($file,$lock_type);
                    587: 	alarm(0);
                    588:     };
                    589:     if ($failed) {
                    590: 	return undef;
                    591:     } else {
                    592: 	return 1;
                    593:     }
                    594: }
                    595: 
1.5       www       596: # ---------------------------------------------------------- Append Environment
                    597: 
                    598: sub appenv {
1.949     raeburn   599:     my ($newenv,$roles) = @_;
                    600:     if (ref($newenv) eq 'HASH') {
                    601:         foreach my $key (keys(%{$newenv})) {
                    602:             my $refused = 0;
                    603: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    604:                 $refused = 1;
                    605:                 if (ref($roles) eq 'ARRAY') {
                    606:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    607:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    608:                         $refused = 0;
                    609:                     }
                    610:                 }
                    611:             }
                    612:             if ($refused) {
                    613:                 &logthis("<font color=\"blue\">WARNING: ".
                    614:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    615:                          .'</font>');
                    616: 	        delete($newenv->{$key});
                    617:             } else {
                    618:                 $env{$key}=$newenv->{$key};
                    619:             }
                    620:         }
                    621:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    622:         if ($opened
                    623: 	    && &timed_flock($env_file,LOCK_EX)
                    624: 	    &&
                    625: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    626: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    627: 	    while (my ($key,$value) = each(%{$newenv})) {
                    628: 	        $disk_env{$key} = $value;
                    629: 	    }
                    630: 	    untie(%disk_env);
1.35      www       631:         }
1.191     harris41  632:     }
1.56      www       633:     return 'ok';
                    634: }
                    635: # ----------------------------------------------------- Delete from Environment
                    636: 
                    637: sub delenv {
1.987     raeburn   638:     my ($delthis,$regexp) = @_;
1.56      www       639:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  640:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       641:                 "Attempt to delete from environment ".$delthis);
                    642:         return 'error';
                    643:     }
1.917     albertel  644:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    645:     if ($opened
1.915     albertel  646: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  647: 	&&
                    648: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    649: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  650: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   651: 	    if ($regexp) {
                    652:                 if ($key=~/^$delthis/) {
                    653:                     delete($env{$key});
                    654:                     delete($disk_env{$key});
                    655:                 } 
                    656:             } else {
                    657:                 if ($key=~/^\Q$delthis\E/) {
                    658: 		    delete($env{$key});
                    659: 		    delete($disk_env{$key});
                    660: 	        }
                    661:             }
1.448     albertel  662: 	}
1.783     albertel  663: 	untie(%disk_env);
1.5       www       664:     }
                    665:     return 'ok';
1.369     albertel  666: }
                    667: 
1.790     albertel  668: sub get_env_multiple {
                    669:     my ($name) = @_;
                    670:     my @values;
                    671:     if (defined($env{$name})) {
                    672:         # exists is it an array
                    673:         if (ref($env{$name})) {
                    674:             @values=@{ $env{$name} };
                    675:         } else {
                    676:             $values[0]=$env{$name};
                    677:         }
                    678:     }
                    679:     return(@values);
                    680: }
                    681: 
1.958     www       682: # ------------------------------------------------------------------- Locking
                    683: 
                    684: sub set_lock {
                    685:     my ($text)=@_;
                    686:     $locknum++;
                    687:     my $id=$$.'-'.$locknum;
                    688:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    689:              'session.lock.'.$id => $text});
                    690:     return $id;
                    691: }
                    692: 
                    693: sub get_locks {
                    694:     my $num=0;
                    695:     my %texts=();
                    696:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    697:        if ($lock=~/\w/) {
                    698:           $num++;
                    699:           $texts{$lock}=$env{'session.lock.'.$lock};
                    700:        }
                    701:    }
                    702:    return ($num,%texts);
                    703: }
                    704: 
                    705: sub remove_lock {
                    706:     my ($id)=@_;
                    707:     my $newlocks='';
                    708:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    709:        if (($lock=~/\w/) && ($lock ne $id)) {
                    710:           $newlocks.=','.$lock;
                    711:        }
                    712:     }
                    713:     &appenv({'session.locks' => $newlocks});
                    714:     &delenv('session.lock.'.$id);
                    715: }
                    716: 
                    717: sub remove_all_locks {
                    718:     my $activelocks=$env{'session.locks'};
                    719:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    720:        if ($lock=~/\w/) {
                    721:           &remove_lock($lock);
                    722:        }
                    723:     }
                    724: }
                    725: 
                    726: 
1.369     albertel  727: # ------------------------------------------ Find out current server userload
                    728: sub userload {
                    729:     my $numusers=0;
                    730:     {
                    731: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    732: 	my $filename;
                    733: 	my $curtime=time;
                    734: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  735: 	    next if ($filename eq '.' || $filename eq '..');
                    736: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  737: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  738: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  739: 	}
                    740: 	closedir(LONIDS);
                    741:     }
                    742:     my $userloadpercent=0;
                    743:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    744:     if ($maxuserload) {
1.371     albertel  745: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  746:     }
1.372     albertel  747:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  748:     return $userloadpercent;
1.283     www       749: }
                    750: 
                    751: # ------------------------------------------ Fight off request when overloaded
                    752: 
                    753: sub overloaderror {
                    754:     my ($r,$checkserver)=@_;
                    755:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    756:     my $loadavg;
                    757:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  758:        open(my $loadfile,'/proc/loadavg');
1.283     www       759:        $loadavg=<$loadfile>;
                    760:        $loadavg =~ s/\s.*//g;
1.285     matthew   761:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  762:        close($loadfile);
1.283     www       763:     } else {
                    764:        $loadavg=&reply('load',$checkserver);
                    765:     }
1.285     matthew   766:     my $overload=$loadavg-100;
1.283     www       767:     if ($overload>0) {
1.285     matthew   768: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       769:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       770:         return 413;
1.283     www       771:     }    
                    772:     return '';
1.5       www       773: }
1.1       albertel  774: 
                    775: # ------------------------------ Find server with least workload from spare.tab
1.11      www       776: 
1.1       albertel  777: sub spareserver {
1.1056.4.23  raeburn   778:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  779:     my $spare_server;
1.370     albertel  780:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  781:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    782:                                                      :  $userloadpercent;
1.1056.4.8  raeburn   783:     my ($uint_dom,$remotesessions);
1.1056.4.23  raeburn   784:     if (($udom ne '') && (&domain($udom) ne '')) {
                    785:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1.1056.4.8  raeburn   786:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.23  raeburn   787:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
1.1056.4.8  raeburn   788:         $remotesessions = $udomdefaults{'remotesessions'};
                    789:     }
1.784     albertel  790:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8  raeburn   791:         if ($uint_dom) {
1.1056.4.23  raeburn   792:             next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    793:                                          $try_server));
1.1056.4.8  raeburn   794:         }
1.784     albertel  795: 	($spare_server, $lowest_load) =
                    796: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    797:     }
                    798: 
                    799:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    800: 
                    801:     if (!$found_server) {
                    802: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8  raeburn   803:             if ($uint_dom) {
1.1056.4.23  raeburn   804:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    805:                                              $try_server));
1.1056.4.8  raeburn   806:             }
1.784     albertel  807: 	    ($spare_server, $lowest_load) =
                    808: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    809: 	}
                    810:     }
                    811: 
                    812:     if (!$want_server_name) {
1.968     raeburn   813:         my $protocol = 'http';
                    814:         if ($protocol{$spare_server} eq 'https') {
                    815:             $protocol = $protocol{$spare_server};
                    816:         }
1.1001    raeburn   817:         if (defined($spare_server)) {
                    818:             my $hostname = &hostname($spare_server);
1.1056.4.8  raeburn   819:             if (defined($hostname)) {
1.1001    raeburn   820: 	        $spare_server = $protocol.'://'.$hostname;
                    821:             }
                    822:         }
1.784     albertel  823:     }
                    824:     return $spare_server;
                    825: }
                    826: 
                    827: sub compare_server_load {
                    828:     my ($try_server, $spare_server, $lowest_load) = @_;
                    829: 
                    830:     my $loadans     = &reply('load',    $try_server);
                    831:     my $userloadans = &reply('userload',$try_server);
                    832: 
                    833:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.29! raeburn   834:         return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  835:     }
                    836: 
                    837:     my $load;
                    838:     if ($loadans =~ /\d/) {
                    839: 	if ($userloadans =~ /\d/) {
                    840: 	    #both are numbers, pick the bigger one
                    841: 	    $load = ($loadans > $userloadans) ? $loadans 
                    842: 		                              : $userloadans;
1.411     albertel  843: 	} else {
1.784     albertel  844: 	    $load = $loadans;
1.411     albertel  845: 	}
1.784     albertel  846:     } else {
                    847: 	$load = $userloadans;
                    848:     }
                    849: 
                    850:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    851: 	$spare_server = $try_server;
                    852: 	$lowest_load  = $load;
1.370     albertel  853:     }
1.784     albertel  854:     return ($spare_server,$lowest_load);
1.202     matthew   855: }
1.914     albertel  856: 
                    857: # --------------------------- ask offload servers if user already has a session
                    858: sub find_existing_session {
                    859:     my ($udom,$uname) = @_;
                    860:     foreach my $try_server (@{ $spareid{'primary'} },
                    861: 			    @{ $spareid{'default'} }) {
                    862: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    863:     }
                    864:     return;
                    865: }
                    866: 
                    867: # -------------------------------- ask if server already has a session for user
                    868: sub has_user_session {
                    869:     my ($lonid,$udom,$uname) = @_;
                    870:     my $result = &reply(join(':','userhassession',
                    871: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    872:     return 1 if ($result eq 'ok');
                    873: 
                    874:     return 0;
                    875: }
                    876: 
1.1056.4.3  raeburn   877: # --------- determine least loaded server in a user's domain which allows login
                    878: 
                    879: sub choose_server {
                    880:     my ($udom) = @_;
                    881:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
                    882:     my %servers = &get_servers($udom);
                    883:     my $lowest_load = 30000;
                    884:     my ($login_host,$hostname);
                    885:     foreach my $lonhost (keys(%servers)) {
                    886:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    887:         if ($loginvia eq '') {
                    888:             ($login_host, $lowest_load) =
                    889:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    890:         }
                    891:     }
                    892:     if ($login_host ne '') {
                    893:         $hostname = $servers{$login_host};
                    894:     }
                    895:     return ($login_host,$hostname);
                    896: }
                    897: 
1.202     matthew   898: # --------------------------------------------- Try to change a user's password
                    899: 
                    900: sub changepass {
1.799     raeburn   901:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   902:     $currentpass = &escape($currentpass);
                    903:     $newpass     = &escape($newpass);
1.1030    raeburn   904:     my $lonhost = $perlvar{'lonHostID'};
                    905:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   906: 		       $server);
                    907:     if (! $answer) {
                    908: 	&logthis("No reply on password change request to $server ".
                    909: 		 "by $uname in domain $udom.");
                    910:     } elsif ($answer =~ "^ok") {
                    911:         &logthis("$uname in $udom successfully changed their password ".
                    912: 		 "on $server.");
                    913:     } elsif ($answer =~ "^pwchange_failure") {
                    914: 	&logthis("$uname in $udom was unable to change their password ".
                    915: 		 "on $server.  The action was blocked by either lcpasswd ".
                    916: 		 "or pwchange");
                    917:     } elsif ($answer =~ "^non_authorized") {
                    918:         &logthis("$uname in $udom did not get their password correct when ".
                    919: 		 "attempting to change it on $server.");
                    920:     } elsif ($answer =~ "^auth_mode_error") {
                    921:         &logthis("$uname in $udom attempted to change their password despite ".
                    922: 		 "not being locally or internally authenticated on $server.");
                    923:     } elsif ($answer =~ "^unknown_user") {
                    924:         &logthis("$uname in $udom attempted to change their password ".
                    925: 		 "on $server but were unable to because $server is not ".
                    926: 		 "their home server.");
                    927:     } elsif ($answer =~ "^refused") {
                    928: 	&logthis("$server refused to change $uname in $udom password because ".
                    929: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   930:     } elsif ($answer =~ "invalid_client") {
                    931:         &logthis("$server refused to change $uname in $udom password because ".
                    932:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   933:     }
                    934:     return $answer;
1.1       albertel  935: }
                    936: 
1.169     harris41  937: # ----------------------- Try to determine user's current authentication scheme
                    938: 
                    939: sub queryauthenticate {
                    940:     my ($uname,$udom)=@_;
1.456     albertel  941:     my $uhome=&homeserver($uname,$udom);
                    942:     if (!$uhome) {
                    943: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    944: 	return 'no_host';
                    945:     }
                    946:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    947:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    948: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  949:     }
1.456     albertel  950:     return $answer;
1.169     harris41  951: }
                    952: 
1.1       albertel  953: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       954: 
1.1       albertel  955: sub authenticate {
1.1056.4.3  raeburn   956:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  957:     $upass=&escape($upass);
                    958:     $uname= &LONCAPA::clean_username($uname);
1.836     www       959:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   960:     my $newhome;
1.836     www       961:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    962: # Maybe the machine was offline and only re-appeared again recently?
                    963:         &reconlonc();
                    964: # One more
1.952     raeburn   965: 	$uhome=&homeserver($uname,$udom,1);
                    966:         if (($uhome eq 'no_host') && $checkdefauth) {
                    967:             if (defined(&domain($udom,'primary'))) {
                    968:                 $newhome=&domain($udom,'primary');
                    969:             }
                    970:             if ($newhome ne '') {
                    971:                 $uhome = $newhome;
                    972:             }
                    973:         }
1.836     www       974: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    975: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   976: 	    return 'no_host';
                    977:         }
1.1       albertel  978:     }
1.1056.4.3  raeburn   979:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  980:     if ($answer eq 'authorized') {
1.952     raeburn   981:         if ($newhome) {
                    982:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    983:             return 'no_account_on_host'; 
                    984:         } else {
                    985:             &logthis("User $uname at $udom authorized by $uhome");
                    986:             return $uhome;
                    987:         }
1.471     albertel  988:     }
                    989:     if ($answer eq 'non_authorized') {
                    990: 	&logthis("User $uname at $udom rejected by $uhome");
                    991: 	return 'no_host'; 
1.9       www       992:     }
1.471     albertel  993:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  994:     return 'no_host';
                    995: }
                    996: 
1.1056.4.3  raeburn   997: sub can_host_session {
                    998:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
                    999:     my $canhost = 1;
                   1000:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
                   1001:     if (ref($remotesessions) eq 'HASH') {
                   1002:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
                   1003:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
                   1004:                 $canhost = 0;
                   1005:             } else {
                   1006:                 $canhost = 1;
                   1007:             }
                   1008:         }
                   1009:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
                   1010:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
                   1011:                 $canhost = 1;
                   1012:             } else {
                   1013:                 $canhost = 0;
                   1014:             }
                   1015:         }
                   1016:         if ($canhost) {
                   1017:             if ($remotesessions->{'version'} ne '') {
                   1018:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1019:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1020:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1021:                         my $major = $1;
                   1022:                         my $minor = $2;
                   1023:                         if (($major < $reqmajor ) ||
                   1024:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1025:                             $canhost = 0;
                   1026:                         }
                   1027:                     } else {
                   1028:                         $canhost = 0;
                   1029:                     }
                   1030:                 }
                   1031:             }
                   1032:         }
                   1033:     }
                   1034:     if ($canhost) {
                   1035:         if (ref($hostedsessions) eq 'HASH') {
1.1056.4.28  raeburn  1036:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1037:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.3  raeburn  1038:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1056.4.28  raeburn  1039:                 if (($uint_dom ne '') && 
                   1040:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1056.4.3  raeburn  1041:                     $canhost = 0;
                   1042:                 } else {
                   1043:                     $canhost = 1;
                   1044:                 }
                   1045:             }
                   1046:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1056.4.28  raeburn  1047:                 if (($uint_dom ne '') && 
                   1048:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1056.4.3  raeburn  1049:                     $canhost = 1;
                   1050:                 } else {
                   1051:                     $canhost = 0;
                   1052:                 }
                   1053:             }
                   1054:         }
                   1055:     }
                   1056:     return $canhost;
                   1057: }
                   1058: 
1.1056.4.8  raeburn  1059: sub spare_can_host {
                   1060:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1061:     my $canhost=1;
                   1062:     my @intdoms;
                   1063:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1064:     if (ref($internet_names) eq 'ARRAY') {
                   1065:         @intdoms = @{$internet_names};
                   1066:     }
                   1067:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1068:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1069:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1070:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1071:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1072:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1073:                                      $remotesessions,
                   1074:                                      $defdomdefaults{'hostedsessions'});
                   1075:     }
                   1076:     return $canhost;
                   1077: }
                   1078: 
1.1       albertel 1079: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1080: 
1.599     albertel 1081: my %homecache;
1.1       albertel 1082: sub homeserver {
1.230     stredwic 1083:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1084:     my $index="$uname:$udom";
1.426     albertel 1085: 
1.599     albertel 1086:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1087: 
                   1088:     my %servers = &get_servers($udom,'library');
                   1089:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1090:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1091: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1092: 
                   1093: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1094: 	if ($answer eq 'found') {
                   1095: 	    delete($badServerCache{$tryserver}); 
                   1096: 	    return $homecache{$index}=$tryserver;
                   1097: 	} elsif ($answer eq 'no_host') {
                   1098: 	    $badServerCache{$tryserver}=1;
                   1099: 	}
1.1       albertel 1100:     }    
                   1101:     return 'no_host';
1.70      www      1102: }
                   1103: 
                   1104: # ------------------------------------- Find the usernames behind a list of IDs
                   1105: 
                   1106: sub idget {
                   1107:     my ($udom,@ids)=@_;
                   1108:     my %returnhash=();
                   1109:     
1.841     albertel 1110:     my %servers = &get_servers($udom,'library');
                   1111:     foreach my $tryserver (keys(%servers)) {
                   1112: 	my $idlist=join('&',@ids);
                   1113: 	$idlist=~tr/A-Z/a-z/; 
                   1114: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1115: 	my @answer=();
                   1116: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1117: 	    @answer=split(/\&/,$reply);
                   1118: 	}                    ;
                   1119: 	my $i;
                   1120: 	for ($i=0;$i<=$#ids;$i++) {
                   1121: 	    if ($answer[$i]) {
                   1122: 		$returnhash{$ids[$i]}=$answer[$i];
                   1123: 	    } 
                   1124: 	}
                   1125:     } 
1.70      www      1126:     return %returnhash;
                   1127: }
                   1128: 
                   1129: # ------------------------------------- Find the IDs behind a list of usernames
                   1130: 
                   1131: sub idrget {
                   1132:     my ($udom,@unames)=@_;
                   1133:     my %returnhash=();
1.800     albertel 1134:     foreach my $uname (@unames) {
                   1135:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1136:     }
1.70      www      1137:     return %returnhash;
                   1138: }
                   1139: 
                   1140: # ------------------------------- Store away a list of names and associated IDs
                   1141: 
                   1142: sub idput {
                   1143:     my ($udom,%ids)=@_;
                   1144:     my %servers=();
1.800     albertel 1145:     foreach my $uname (keys(%ids)) {
                   1146: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1147:         my $uhom=&homeserver($uname,$udom);
1.70      www      1148:         if ($uhom ne 'no_host') {
1.800     albertel 1149:             my $id=&escape($ids{$uname});
1.70      www      1150:             $id=~tr/A-Z/a-z/;
1.800     albertel 1151:             my $esc_unam=&escape($uname);
1.70      www      1152: 	    if ($servers{$uhom}) {
1.800     albertel 1153: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1154:             } else {
1.800     albertel 1155:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1156:             }
                   1157:         }
1.191     harris41 1158:     }
1.800     albertel 1159:     foreach my $server (keys(%servers)) {
                   1160:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1161:     }
1.344     www      1162: }
                   1163: 
1.1023    raeburn  1164: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1165: sub dump_dom {
1.1023    raeburn  1166:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1167:     if (!$udom) {
                   1168:         $udom=$env{'user.domain'};
                   1169:     }
                   1170:     my %returnhash;
1.1023    raeburn  1171:     if ($udom) {
                   1172:         my $uname = &get_domainconfiguser($udom);
                   1173:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1174:     }
                   1175:     return %returnhash;
                   1176: }
                   1177: 
1.1023    raeburn  1178: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1179: 
                   1180: sub get_dom {
1.860     raeburn  1181:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1182:     my $items='';
                   1183:     foreach my $item (@$storearr) {
                   1184:         $items.=&escape($item).'&';
                   1185:     }
                   1186:     $items=~s/\&$//;
1.860     raeburn  1187:     if (!$udom) {
                   1188:         $udom=$env{'user.domain'};
                   1189:         if (defined(&domain($udom,'primary'))) {
                   1190:             $uhome=&domain($udom,'primary');
                   1191:         } else {
1.874     albertel 1192:             undef($uhome);
1.860     raeburn  1193:         }
                   1194:     } else {
                   1195:         if (!$uhome) {
                   1196:             if (defined(&domain($udom,'primary'))) {
                   1197:                 $uhome=&domain($udom,'primary');
                   1198:             }
                   1199:         }
                   1200:     }
                   1201:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1202:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1203:         my %returnhash;
1.875     albertel 1204:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1205:             return %returnhash;
                   1206:         }
1.806     raeburn  1207:         my @pairs=split(/\&/,$rep);
                   1208:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1209:             return @pairs;
                   1210:         }
                   1211:         my $i=0;
                   1212:         foreach my $item (@$storearr) {
                   1213:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1214:             $i++;
                   1215:         }
                   1216:         return %returnhash;
                   1217:     } else {
1.880     banghart 1218:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1219:     }
                   1220: }
                   1221: 
                   1222: # -------------------------------------------- put items in domain db files 
                   1223: 
                   1224: sub put_dom {
1.860     raeburn  1225:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1226:     if (!$udom) {
                   1227:         $udom=$env{'user.domain'};
                   1228:         if (defined(&domain($udom,'primary'))) {
                   1229:             $uhome=&domain($udom,'primary');
                   1230:         } else {
1.874     albertel 1231:             undef($uhome);
1.860     raeburn  1232:         }
                   1233:     } else {
                   1234:         if (!$uhome) {
                   1235:             if (defined(&domain($udom,'primary'))) {
                   1236:                 $uhome=&domain($udom,'primary');
                   1237:             }
                   1238:         }
                   1239:     } 
                   1240:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1241:         my $items='';
                   1242:         foreach my $item (keys(%$storehash)) {
                   1243:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1244:         }
                   1245:         $items=~s/\&$//;
                   1246:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1247:     } else {
1.860     raeburn  1248:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1249:     }
                   1250: }
                   1251: 
1.1023    raeburn  1252: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1253: sub newput_dom {
1.1023    raeburn  1254:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1255:     my $result;
                   1256:     if (!$udom) {
                   1257:         $udom=$env{'user.domain'};
                   1258:     }
1.1023    raeburn  1259:     if ($udom) {
                   1260:         my $uname = &get_domainconfiguser($udom);
                   1261:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1262:     }
                   1263:     return $result;
                   1264: }
                   1265: 
1.1023    raeburn  1266: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1267: sub del_dom {
1.1023    raeburn  1268:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1269:     if (ref($storearr) eq 'ARRAY') {
                   1270:         if (!$udom) {
                   1271:             $udom=$env{'user.domain'};
                   1272:         }
1.1023    raeburn  1273:         if ($udom) {
                   1274:             my $uname = &get_domainconfiguser($udom); 
                   1275:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1276:         }
                   1277:     }
                   1278: }
                   1279: 
1.1023    raeburn  1280: # ----------------------------------construct domainconfig user for a domain 
                   1281: sub get_domainconfiguser {
                   1282:     my ($udom) = @_;
                   1283:     return $udom.'-domainconfig';
                   1284: }
                   1285: 
1.837     raeburn  1286: sub retrieve_inst_usertypes {
                   1287:     my ($udom) = @_;
                   1288:     my (%returnhash,@order);
1.989     raeburn  1289:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1290:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1291:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1292:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1293:         @order = @{$domdefs{'inststatusorder'}};
                   1294:     } else {
                   1295:         if (defined(&domain($udom,'primary'))) {
                   1296:             my $uhome=&domain($udom,'primary');
                   1297:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1298:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1299:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1300:                 return (\%returnhash,\@order);
                   1301:             }
                   1302:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1303:             my @pairs=split(/\&/,$hashitems);
                   1304:             foreach my $item (@pairs) {
                   1305:                 my ($key,$value)=split(/=/,$item,2);
                   1306:                 $key = &unescape($key);
                   1307:                 next if ($key =~ /^error: 2 /);
                   1308:                 $returnhash{$key}=&thaw_unescape($value);
                   1309:             }
                   1310:             my @esc_order = split(/\&/,$orderitems);
                   1311:             foreach my $item (@esc_order) {
                   1312:                 push(@order,&unescape($item));
                   1313:             }
                   1314:         } else {
                   1315:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1316:         }
                   1317:     }
                   1318:     return (\%returnhash,\@order);
                   1319: }
                   1320: 
1.868     raeburn  1321: sub is_domainimage {
                   1322:     my ($url) = @_;
                   1323:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1324:         if (&domain($1) ne '') {
                   1325:             return '1';
                   1326:         }
                   1327:     }
                   1328:     return;
                   1329: }
                   1330: 
1.899     raeburn  1331: sub inst_directory_query {
                   1332:     my ($srch) = @_;
                   1333:     my $udom = $srch->{'srchdomain'};
                   1334:     my %results;
                   1335:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1336:     my $outcome;
1.899     raeburn  1337:     if ($homeserver ne '') {
1.904     albertel 1338: 	my $queryid=&reply("querysend:instdirsearch:".
                   1339: 			   &escape($srch->{'srchby'}).':'.
                   1340: 			   &escape($srch->{'srchterm'}).':'.
                   1341: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1342: 	my $host=&hostname($homeserver);
                   1343: 	if ($queryid !~/^\Q$host\E\_/) {
                   1344: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1345: 	    return;
                   1346: 	}
                   1347: 	my $response = &get_query_reply($queryid);
                   1348: 	my $maxtries = 5;
                   1349: 	my $tries = 1;
                   1350: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1351: 	    $response = &get_query_reply($queryid);
                   1352: 	    $tries ++;
                   1353: 	}
                   1354: 
                   1355:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1356:             if ($response eq 'unavailable') {
                   1357:                 $outcome = $response;
                   1358:             } else {
                   1359:                 $outcome = 'ok';
                   1360:                 my @matches = split(/\n/,$response);
                   1361:                 foreach my $match (@matches) {
                   1362:                     my ($key,$value) = split(/=/,$match);
                   1363:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1364:                 }
1.899     raeburn  1365:             }
                   1366:         }
                   1367:     }
1.909     raeburn  1368:     return ($outcome,%results);
1.899     raeburn  1369: }
                   1370: 
                   1371: sub usersearch {
                   1372:     my ($srch) = @_;
                   1373:     my $dom = $srch->{'srchdomain'};
                   1374:     my %results;
                   1375:     my %libserv = &all_library();
                   1376:     my $query = 'usersearch';
                   1377:     foreach my $tryserver (keys(%libserv)) {
                   1378:         if (&host_domain($tryserver) eq $dom) {
                   1379:             my $host=&hostname($tryserver);
                   1380:             my $queryid=
1.911     raeburn  1381:                 &reply("querysend:".&escape($query).':'.
                   1382:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1383:                        &escape($srch->{'srchtype'}).':'.
                   1384:                        &escape($srch->{'srchterm'}),$tryserver);
                   1385:             if ($queryid !~/^\Q$host\E\_/) {
                   1386:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1387:                 next;
1.899     raeburn  1388:             }
                   1389:             my $reply = &get_query_reply($queryid);
                   1390:             my $maxtries = 1;
                   1391:             my $tries = 1;
                   1392:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1393:                 $reply = &get_query_reply($queryid);
                   1394:                 $tries ++;
                   1395:             }
                   1396:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1397:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1398:             } else {
1.911     raeburn  1399:                 my @matches;
                   1400:                 if ($reply =~ /\n/) {
                   1401:                     @matches = split(/\n/,$reply);
                   1402:                 } else {
                   1403:                     @matches = split(/\&/,$reply);
                   1404:                 }
1.899     raeburn  1405:                 foreach my $match (@matches) {
                   1406:                     my ($uname,$udom,%userhash);
1.911     raeburn  1407:                     foreach my $entry (split(/:/,$match)) {
                   1408:                         my ($key,$value) =
                   1409:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1410:                         $userhash{$key} = $value;
                   1411:                         if ($key eq 'username') {
                   1412:                             $uname = $value;
                   1413:                         } elsif ($key eq 'domain') {
                   1414:                             $udom = $value;
1.911     raeburn  1415:                         }
1.899     raeburn  1416:                     }
                   1417:                     $results{$uname.':'.$udom} = \%userhash;
                   1418:                 }
                   1419:             }
                   1420:         }
                   1421:     }
                   1422:     return %results;
                   1423: }
                   1424: 
1.912     raeburn  1425: sub get_instuser {
                   1426:     my ($udom,$uname,$id) = @_;
                   1427:     my $homeserver = &domain($udom,'primary');
                   1428:     my ($outcome,%results);
                   1429:     if ($homeserver ne '') {
                   1430:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1431:                            &escape($id).':'.&escape($udom),$homeserver);
                   1432:         my $host=&hostname($homeserver);
                   1433:         if ($queryid !~/^\Q$host\E\_/) {
                   1434:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1435:             return;
                   1436:         }
                   1437:         my $response = &get_query_reply($queryid);
                   1438:         my $maxtries = 5;
                   1439:         my $tries = 1;
                   1440:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1441:             $response = &get_query_reply($queryid);
                   1442:             $tries ++;
                   1443:         }
                   1444:         if (!&error($response) && $response ne 'refused') {
                   1445:             if ($response eq 'unavailable') {
                   1446:                 $outcome = $response;
                   1447:             } else {
                   1448:                 $outcome = 'ok';
                   1449:                 my @matches = split(/\n/,$response);
                   1450:                 foreach my $match (@matches) {
                   1451:                     my ($key,$value) = split(/=/,$match);
                   1452:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1453:                 }
                   1454:             }
                   1455:         }
                   1456:     }
                   1457:     my %userinfo;
                   1458:     if (ref($results{$uname}) eq 'HASH') {
                   1459:         %userinfo = %{$results{$uname}};
                   1460:     } 
                   1461:     return ($outcome,%userinfo);
                   1462: }
                   1463: 
                   1464: sub inst_rulecheck {
1.923     raeburn  1465:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1466:     my %returnhash;
                   1467:     if ($udom ne '') {
                   1468:         if (ref($rules) eq 'ARRAY') {
                   1469:             @{$rules} = map {&escape($_);} (@{$rules});
                   1470:             my $rulestr = join(':',@{$rules});
                   1471:             my $homeserver=&domain($udom,'primary');
                   1472:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1473:                 my $response;
                   1474:                 if ($item eq 'username') {                
                   1475:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1476:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1477:                                               $homeserver));
1.923     raeburn  1478:                 } elsif ($item eq 'id') {
                   1479:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1480:                                               ':'.&escape($id).':'.$rulestr,
                   1481:                                               $homeserver));
1.945     raeburn  1482:                 } elsif ($item eq 'selfcreate') {
                   1483:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1484:                                                &escape($udom).':'.&escape($uname).
                   1485:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1486:                 }
1.912     raeburn  1487:                 if ($response ne 'refused') {
                   1488:                     my @pairs=split(/\&/,$response);
                   1489:                     foreach my $item (@pairs) {
                   1490:                         my ($key,$value)=split(/=/,$item,2);
                   1491:                         $key = &unescape($key);
                   1492:                         next if ($key =~ /^error: 2 /);
                   1493:                         $returnhash{$key}=&thaw_unescape($value);
                   1494:                     }
                   1495:                 }
                   1496:             }
                   1497:         }
                   1498:     }
                   1499:     return %returnhash;
                   1500: }
                   1501: 
                   1502: sub inst_userrules {
1.923     raeburn  1503:     my ($udom,$check) = @_;
1.912     raeburn  1504:     my (%ruleshash,@ruleorder);
                   1505:     if ($udom ne '') {
                   1506:         my $homeserver=&domain($udom,'primary');
                   1507:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1508:             my $response;
                   1509:             if ($check eq 'id') {
                   1510:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1511:                                  $homeserver);
1.943     raeburn  1512:             } elsif ($check eq 'email') {
                   1513:                 $response=&reply('instemailrules:'.&escape($udom),
                   1514:                                  $homeserver);
1.923     raeburn  1515:             } else {
                   1516:                 $response=&reply('instuserrules:'.&escape($udom),
                   1517:                                  $homeserver);
                   1518:             }
1.912     raeburn  1519:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1520:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1521:                 ($response ne 'no_such_host')) {
                   1522:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1523:                 my @pairs=split(/\&/,$hashitems);
                   1524:                 foreach my $item (@pairs) {
                   1525:                     my ($key,$value)=split(/=/,$item,2);
                   1526:                     $key = &unescape($key);
                   1527:                     next if ($key =~ /^error: 2 /);
                   1528:                     $ruleshash{$key}=&thaw_unescape($value);
                   1529:                 }
                   1530:                 my @esc_order = split(/\&/,$orderitems);
                   1531:                 foreach my $item (@esc_order) {
                   1532:                     push(@ruleorder,&unescape($item));
                   1533:                 }
                   1534:             }
                   1535:         }
                   1536:     }
                   1537:     return (\%ruleshash,\@ruleorder);
                   1538: }
                   1539: 
1.976     raeburn  1540: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1541: 
                   1542: sub get_domain_defaults {
                   1543:     my ($domain) = @_;
                   1544:     my $cachetime = 60*60*24;
                   1545:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1546:     if (defined($cached)) {
                   1547:         if (ref($result) eq 'HASH') {
                   1548:             return %{$result};
                   1549:         }
                   1550:     }
                   1551:     my %domdefaults;
                   1552:     my %domconfig =
1.989     raeburn  1553:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1554:                                   'requestcourses','inststatus',
1.1056.4.3  raeburn  1555:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1556:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1557:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1558:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1559:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1560:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1561:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1562:     } else {
                   1563:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1564:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1565:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1566:     }
1.976     raeburn  1567:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1568:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1569:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1570:         } else {
                   1571:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1572:         } 
                   1573:         my @usertools = ('aboutme','blog','portfolio');
                   1574:         foreach my $item (@usertools) {
                   1575:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1576:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1577:             }
                   1578:         }
                   1579:     }
1.985     raeburn  1580:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1581:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1582:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1583:         }
                   1584:     }
1.989     raeburn  1585:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1586:         foreach my $item ('inststatustypes','inststatusorder') {
                   1587:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1588:         }
                   1589:     }
1.1047    raeburn  1590:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1591:         foreach my $item ('canuse_pdfforms') {
                   1592:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1593:         }
                   1594:     }
1.1056.4.3  raeburn  1595:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1596:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1597:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1598:         }
                   1599:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1600:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1601:         }
                   1602:     }
1.943     raeburn  1603:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1604:                                   $cachetime);
                   1605:     return %domdefaults;
                   1606: }
                   1607: 
1.344     www      1608: # --------------------------------------------------- Assign a key to a student
                   1609: 
                   1610: sub assign_access_key {
1.364     www      1611: #
                   1612: # a valid key looks like uname:udom#comments
                   1613: # comments are being appended
                   1614: #
1.498     www      1615:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1616:     $kdom=
1.620     albertel 1617:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1618:     $knum=
1.620     albertel 1619:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1620:     $cdom=
1.620     albertel 1621:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1622:     $cnum=
1.620     albertel 1623:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1624:     $udom=$env{'user.name'} unless (defined($udom));
                   1625:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1626:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1627:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1628:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1629:                                                   # assigned to this person
                   1630:                                                   # - this should not happen,
1.345     www      1631:                                                   # unless something went wrong
                   1632:                                                   # the first time around
                   1633: # ready to assign
1.364     www      1634:         $logentry=$1.'; '.$logentry;
1.496     www      1635:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1636:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1637: # key now belongs to user
1.346     www      1638: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1639:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1640:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1641:                 return 'ok';
                   1642:             } else {
                   1643:                 return 
                   1644:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1645: 	    }
                   1646:         } else {
                   1647:             return 'error: Could not assign key, try again later.';
                   1648:         }
1.364     www      1649:     } elsif (!$existing{$ckey}) {
1.345     www      1650: # the key does not exist
                   1651: 	return 'error: The key does not exist';
                   1652:     } else {
                   1653: # the key is somebody else's
                   1654: 	return 'error: The key is already in use';
                   1655:     }
1.344     www      1656: }
                   1657: 
1.364     www      1658: # ------------------------------------------ put an additional comment on a key
                   1659: 
                   1660: sub comment_access_key {
                   1661: #
                   1662: # a valid key looks like uname:udom#comments
                   1663: # comments are being appended
                   1664: #
                   1665:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1666:     $cdom=
1.620     albertel 1667:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1668:     $cnum=
1.620     albertel 1669:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1670:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1671:     if ($existing{$ckey}) {
                   1672:         $existing{$ckey}.='; '.$logentry;
                   1673: # ready to assign
1.367     www      1674:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1675:                                                  $cdom,$cnum) eq 'ok') {
                   1676: 	    return 'ok';
                   1677:         } else {
                   1678: 	    return 'error: Count not store comment.';
                   1679:         }
                   1680:     } else {
                   1681: # the key does not exist
                   1682: 	return 'error: The key does not exist';
                   1683:     }
                   1684: }
                   1685: 
1.344     www      1686: # ------------------------------------------------------ Generate a set of keys
                   1687: 
                   1688: sub generate_access_keys {
1.364     www      1689:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1690:     $cdom=
1.620     albertel 1691:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1692:     $cnum=
1.620     albertel 1693:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1694:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1695:     unless (($cdom) && ($cnum)) { return 0; }
                   1696:     if ($number>10000) { return 0; }
                   1697:     sleep(2); # make sure don't get same seed twice
                   1698:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1699:     my $total=0;
                   1700:     for (my $i=1;$i<=$number;$i++) {
                   1701:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1702:                   sprintf("%lx",int(100000*rand)).'-'.
                   1703:                   sprintf("%lx",int(100000*rand));
                   1704:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1705:        $newkey=~s/0/h/g; # and also 0 and O
                   1706:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1707:        if ($existing{$newkey}) {
                   1708:            $i--;
                   1709:        } else {
1.364     www      1710: 	  if (&put('accesskeys',
                   1711:               { $newkey => '# generated '.localtime().
1.620     albertel 1712:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1713:                            '; '.$logentry },
                   1714: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1715:               $total++;
                   1716: 	  }
                   1717:        }
                   1718:     }
1.620     albertel 1719:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1720:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1721:     return $total;
                   1722: }
                   1723: 
                   1724: # ------------------------------------------------------- Validate an accesskey
                   1725: 
                   1726: sub validate_access_key {
                   1727:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1728:     $cdom=
1.620     albertel 1729:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1730:     $cnum=
1.620     albertel 1731:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1732:     $udom=$env{'user.domain'} unless (defined($udom));
                   1733:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1734:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1735:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1736: }
                   1737: 
                   1738: # ------------------------------------- Find the section of student in a course
1.652     albertel 1739: sub devalidate_getsection_cache {
                   1740:     my ($udom,$unam,$courseid)=@_;
                   1741:     my $hashid="$udom:$unam:$courseid";
                   1742:     &devalidate_cache_new('getsection',$hashid);
                   1743: }
1.298     matthew  1744: 
1.815     albertel 1745: sub courseid_to_courseurl {
                   1746:     my ($courseid) = @_;
                   1747:     #already url style courseid
                   1748:     return $courseid if ($courseid =~ m{^/});
                   1749: 
                   1750:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1751: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1752: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1753: 	return "/$cdom/$cnum";
                   1754:     }
                   1755: 
                   1756:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1757:     if (exists($courseinfo{'num'})) {
                   1758: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1759:     }
                   1760: 
                   1761:     return undef;
                   1762: }
                   1763: 
1.298     matthew  1764: sub getsection {
                   1765:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1766:     my $cachetime=1800;
1.551     albertel 1767: 
                   1768:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1769:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1770:     if (defined($cached)) { return $result; }
                   1771: 
1.298     matthew  1772:     my %Pending; 
                   1773:     my %Expired;
                   1774:     #
                   1775:     # Each role can either have not started yet (pending), be active, 
                   1776:     #    or have expired.
                   1777:     #
                   1778:     # If there is an active role, we are done.
                   1779:     #
                   1780:     # If there is more than one role which has not started yet, 
                   1781:     #     choose the one which will start sooner
                   1782:     # If there is one role which has not started yet, return it.
                   1783:     #
                   1784:     # If there is more than one expired role, choose the one which ended last.
                   1785:     # If there is a role which has expired, return it.
                   1786:     #
1.815     albertel 1787:     $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  1788:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1789:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1790:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1791:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1792:         my $section=$1;
                   1793:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1794:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1795:         my $now=time;
1.548     albertel 1796:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1797:             $Expired{$end}=$section;
                   1798:             next;
                   1799:         }
1.548     albertel 1800:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1801:             $Pending{$start}=$section;
                   1802:             next;
                   1803:         }
1.599     albertel 1804:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1805:     }
                   1806:     #
                   1807:     # Presumedly there will be few matching roles from the above
                   1808:     # loop and the sorting time will be negligible.
                   1809:     if (scalar(keys(%Pending))) {
                   1810:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1811:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1812:     } 
                   1813:     if (scalar(keys(%Expired))) {
                   1814:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1815:         my $time = pop(@sorted);
1.599     albertel 1816:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1817:     }
1.599     albertel 1818:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1819: }
1.70      www      1820: 
1.599     albertel 1821: sub save_cache {
                   1822:     &purge_remembered();
1.722     albertel 1823:     #&Apache::loncommon::validate_page();
1.620     albertel 1824:     undef(%env);
1.780     albertel 1825:     undef($env_loaded);
1.599     albertel 1826: }
1.452     albertel 1827: 
1.599     albertel 1828: my $to_remember=-1;
                   1829: my %remembered;
                   1830: my %accessed;
                   1831: my $kicks=0;
                   1832: my $hits=0;
1.849     albertel 1833: sub make_key {
                   1834:     my ($name,$id) = @_;
1.872     albertel 1835:     if (length($id) > 65 
                   1836: 	&& length(&escape($id)) > 200) {
                   1837: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1838:     }
1.849     albertel 1839:     return &escape($name.':'.$id);
                   1840: }
                   1841: 
1.599     albertel 1842: sub devalidate_cache_new {
                   1843:     my ($name,$id,$debug) = @_;
                   1844:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1845:     $id=&make_key($name,$id);
1.599     albertel 1846:     $memcache->delete($id);
                   1847:     delete($remembered{$id});
                   1848:     delete($accessed{$id});
                   1849: }
                   1850: 
                   1851: sub is_cached_new {
                   1852:     my ($name,$id,$debug) = @_;
1.849     albertel 1853:     $id=&make_key($name,$id);
1.599     albertel 1854:     if (exists($remembered{$id})) {
                   1855: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1856: 	$accessed{$id}=[&gettimeofday()];
                   1857: 	$hits++;
                   1858: 	return ($remembered{$id},1);
                   1859:     }
                   1860:     my $value = $memcache->get($id);
                   1861:     if (!(defined($value))) {
                   1862: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1863: 	return (undef,undef);
1.416     albertel 1864:     }
1.599     albertel 1865:     if ($value eq '__undef__') {
                   1866: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1867: 	$value=undef;
                   1868:     }
                   1869:     &make_room($id,$value,$debug);
                   1870:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1871:     return ($value,1);
                   1872: }
                   1873: 
                   1874: sub do_cache_new {
                   1875:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1876:     $id=&make_key($name,$id);
1.599     albertel 1877:     my $setvalue=$value;
                   1878:     if (!defined($setvalue)) {
                   1879: 	$setvalue='__undef__';
                   1880:     }
1.623     albertel 1881:     if (!defined($time) ) {
                   1882: 	$time=600;
                   1883:     }
1.599     albertel 1884:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1885:     my $result = $memcache->set($id,$setvalue,$time);
                   1886:     if (! $result) {
1.872     albertel 1887: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1888: 	$memcache->disconnect_all();
1.872     albertel 1889:     }
1.600     albertel 1890:     # need to make a copy of $value
1.919     albertel 1891:     &make_room($id,$value,$debug);
1.599     albertel 1892:     return $value;
                   1893: }
                   1894: 
                   1895: sub make_room {
                   1896:     my ($id,$value,$debug)=@_;
1.919     albertel 1897: 
                   1898:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1899:                                     : $value;
1.599     albertel 1900:     if ($to_remember<0) { return; }
                   1901:     $accessed{$id}=[&gettimeofday()];
                   1902:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1903:     my $to_kick;
                   1904:     my $max_time=0;
                   1905:     foreach my $other (keys(%accessed)) {
                   1906: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1907: 	    $to_kick=$other;
                   1908: 	    $max_time=&tv_interval($accessed{$other});
                   1909: 	}
                   1910:     }
                   1911:     delete($remembered{$to_kick});
                   1912:     delete($accessed{$to_kick});
                   1913:     $kicks++;
                   1914:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1915:     return;
                   1916: }
                   1917: 
1.599     albertel 1918: sub purge_remembered {
1.604     albertel 1919:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1920:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1921:     undef(%remembered);
                   1922:     undef(%accessed);
1.428     albertel 1923: }
1.70      www      1924: # ------------------------------------- Read an entry from a user's environment
                   1925: 
                   1926: sub userenvironment {
                   1927:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1928:     my $items;
                   1929:     foreach my $item (@what) {
                   1930:         $items.=&escape($item).'&';
                   1931:     }
                   1932:     $items=~s/\&$//;
1.70      www      1933:     my %returnhash=();
1.1009    raeburn  1934:     my $uhome = &homeserver($unam,$udom);
                   1935:     unless ($uhome eq 'no_host') {
                   1936:         my @answer=split(/\&/, 
                   1937:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1938:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1939:             return %returnhash;
                   1940:         }
1.1009    raeburn  1941:         my $i;
                   1942:         for ($i=0;$i<=$#what;$i++) {
                   1943: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1944:         }
1.70      www      1945:     }
                   1946:     return %returnhash;
1.1       albertel 1947: }
                   1948: 
1.617     albertel 1949: # ---------------------------------------------------------- Get a studentphoto
                   1950: sub studentphoto {
                   1951:     my ($udom,$unam,$ext) = @_;
                   1952:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1953:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1954:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1955:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1956:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1957:             } else {
                   1958:                 my ($result,$perm_reqd)=
1.707     albertel 1959: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1960:                 if ($result eq 'ok') {
                   1961:                     if (!($perm_reqd eq 'yes')) {
                   1962:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1963:                     }
                   1964:                 }
                   1965:             }
                   1966:         }
                   1967:     } else {
                   1968:         my ($result,$perm_reqd) = 
1.707     albertel 1969: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1970:         if ($result eq 'ok') {
                   1971:             if (!($perm_reqd eq 'yes')) {
                   1972:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1973:             }
                   1974:         }
                   1975:     }
                   1976:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1977: }
                   1978: 
                   1979: sub retrievestudentphoto {
                   1980:     my ($udom,$unam,$ext,$type) = @_;
                   1981:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1982:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1983:     if ($ret eq 'ok') {
                   1984:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1985:         if ($type eq 'thumbnail') {
                   1986:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1987:         }
                   1988:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1989:         return $tokenurl;
                   1990:     } else {
                   1991:         if ($type eq 'thumbnail') {
                   1992:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1993:         } else { 
                   1994:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1995:         }
1.617     albertel 1996:     }
                   1997: }
                   1998: 
1.263     www      1999: # -------------------------------------------------------------------- New chat
                   2000: 
                   2001: sub chatsend {
1.724     raeburn  2002:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2003:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2004:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2005:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2006:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2007: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2008: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2009: }
                   2010: 
                   2011: # ------------------------------------------ Find current version of a resource
                   2012: 
                   2013: sub getversion {
                   2014:     my $fname=&clutter(shift);
                   2015:     unless ($fname=~/^\/res\//) { return -1; }
                   2016:     return &currentversion(&filelocation('',$fname));
                   2017: }
                   2018: 
                   2019: sub currentversion {
                   2020:     my $fname=shift;
1.599     albertel 2021:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      2022:     if (defined($cached)) { return $result; }
1.292     www      2023:     my $author=$fname;
                   2024:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2025:     my ($udom,$uname)=split(/\//,$author);
                   2026:     my $home=homeserver($uname,$udom);
                   2027:     if ($home eq 'no_host') { 
                   2028:         return -1; 
                   2029:     }
                   2030:     my $answer=reply("currentversion:$fname",$home);
                   2031:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2032: 	return -1;
                   2033:     }
1.599     albertel 2034:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      2035: }
                   2036: 
1.1       albertel 2037: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2038: 
1.1       albertel 2039: sub subscribe {
                   2040:     my $fname=shift;
1.761     raeburn  2041:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2042:     $fname=~s/[\n\r]//g;
1.1       albertel 2043:     my $author=$fname;
                   2044:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2045:     my ($udom,$uname)=split(/\//,$author);
                   2046:     my $home=homeserver($uname,$udom);
1.335     albertel 2047:     if ($home eq 'no_host') {
                   2048:         return 'not_found';
1.1       albertel 2049:     }
                   2050:     my $answer=reply("sub:$fname",$home);
1.64      www      2051:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2052: 	$answer.=' by '.$home;
                   2053:     }
1.1       albertel 2054:     return $answer;
                   2055: }
                   2056:     
1.8       www      2057: # -------------------------------------------------------------- Replicate file
                   2058: 
                   2059: sub repcopy {
                   2060:     my $filename=shift;
1.23      www      2061:     $filename=~s/\/+/\//g;
1.607     raeburn  2062:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2063:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2064:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2065: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2066: 	return &repcopy_userfile($filename);
                   2067:     }
1.532     albertel 2068:     $filename=~s/[\n\r]//g;
1.8       www      2069:     my $transname="$filename.in.transfer";
1.828     www      2070: # FIXME: this should flock
1.607     raeburn  2071:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2072:     my $remoteurl=subscribe($filename);
1.64      www      2073:     if ($remoteurl =~ /^con_lost by/) {
                   2074: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2075:            return 'unavailable';
1.8       www      2076:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2077: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2078: 	   return 'not_found';
1.64      www      2079:     } elsif ($remoteurl =~ /^rejected by/) {
                   2080: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2081:            return 'forbidden';
1.20      www      2082:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2083:            return 'ok';
1.8       www      2084:     } else {
1.290     www      2085:         my $author=$filename;
                   2086:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2087:         my ($udom,$uname)=split(/\//,$author);
                   2088:         my $home=homeserver($uname,$udom);
                   2089:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2090:            my @parts=split(/\//,$filename);
                   2091:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2092:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2093:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2094: 	       return 'bad_request';
1.8       www      2095:            }
                   2096:            my $count;
                   2097:            for ($count=5;$count<$#parts;$count++) {
                   2098:                $path.="/$parts[$count]";
                   2099:                if ((-e $path)!=1) {
                   2100: 		   mkdir($path,0777);
                   2101:                }
                   2102:            }
                   2103:            my $ua=new LWP::UserAgent;
                   2104:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2105:            my $response=$ua->request($request,$transname);
                   2106:            if ($response->is_error()) {
                   2107: 	       unlink($transname);
                   2108:                my $message=$response->status_line;
1.672     albertel 2109:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2110:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2111:                return 'unavailable';
1.8       www      2112:            } else {
1.16      www      2113: 	       if ($remoteurl!~/\.meta$/) {
                   2114:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2115:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2116:                   if ($mresponse->is_error()) {
                   2117: 		      unlink($filename.'.meta');
                   2118:                       &logthis(
1.672     albertel 2119:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2120:                   }
                   2121: 	       }
1.8       www      2122:                rename($transname,$filename);
1.607     raeburn  2123:                return 'ok';
1.8       www      2124:            }
1.290     www      2125:        }
1.8       www      2126:     }
1.330     www      2127: }
                   2128: 
                   2129: # ------------------------------------------------ Get server side include body
                   2130: sub ssi_body {
1.381     albertel 2131:     my ($filelink,%form)=@_;
1.606     matthew  2132:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2133:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2134:     }
1.953     www      2135:     my $output='';
                   2136:     my $response;
1.980     raeburn  2137:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2138:        ($output,$response)=&externalssi($filelink);
1.953     www      2139:     } else {
1.1004    droeschl 2140:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2141:        $filelink .= 'inhibitmenu=yes';
1.953     www      2142:        ($output,$response)=&ssi($filelink,%form);
                   2143:     }
1.778     albertel 2144:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2145:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2146:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2147:     if (wantarray) {
                   2148:         return ($output, $response);
                   2149:     } else {
                   2150:         return $output;
                   2151:     }
1.8       www      2152: }
                   2153: 
1.15      www      2154: # --------------------------------------------------------- Server Side Include
                   2155: 
1.782     albertel 2156: sub absolute_url {
                   2157:     my ($host_name) = @_;
                   2158:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2159:     if ($host_name eq '') {
                   2160: 	$host_name = $ENV{'SERVER_NAME'};
                   2161:     }
                   2162:     return $protocol.$host_name;
                   2163: }
                   2164: 
1.942     foxr     2165: #
                   2166: #   Server side include.
                   2167: # Parameters:
                   2168: #  fn     Possibly encrypted resource name/id.
                   2169: #  form   Hash that describes how the rendering should be done
                   2170: #         and other things.
1.944     foxr     2171: # Returns:
1.950     raeburn  2172: #   Scalar context: The content of the response.
                   2173: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2174: #     
1.15      www      2175: sub ssi {
                   2176: 
1.944     foxr     2177:     my ($fn,%form)=@_;
1.15      www      2178:     my $ua=new LWP::UserAgent;
1.23      www      2179:     my $request;
1.711     albertel 2180: 
                   2181:     $form{'no_update_last_known'}=1;
1.895     albertel 2182:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2183:     if (%form) {
1.782     albertel 2184:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2185:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2186:     } else {
1.782     albertel 2187:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2188:     }
                   2189: 
1.15      www      2190:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2191:     my $response=$ua->request($request);
                   2192: 
1.944     foxr     2193:     if (wantarray) {
                   2194: 	return ($response->content, $response);
                   2195:     } else {
                   2196: 	return $response->content;
1.942     foxr     2197:     }
1.324     www      2198: }
                   2199: 
                   2200: sub externalssi {
                   2201:     my ($url)=@_;
                   2202:     my $ua=new LWP::UserAgent;
                   2203:     my $request=new HTTP::Request('GET',$url);
                   2204:     my $response=$ua->request($request);
1.954     raeburn  2205:     if (wantarray) {
                   2206:         return ($response->content, $response);
                   2207:     } else {
                   2208:         return $response->content;
                   2209:     }
1.15      www      2210: }
1.254     www      2211: 
1.492     albertel 2212: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2213: 
                   2214: sub allowuploaded {
                   2215:     my ($srcurl,$url)=@_;
                   2216:     $url=&clutter(&declutter($url));
                   2217:     my $dir=$url;
                   2218:     $dir=~s/\/[^\/]+$//;
                   2219:     my %httpref=();
                   2220:     my $httpurl=&hreflocation('',$url);
                   2221:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2222:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2223: }
1.477     raeburn  2224: 
1.478     albertel 2225: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2226: # input: action, courseID, current domain, intended
1.637     raeburn  2227: #        path to file, source of file, instruction to parse file for objects,
                   2228: #        ref to hash for embedded objects,
                   2229: #        ref to hash for codebase of java objects.
1.1056.4.16  raeburn  2230: #        reference to scalar to accommodate mime type determined
                   2231: #          from File::MMagic if $parser = parse.
1.637     raeburn  2232: #
1.485     raeburn  2233: # output: url to file (if action was uploaddoc), 
                   2234: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2235: #
1.478     albertel 2236: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2237: # course.
1.477     raeburn  2238: #
1.478     albertel 2239: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2240: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2241: #          course's home server.
1.477     raeburn  2242: #
1.478     albertel 2243: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2244: #          be copied from $source (current location) to 
                   2245: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2246: #         and will then be copied to
                   2247: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2248: #         course's home server.
1.485     raeburn  2249: #
1.481     raeburn  2250: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2251: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2252: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2253: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2254: #         in course's home server.
1.637     raeburn  2255: #
1.477     raeburn  2256: 
                   2257: sub process_coursefile {
1.1056.4.16  raeburn  2258:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2259:         $mimetype)=@_;
1.477     raeburn  2260:     my $fetchresult;
1.638     albertel 2261:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2262:     if ($action eq 'propagate') {
1.638     albertel 2263:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2264: 			     $home);
1.481     raeburn  2265:     } else {
1.477     raeburn  2266:         my $fpath = '';
                   2267:         my $fname = $file;
1.478     albertel 2268:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2269:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2270:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2271:         if ($action eq 'copy') {
                   2272:             if ($source eq '') {
                   2273:                 $fetchresult = 'no source file';
                   2274:                 return $fetchresult;
                   2275:             } else {
                   2276:                 my $destination = $filepath.'/'.$fname;
                   2277:                 rename($source,$destination);
                   2278:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2279:                                  $home);
1.481     raeburn  2280:             }
                   2281:         } elsif ($action eq 'uploaddoc') {
                   2282:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2283:             print $fh $env{'form.'.$source};
1.481     raeburn  2284:             close($fh);
1.637     raeburn  2285:             if ($parser eq 'parse') {
1.1024    raeburn  2286:                 my $mm = new File::MMagic;
1.1056.4.16  raeburn  2287:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2288:                 if ($type eq 'text/html') {
1.1024    raeburn  2289:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2290:                     unless ($parse_result eq 'ok') {
                   2291:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2292:                     }
1.637     raeburn  2293:                 }
1.1056.4.16  raeburn  2294:                 if (ref($mimetype)) {
                   2295:                     $$mimetype = $type;
                   2296:                 }
1.637     raeburn  2297:             }
1.477     raeburn  2298:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2299:                                  $home);
1.481     raeburn  2300:             if ($fetchresult eq 'ok') {
                   2301:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2302:             } else {
                   2303:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2304:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2305:                 return '/adm/notfound.html';
                   2306:             }
1.477     raeburn  2307:         }
                   2308:     }
1.485     raeburn  2309:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2310:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2311:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2312:     }
                   2313:     return $fetchresult;
                   2314: }
                   2315: 
1.637     raeburn  2316: sub build_filepath {
                   2317:     my ($fpath) = @_;
                   2318:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2319:     unless ($fpath eq '') {
                   2320:         my @parts=split('/',$fpath);
                   2321:         foreach my $part (@parts) {
                   2322:             $filepath.= '/'.$part;
                   2323:             if ((-e $filepath)!=1) {
                   2324:                 mkdir($filepath,0777);
                   2325:             }
                   2326:         }
                   2327:     }
                   2328:     return $filepath;
                   2329: }
                   2330: 
                   2331: sub store_edited_file {
1.638     albertel 2332:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2333:     my $file = $primary_url;
                   2334:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2335:     my $fpath = '';
                   2336:     my $fname = $file;
                   2337:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2338:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2339:     my $filepath = &build_filepath($fpath);
                   2340:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2341:     print $fh $content;
                   2342:     close($fh);
1.638     albertel 2343:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2344:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2345: 			  $home);
1.637     raeburn  2346:     if ($$fetchresult eq 'ok') {
                   2347:         return '/uploaded/'.$fpath.'/'.$fname;
                   2348:     } else {
1.638     albertel 2349:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2350: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2351:         return '/adm/notfound.html';
                   2352:     }
                   2353: }
                   2354: 
1.531     albertel 2355: sub clean_filename {
1.831     albertel 2356:     my ($fname,$args)=@_;
1.315     www      2357: # Replace Windows backslashes by forward slashes
1.257     www      2358:     $fname=~s/\\/\//g;
1.831     albertel 2359:     if (!$args->{'keep_path'}) {
                   2360:         # Get rid of everything but the actual filename
                   2361: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2362:     }
1.315     www      2363: # Replace spaces by underscores
                   2364:     $fname=~s/\s+/\_/g;
                   2365: # Replace all other weird characters by nothing
1.831     albertel 2366:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2367: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2368: # numbers
                   2369:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2370:     return $fname;
                   2371: }
1.1051    raeburn  2372: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2373: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2374: # image with the same aspect ratio as the original, but with dimensions which do 
                   2375: # not exceed $resizewidth and $resizeheight.
                   2376:  
1.984     neumanie 2377: sub resizeImage {
1.1051    raeburn  2378:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2379:     my $ima = Image::Magick->new;
                   2380:     my $resized;
                   2381:     if (-e $img_path) {
                   2382:         $ima->Read($img_path);
                   2383:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2384:             my $width = $ima->Get('width');
                   2385:             my $height = $ima->Get('height');
                   2386:             if ($width > $resizewidth) {
                   2387: 	        my $factor = $width/$resizewidth;
                   2388:                 my $newheight = $height/$factor;
                   2389:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2390:                 $resized = 1;
                   2391:             }
                   2392:         }
                   2393:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2394:             my $width = $ima->Get('width');
                   2395:             my $height = $ima->Get('height');
                   2396:             if ($height > $resizeheight) {
                   2397:                 my $factor = $height/$resizeheight;
                   2398:                 my $newwidth = $width/$factor;
                   2399:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2400:                 $resized = 1;
                   2401:             }
                   2402:         }
                   2403:         if ($resized) {
                   2404:             $ima->Write($img_path);
                   2405:         }
                   2406:     }
                   2407:     return;
1.977     amueller 2408: }
                   2409: 
1.608     albertel 2410: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2411: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13  raeburn  2412: #                    the desired filename is in $env{"form.$formname.filename"}
                   2413: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2414: #                                    canceloverwrite, or ''.
                   2415: #                   if 'coursedoc': upload to the current course
                   2416: #                   if 'existingfile': write file to tmp/overwrites directory
                   2417: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2418: #                   $context is passed as argument to &finishuserfileupload 
1.686     albertel 2419: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2420: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2421: #        $allfiles - reference to hash for embedded objects
                   2422: #        $codebase - reference to hash for codebase of java objects
                   2423: #        $desuname - username for permanent storage of uploaded file
                   2424: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2425: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2426: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2427: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2428: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1056.4.16  raeburn  2429: #        $mimetype - reference to scalar to accommodate mime type determined
                   2430: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2431: # 
1.686     albertel 2432: # output: url of file in userspace, or error: <message> 
                   2433: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2434: 
1.531     albertel 2435: sub userfileupload {
1.1056.4.13  raeburn  2436:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1056.4.16  raeburn  2437:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2438:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2439:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2440:     $fname=&clean_filename($fname);
1.1056.4.13  raeburn  2441:     # See if there is anything left
1.257     www      2442:     unless ($fname) { return 'error: no uploaded file'; }
1.1056.4.13  raeburn  2443:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2444:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2445:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2446:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2447:         my $now = time;
1.1056.4.13  raeburn  2448:         my $filepath;
                   2449:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
                   2450:              $filepath = 'tmp/helprequests/'.$now;
                   2451:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2452:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2453:                          '_'.$env{'user.domain'}.'/pending';
                   2454:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2455:             my ($docuname,$docudom);
                   2456:             if ($destudom) {
                   2457:                 $docudom = $destudom;
                   2458:             } else {
                   2459:                 $docudom = $env{'user.domain'};
                   2460:             }
                   2461:             if ($destuname) {
                   2462:                 $docuname = $destuname;
                   2463:             } else {
                   2464:                 $docuname = $env{'user.name'};
                   2465:             }
                   2466:             if (exists($env{'form.group'})) {
                   2467:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2468:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2469:             }
                   2470:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2471:             if ($context eq 'canceloverwrite') {
                   2472:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2473:                 if (-e  $tempfile) {
                   2474:                     my @info = stat($tempfile);
                   2475:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2476:                         unlink($tempfile);
                   2477:                     }
                   2478:                 }
                   2479:                 return;
1.523     raeburn  2480:             }
                   2481:         }
1.1056.4.13  raeburn  2482:         # Create the directory if not present
1.741     raeburn  2483:         my @parts=split(/\//,$filepath);
                   2484:         my $fullpath = $perlvar{'lonDaemons'};
                   2485:         for (my $i=0;$i<@parts;$i++) {
                   2486:             $fullpath .= '/'.$parts[$i];
                   2487:             if ((-e $fullpath)!=1) {
                   2488:                 mkdir($fullpath,0777);
                   2489:             }
                   2490:         }
                   2491:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2492:         print $fh $env{'form.'.$formname};
                   2493:         close($fh);
1.1056.4.13  raeburn  2494:         if ($context eq 'existingfile') {
                   2495:             my @info = stat($fullpath.'/'.$fname);
                   2496:             return ($fullpath.'/'.$fname,$info[9]);
                   2497:         } else {
                   2498:             return $fullpath.'/'.$fname;
                   2499:         }
1.523     raeburn  2500:     }
1.995     raeburn  2501:     if ($subdir eq 'scantron') {
                   2502:         $fname = 'scantron_orig_'.$fname;
1.1056.4.14  raeburn  2503:     } else {
1.995     raeburn  2504:         $fname="$subdir/$fname";
                   2505:     }
1.1056.4.13  raeburn  2506:     if ($context eq 'coursedoc') {
1.638     albertel 2507: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2508: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2509:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2510:             return &finishuserfileupload($docuname,$docudom,
                   2511: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2512: 					 $codebase,$thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2513:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2514:         } else {
1.620     albertel 2515:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2516:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2517: 				       $fname,$formname,$parser,
1.1056.4.16  raeburn  2518: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2519:         }
1.719     banghart 2520:     } elsif (defined($destuname)) {
                   2521:         my $docuname=$destuname;
                   2522:         my $docudom=$destudom;
1.860     raeburn  2523: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2524: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2525:                                      $thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2526:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2527:     } else {
1.638     albertel 2528:         my $docuname=$env{'user.name'};
                   2529:         my $docudom=$env{'user.domain'};
1.714     raeburn  2530:         if (exists($env{'form.group'})) {
                   2531:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2532:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2533:         }
1.860     raeburn  2534: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2535: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2536:                                      $thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2537:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2538:     }
1.271     www      2539: }
                   2540: 
                   2541: sub finishuserfileupload {
1.860     raeburn  2542:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.16  raeburn  2543:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2544:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2545:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2546:   
1.860     raeburn  2547:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2548:     $file=$fname;
                   2549:     if ($fname=~m|/|) {
                   2550:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2551: 	$path.=$fnamepath.'/';
                   2552:     }
1.259     www      2553:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2554:     my $count;
                   2555:     for ($count=4;$count<=$#parts;$count++) {
                   2556:         $filepath.="/$parts[$count]";
                   2557:         if ((-e $filepath)!=1) {
                   2558: 	    mkdir($filepath,0777);
                   2559:         }
                   2560:     }
1.984     neumanie 2561: 
1.258     www      2562: # Save the file
                   2563:     {
1.701     albertel 2564: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2565: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2566: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2567: 	    return '/adm/notfound.html';
                   2568: 	}
1.1056.4.13  raeburn  2569:         if ($context eq 'overwrite') {
                   2570:             my $source =  $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
                   2571:             my $target = $filepath.'/'.$file;
                   2572:             if (-e $source) {
                   2573:                 my @info = stat($source);
                   2574:                 if ($info[9] eq $env{'form.timestamp'}) {
                   2575:                     unless (&File::Copy::move($source,$target)) {
                   2576:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2577:                         return "Moving from $source failed";
                   2578:                     }
                   2579:                 } else {
                   2580:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2581:                 }
                   2582:             } else {
                   2583:                 return "Temporary file: $source missing";
                   2584:             }
                   2585: 	} elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2586: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2587: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2588: 	    return '/adm/notfound.html';
                   2589: 	}
1.570     albertel 2590: 	close(FH);
1.1051    raeburn  2591:         if ($resizewidth && $resizeheight) {
                   2592:             my $mm = new File::MMagic;
                   2593:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2594:             if ($mime_type =~ m{^image/}) {
                   2595: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2596:             }  
1.977     amueller 2597: 	}
1.258     www      2598:     }
1.637     raeburn  2599:     if ($parser eq 'parse') {
1.1024    raeburn  2600:         my $mm = new File::MMagic;
1.1056.4.16  raeburn  2601:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2602:         if ($type eq 'text/html') {
1.1024    raeburn  2603:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2604:                                                        $allfiles,$codebase);
                   2605:             unless ($parse_result eq 'ok') {
                   2606:                 &logthis('Failed to parse '.$filepath.$file.
                   2607: 	   	         ' for embedded media: '.$parse_result); 
                   2608:             }
1.637     raeburn  2609:         }
1.1056.4.16  raeburn  2610:         if (ref($mimetype)) {
                   2611:             $$mimetype = $type;
                   2612:         }
1.637     raeburn  2613:     }
1.860     raeburn  2614:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2615:         my $input = $filepath.'/'.$file;
                   2616:         my $output = $filepath.'/'.'tn-'.$file;
                   2617:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2618:         system("convert -sample $thumbsize $input $output");
                   2619:         if (-e $filepath.'/'.'tn-'.$file) {
                   2620:             $fetchthumb  = 1; 
                   2621:         }
                   2622:     }
1.858     raeburn  2623:  
1.259     www      2624: # Notify homeserver to grep it
                   2625: #
1.984     neumanie 2626:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2627:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2628:     if ($fetchresult eq 'ok') {
1.860     raeburn  2629:         if ($fetchthumb) {
                   2630:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2631:             if ($thumbresult ne 'ok') {
                   2632:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2633:                          $docuhome.': '.$thumbresult);
                   2634:             }
                   2635:         }
1.259     www      2636: #
1.258     www      2637: # Return the URL to it
1.494     albertel 2638:         return '/uploaded/'.$path.$file;
1.263     www      2639:     } else {
1.494     albertel 2640:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2641: 		 ': '.$fetchresult);
1.263     www      2642:         return '/adm/notfound.html';
1.858     raeburn  2643:     }
1.493     albertel 2644: }
                   2645: 
1.637     raeburn  2646: sub extract_embedded_items {
1.961     raeburn  2647:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2648:     my @state = ();
                   2649:     my %javafiles = (
                   2650:                       codebase => '',
                   2651:                       code => '',
                   2652:                       archive => ''
                   2653:                     );
                   2654:     my %mediafiles = (
                   2655:                       src => '',
                   2656:                       movie => '',
                   2657:                      );
1.648     raeburn  2658:     my $p;
                   2659:     if ($content) {
                   2660:         $p = HTML::LCParser->new($content);
                   2661:     } else {
1.961     raeburn  2662:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2663:     }
1.641     albertel 2664:     while (my $t=$p->get_token()) {
1.640     albertel 2665: 	if ($t->[0] eq 'S') {
                   2666: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2667: 	    push(@state, $tagname);
1.648     raeburn  2668:             if (lc($tagname) eq 'allow') {
                   2669:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2670:             }
1.640     albertel 2671: 	    if (lc($tagname) eq 'img') {
                   2672: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2673: 	    }
1.886     albertel 2674: 	    if (lc($tagname) eq 'a') {
                   2675: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2676: 	    }
1.645     raeburn  2677:             if (lc($tagname) eq 'script') {
                   2678:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2679:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2680:                 } else {
                   2681:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2682:                 }
                   2683:             }
                   2684:             if (lc($tagname) eq 'link') {
                   2685:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2686:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2687:                 }
                   2688:             }
1.640     albertel 2689: 	    if (lc($tagname) eq 'object' ||
                   2690: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2691: 		foreach my $item (keys(%javafiles)) {
                   2692: 		    $javafiles{$item} = '';
                   2693: 		}
                   2694: 	    }
                   2695: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2696: 		my $name = lc($attr->{'name'});
                   2697: 		foreach my $item (keys(%javafiles)) {
                   2698: 		    if ($name eq $item) {
                   2699: 			$javafiles{$item} = $attr->{'value'};
                   2700: 			last;
                   2701: 		    }
                   2702: 		}
                   2703: 		foreach my $item (keys(%mediafiles)) {
                   2704: 		    if ($name eq $item) {
                   2705: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2706: 			last;
                   2707: 		    }
                   2708: 		}
                   2709: 	    }
                   2710: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2711: 		foreach my $item (keys(%javafiles)) {
                   2712: 		    if ($attr->{$item}) {
                   2713: 			$javafiles{$item} = $attr->{$item};
                   2714: 			last;
                   2715: 		    }
                   2716: 		}
                   2717: 		foreach my $item (keys(%mediafiles)) {
                   2718: 		    if ($attr->{$item}) {
                   2719: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2720: 			last;
                   2721: 		    }
                   2722: 		}
                   2723: 	    }
                   2724: 	} elsif ($t->[0] eq 'E') {
                   2725: 	    my ($tagname) = ($t->[1]);
                   2726: 	    if ($javafiles{'codebase'} ne '') {
                   2727: 		$javafiles{'codebase'} .= '/';
                   2728: 	    }  
                   2729: 	    if (lc($tagname) eq 'applet' ||
                   2730: 		lc($tagname) eq 'object' ||
                   2731: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2732: 		) {
                   2733: 		foreach my $item (keys(%javafiles)) {
                   2734: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2735: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2736: 			&add_filetype($allfiles,$file,$item);
                   2737: 		    }
                   2738: 		}
                   2739: 	    } 
                   2740: 	    pop @state;
                   2741: 	}
                   2742:     }
1.637     raeburn  2743:     return 'ok';
                   2744: }
                   2745: 
1.639     albertel 2746: sub add_filetype {
                   2747:     my ($allfiles,$file,$type)=@_;
                   2748:     if (exists($allfiles->{$file})) {
                   2749: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2750: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2751: 	}
                   2752:     } else {
                   2753: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2754:     }
                   2755: }
                   2756: 
1.493     albertel 2757: sub removeuploadedurl {
1.984     neumanie 2758:     my ($url)=@_;	
                   2759:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2760:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2761: }
                   2762: 
                   2763: sub removeuserfile {
                   2764:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2765:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2766:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2767:     if ($result eq 'ok') {	
1.798     raeburn  2768:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2769:             my $metafile = $fname.'.meta';
                   2770:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2771: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2772:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2773:             my $sqlresult = 
1.823     albertel 2774:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2775:                                         'portfolio_metadata',$group,
                   2776:                                         'delete');
1.798     raeburn  2777:         }
                   2778:     }
                   2779:     return $result;
1.257     www      2780: }
1.15      www      2781: 
1.530     albertel 2782: sub mkdiruserfile {
                   2783:     my ($docuname,$docudom,$dir)=@_;
                   2784:     my $home=&homeserver($docuname,$docudom);
                   2785:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2786: }
                   2787: 
1.531     albertel 2788: sub renameuserfile {
                   2789:     my ($docuname,$docudom,$old,$new)=@_;
                   2790:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2791:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2792:                         &escape("$old").':'.&escape("$new"),$home);
                   2793:     if ($result eq 'ok') {
                   2794:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2795:             my $oldmeta = $old.'.meta';
                   2796:             my $newmeta = $new.'.meta';
                   2797:             my $metaresult = 
                   2798:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2799: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2800:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2801:             my $sqlresult = 
1.823     albertel 2802:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2803:                                         'portfolio_metadata',$group,
                   2804:                                         'delete');
1.798     raeburn  2805:         }
                   2806:     }
                   2807:     return $result;
1.531     albertel 2808: }
                   2809: 
1.14      www      2810: # ------------------------------------------------------------------------- Log
                   2811: 
                   2812: sub log {
                   2813:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2814:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2815: }
                   2816: 
                   2817: # ------------------------------------------------------------------ Course Log
1.352     www      2818: #
                   2819: # This routine flushes several buffers of non-mission-critical nature
                   2820: #
1.157     www      2821: 
                   2822: sub flushcourselogs {
1.352     www      2823:     &logthis('Flushing log buffers');
                   2824: #
                   2825: # course logs
                   2826: # This is a log of all transactions in a course, which can be used
                   2827: # for data mining purposes
                   2828: #
                   2829: # It also collects the courseid database, which lists last transaction
                   2830: # times and course titles for all courseids
                   2831: #
                   2832:     my %courseidbuffer=();
1.921     raeburn  2833:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2834:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2835: 		          &escape($courselogs{$crsid}),
                   2836: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2837: 	    delete $courselogs{$crsid};
                   2838:         } else {
                   2839:             &logthis('Failed to flush log buffer for '.$crsid);
                   2840:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2841:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2842:                         " exceeded maximum size, deleting.</font>");
                   2843:                delete $courselogs{$crsid};
                   2844:             }
1.352     www      2845:         }
1.920     raeburn  2846:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2847:             'description' => $coursedescrbuf{$crsid},
                   2848:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2849:             'type'        => $coursetypebuf{$crsid},
                   2850:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2851:         };
1.191     harris41 2852:     }
1.352     www      2853: #
                   2854: # Write course id database (reverse lookup) to homeserver of courses 
                   2855: # Is used in pickcourse
                   2856: #
1.840     albertel 2857:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2858:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2859:                                     $courseidbuffer{$crs_home},
                   2860:                                     $crs_home,'timeonly');
1.352     www      2861:     }
                   2862: #
                   2863: # File accesses
                   2864: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2865: #
1.449     matthew  2866:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2867:         if ($entry =~ /___count$/) {
                   2868:             my ($dom,$name);
1.807     albertel 2869:             ($dom,$name,undef)=
1.811     albertel 2870: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2871:             if (! defined($dom) || $dom eq '' || 
                   2872:                 ! defined($name) || $name eq '') {
1.620     albertel 2873:                 my $cid = $env{'request.course.id'};
                   2874:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2875:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2876:             }
1.450     matthew  2877:             my $value = $accesshash{$entry};
                   2878:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2879:             my %temphash=($url => $value);
1.449     matthew  2880:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2881:             if ($result eq 'ok') {
                   2882:                 delete $accesshash{$entry};
                   2883:             } elsif ($result eq 'unknown_cmd') {
                   2884:                 # Target server has old code running on it.
1.450     matthew  2885:                 my %temphash=($entry => $value);
1.449     matthew  2886:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2887:                     delete $accesshash{$entry};
                   2888:                 }
                   2889:             }
                   2890:         } else {
1.811     albertel 2891:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2892:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2893:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2894:                 delete $accesshash{$entry};
                   2895:             }
1.185     www      2896:         }
1.191     harris41 2897:     }
1.352     www      2898: #
                   2899: # Roles
                   2900: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2901: #
1.800     albertel 2902:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2903:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2904: 	    split(/\:/,$entry);
                   2905:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2906:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2907:                 $rudom,$runame) eq 'ok') {
                   2908: 	    delete $userrolehash{$entry};
                   2909:         }
                   2910:     }
1.662     raeburn  2911: #
                   2912: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2913: #
                   2914:     my %domrolebuffer = ();
1.1000    raeburn  2915:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2916:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2917:         if ($domrolebuffer{$rudom}) {
                   2918:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2919:                       '='.&escape($domainrolehash{$entry});
                   2920:         } else {
                   2921:             $domrolebuffer{$rudom}.=&escape($entry).
                   2922:                       '='.&escape($domainrolehash{$entry});
                   2923:         }
                   2924:         delete $domainrolehash{$entry};
                   2925:     }
                   2926:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2927: 	my %servers = &get_servers($dom,'library');
                   2928: 	foreach my $tryserver (keys(%servers)) {
                   2929: 	    unless (&reply('domroleput:'.$dom.':'.
                   2930: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2931: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2932: 	    }
1.662     raeburn  2933:         }
                   2934:     }
1.186     www      2935:     $dumpcount++;
1.157     www      2936: }
                   2937: 
                   2938: sub courselog {
                   2939:     my $what=shift;
1.158     www      2940:     $what=time.':'.$what;
1.620     albertel 2941:     unless ($env{'request.course.id'}) { return ''; }
                   2942:     $coursedombuf{$env{'request.course.id'}}=
                   2943:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2944:     $coursenumbuf{$env{'request.course.id'}}=
                   2945:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2946:     $coursehombuf{$env{'request.course.id'}}=
                   2947:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2948:     $coursedescrbuf{$env{'request.course.id'}}=
                   2949:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2950:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2951:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2952:     $courseownerbuf{$env{'request.course.id'}}=
                   2953:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2954:     $coursetypebuf{$env{'request.course.id'}}=
                   2955:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2956:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2957: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2958:     } else {
1.620     albertel 2959: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2960:     }
1.620     albertel 2961:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2962: 	&flushcourselogs();
                   2963:     }
1.158     www      2964: }
                   2965: 
                   2966: sub courseacclog {
                   2967:     my $fnsymb=shift;
1.620     albertel 2968:     unless ($env{'request.course.id'}) { return ''; }
                   2969:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2970:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2971:         $what.=':POST';
1.583     matthew  2972:         # FIXME: Probably ought to escape things....
1.800     albertel 2973: 	foreach my $key (keys(%env)) {
                   2974:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2975:                 my $formitem = $1;
                   2976:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2977:                     $what.=':'.$formitem.'='.$env{$key};
                   2978:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2979:                     $what.=':'.$formitem.'='.$env{$key};
                   2980:                 }
1.158     www      2981:             }
1.191     harris41 2982:         }
1.583     matthew  2983:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2984:         # FIXME: We should not be depending on a form parameter that someone
                   2985:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2986:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2987:             $what.= ':POST';
                   2988:             # FIXME: Probably ought to escape things....
                   2989:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2990:                                  'crsdiscuss') {
1.620     albertel 2991:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2992:             }
                   2993:         }
1.158     www      2994:     }
                   2995:     &courselog($what);
1.149     www      2996: }
                   2997: 
1.185     www      2998: sub countacc {
                   2999:     my $url=&declutter(shift);
1.458     matthew  3000:     return if (! defined($url) || $url eq '');
1.620     albertel 3001:     unless ($env{'request.course.id'}) { return ''; }
                   3002:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3003:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3004:     $accesshash{$key}++;
1.185     www      3005: }
1.349     www      3006: 
1.361     www      3007: sub linklog {
                   3008:     my ($from,$to)=@_;
                   3009:     $from=&declutter($from);
                   3010:     $to=&declutter($to);
                   3011:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3012:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3013: }
                   3014:   
1.349     www      3015: sub userrolelog {
                   3016:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3017:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3018:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3019:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3020:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3021:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3022:        $userrolehash
                   3023:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3024:                     =$tend.':'.$tstart;
1.662     raeburn  3025:     }
1.898     albertel 3026:     if (($env{'request.role'} =~ /dc\./) &&
                   3027: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3028: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3029: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3030:          ($trole=~/^co/))) {
1.898     albertel 3031:        $userrolehash
                   3032:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3033:                     =$tend.':'.$tstart;
                   3034:     }
1.662     raeburn  3035:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3036:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3037:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3038:         ($trole=~/^sc/)) {
                   3039:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3040:        $domainrolehash
                   3041:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3042:                     = $tend.':'.$tstart;
                   3043:     }
1.351     www      3044: }
                   3045: 
1.957     raeburn  3046: sub courserolelog {
                   3047:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3048:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3049:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3050:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3051:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3052:         ($trole eq 'co')) {
1.957     raeburn  3053:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3054:             my $cdom = $1;
                   3055:             my $cnum = $2;
                   3056:             my $sec = $3;
                   3057:             my $namespace = 'rolelog';
                   3058:             my %storehash = (
                   3059:                                role    => $trole,
                   3060:                                start   => $tstart,
                   3061:                                end     => $tend,
                   3062:                                selfenroll => $selfenroll,
                   3063:                                context    => $context,
                   3064:                             );
                   3065:             if ($trole eq 'gr') {
                   3066:                 $namespace = 'groupslog';
                   3067:                 $storehash{'group'} = $sec;
                   3068:             } else {
                   3069:                 $storehash{'section'} = $sec;
                   3070:             }
                   3071:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3072:             if (($trole ne 'st') || ($sec ne '')) {
                   3073:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3074:             }
1.957     raeburn  3075:         }
                   3076:     }
                   3077:     return;
                   3078: }
                   3079: 
1.351     www      3080: sub get_course_adv_roles {
1.948     raeburn  3081:     my ($cid,$codes) = @_;
1.620     albertel 3082:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3083:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3084:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3085:     my %nothide=();
1.800     albertel 3086:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3087:         if ($user !~ /:/) {
                   3088: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3089:         } else {
                   3090:             $nothide{$user}=1;
                   3091:         }
1.470     www      3092:     }
1.351     www      3093:     my %returnhash=();
                   3094:     my %dumphash=
                   3095:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3096:     my $now=time;
1.997     raeburn  3097:     my %privileged;
1.1000    raeburn  3098:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3099: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3100:         if (($tstart) && ($tstart<0)) { next; }
                   3101:         if (($tend) && ($tend<$now)) { next; }
                   3102:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3103:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3104: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3105:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3106:             my %dompersonnel =
1.998     raeburn  3107:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3108:             $privileged{$domain} = {};
                   3109:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3110:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3111:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3112:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3113:                         $privileged{$udom}{$uname} = 1;
                   3114:                     }
                   3115:                 }
                   3116:             }
                   3117:         }
                   3118:         if ((exists($privileged{$domain}{$username})) && 
                   3119:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3120: 	if ($role eq 'cr') { next; }
1.948     raeburn  3121:         if ($codes) {
                   3122:             if ($section) { $role .= ':'.$section; }
                   3123:             if ($returnhash{$role}) {
                   3124:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3125:             } else {
                   3126:                 $returnhash{$role}=$username.':'.$domain;
                   3127:             }
1.351     www      3128:         } else {
1.988     raeburn  3129:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3130:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3131:             if ($returnhash{$key}) {
                   3132: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3133:             } else {
                   3134:                 $returnhash{$key}=$username.':'.$domain;
                   3135:             }
1.351     www      3136:         }
1.948     raeburn  3137:     }
1.400     www      3138:     return %returnhash;
                   3139: }
                   3140: 
                   3141: sub get_my_roles {
1.937     raeburn  3142:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3143:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3144:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3145:     my (%dumphash,%nothide);
1.858     raeburn  3146:     if ($context eq 'userroles') { 
1.1056.4.10  raeburn  3147:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3148:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3149:     } else {
                   3150:         %dumphash=
1.400     www      3151:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3152:         if ($hidepriv) {
                   3153:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3154:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3155:                 if ($user !~ /:/) {
                   3156:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3157:                 } else {
                   3158:                     $nothide{$user} = 1;
                   3159:                 }
                   3160:             }
                   3161:         }
1.858     raeburn  3162:     }
1.400     www      3163:     my %returnhash=();
                   3164:     my $now=time;
1.999     raeburn  3165:     my %privileged;
1.800     albertel 3166:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3167:         my ($role,$tend,$tstart);
                   3168:         if ($context eq 'userroles') {
                   3169: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3170:         } else {
                   3171:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3172:         }
1.400     www      3173:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3174:         my $status = 'active';
1.939     raeburn  3175:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3176:             $status = 'previous';
                   3177:         } 
                   3178:         if (($tstart) && ($now<$tstart)) {
                   3179:             $status = 'future';
                   3180:         }
                   3181:         if (ref($types) eq 'ARRAY') {
                   3182:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3183:                 next;
                   3184:             } 
                   3185:         } else {
                   3186:             if ($status ne 'active') {
                   3187:                 next;
                   3188:             }
                   3189:         }
1.867     raeburn  3190:         my ($rolecode,$username,$domain,$section,$area);
                   3191:         if ($context eq 'userroles') {
                   3192:             ($area,$rolecode) = split(/_/,$entry);
                   3193:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3194:         } else {
                   3195:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3196:         }
1.832     raeburn  3197:         if (ref($roledoms) eq 'ARRAY') {
                   3198:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3199:                 next;
                   3200:             }
                   3201:         }
                   3202:         if (ref($roles) eq 'ARRAY') {
                   3203:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3204:                 if ($role =~ /^cr\//) {
                   3205:                     if (!grep(/^cr$/,@{$roles})) {
                   3206:                         next;
                   3207:                     }
                   3208:                 } else {
                   3209:                     next;
                   3210:                 }
1.832     raeburn  3211:             }
1.867     raeburn  3212:         }
1.937     raeburn  3213:         if ($hidepriv) {
1.999     raeburn  3214:             if ($context eq 'userroles') {
                   3215:                 if ((&privileged($username,$domain)) &&
                   3216:                     (!$nothide{$username.':'.$domain})) {
                   3217:                     next;
                   3218:                 }
                   3219:             } else {
                   3220:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3221:                     my %dompersonnel =
                   3222:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3223:                     $privileged{$domain} = {};
                   3224:                     if (keys(%dompersonnel)) {
                   3225:                         foreach my $server (keys(%dompersonnel)) {
                   3226:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3227:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3228:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3229:                                     $privileged{$udom}{$uname} = $trole;
                   3230:                                 }
                   3231:                             }
                   3232:                         }
                   3233:                     }
                   3234:                 }
                   3235:                 if (exists($privileged{$domain}{$username})) {
                   3236:                     if (!$nothide{$username.':'.$domain}) {
                   3237:                         next;
                   3238:                     }
                   3239:                 }
1.937     raeburn  3240:             }
                   3241:         }
1.933     raeburn  3242:         if ($withsec) {
                   3243:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3244:                 $tstart.':'.$tend;
                   3245:         } else {
                   3246:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3247:         }
1.832     raeburn  3248:     }
1.373     www      3249:     return %returnhash;
1.399     www      3250: }
                   3251: 
                   3252: # ----------------------------------------------------- Frontpage Announcements
                   3253: #
                   3254: #
                   3255: 
                   3256: sub postannounce {
                   3257:     my ($server,$text)=@_;
1.844     albertel 3258:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3259:     unless ($text=~/\w/) { $text=''; }
                   3260:     return &reply('setannounce:'.&escape($text),$server);
                   3261: }
                   3262: 
                   3263: sub getannounce {
1.448     albertel 3264: 
                   3265:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3266: 	my $announcement='';
1.800     albertel 3267: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3268: 	close($fh);
1.399     www      3269: 	if ($announcement=~/\w/) { 
                   3270: 	    return 
                   3271:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3272:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3273: 	} else {
                   3274: 	    return '';
                   3275: 	}
                   3276:     } else {
                   3277: 	return '';
                   3278:     }
1.351     www      3279: }
1.353     www      3280: 
                   3281: # ---------------------------------------------------------- Course ID routines
                   3282: # Deal with domain's nohist_courseid.db files
                   3283: #
                   3284: 
                   3285: sub courseidput {
1.921     raeburn  3286:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3287:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3288:     my $outcome;
                   3289:     if ($caller eq 'timeonly') {
                   3290:         my $cids = '';
                   3291:         foreach my $item (keys(%$storehash)) {
                   3292:             $cids.=&escape($item).'&';
                   3293:         }
                   3294:         $cids=~s/\&$//;
                   3295:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3296:                           $coursehome);       
                   3297:     } else {
                   3298:         my $items = '';
                   3299:         foreach my $item (keys(%$storehash)) {
                   3300:             $items.= &escape($item).'='.
                   3301:                      &freeze_escape($$storehash{$item}).'&';
                   3302:         }
                   3303:         $items=~s/\&$//;
                   3304:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3305:                           $coursehome);
1.918     raeburn  3306:     }
                   3307:     if ($outcome eq 'unknown_cmd') {
                   3308:         my $what;
                   3309:         foreach my $cid (keys(%$storehash)) {
                   3310:             $what .= &escape($cid).'=';
1.921     raeburn  3311:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3312:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3313:             }
                   3314:             $what =~ s/\:$/&/;
                   3315:         }
                   3316:         $what =~ s/\&$//;  
                   3317:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3318:     } else {
                   3319:         return $outcome;
                   3320:     }
1.353     www      3321: }
                   3322: 
                   3323: sub courseiddump {
1.921     raeburn  3324:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3325:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3326:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3327:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3328:     my $as_hash = 1;
                   3329:     my %returnhash;
                   3330:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3331:     my %libserv = &all_library();
                   3332:     foreach my $tryserver (keys(%libserv)) {
                   3333:         if ( (  $hostidflag == 1 
                   3334: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3335: 	     || (!defined($hostidflag)) ) {
                   3336: 
1.918     raeburn  3337: 	    if (($domfilter eq '') ||
                   3338: 		(&host_domain($tryserver) eq $domfilter)) {
                   3339:                 my $rep = 
                   3340:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3341:                          $sincefilter.':'.&escape($descfilter).':'.
                   3342:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3343:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3344:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3345:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3346:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3347:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3348:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3349:                          &escape($creationcontext).':'.$domcloner,
                   3350:                          $tryserver);
1.918     raeburn  3351:                 my @pairs=split(/\&/,$rep);
                   3352:                 foreach my $item (@pairs) {
                   3353:                     my ($key,$value)=split(/\=/,$item,2);
                   3354:                     $key = &unescape($key);
                   3355:                     next if ($key =~ /^error: 2 /);
                   3356:                     my $result = &thaw_unescape($value);
                   3357:                     if (ref($result) eq 'HASH') {
                   3358:                         $returnhash{$key}=$result;
                   3359:                     } else {
1.921     raeburn  3360:                         my @responses = split(/:/,$value);
                   3361:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3362:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3363:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3364:                         }
1.1008    raeburn  3365:                     }
1.353     www      3366:                 }
                   3367:             }
                   3368:         }
                   3369:     }
                   3370:     return %returnhash;
                   3371: }
                   3372: 
1.1055    raeburn  3373: sub courselastaccess {
                   3374:     my ($cdom,$cnum,$hostidref) = @_;
                   3375:     my %returnhash;
                   3376:     if ($cdom && $cnum) {
                   3377:         my $chome = &homeserver($cnum,$cdom);
                   3378:         if ($chome ne 'no_host') {
                   3379:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3380:             &extract_lastaccess(\%returnhash,$rep);
                   3381:         }
                   3382:     } else {
                   3383:         if (!$cdom) { $cdom=''; }
                   3384:         my %libserv = &all_library();
                   3385:         foreach my $tryserver (keys(%libserv)) {
                   3386:             if (ref($hostidref) eq 'ARRAY') {
                   3387:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3388:             } 
                   3389:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3390:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3391:                 &extract_lastaccess(\%returnhash,$rep);
                   3392:             }
                   3393:         }
                   3394:     }
                   3395:     return %returnhash;
                   3396: }
                   3397: 
                   3398: sub extract_lastaccess {
                   3399:     my ($returnhash,$rep) = @_;
                   3400:     if (ref($returnhash) eq 'HASH') {
                   3401:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3402:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3403:                  $rep eq '') {
                   3404:             my @pairs=split(/\&/,$rep);
                   3405:             foreach my $item (@pairs) {
                   3406:                 my ($key,$value)=split(/\=/,$item,2);
                   3407:                 $key = &unescape($key);
                   3408:                 next if ($key =~ /^error: 2 /);
                   3409:                 $returnhash->{$key} = &thaw_unescape($value);
                   3410:             }
                   3411:         }
                   3412:     }
                   3413:     return;
                   3414: }
                   3415: 
1.658     raeburn  3416: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3417: 
                   3418: sub dcmailput {
1.685     raeburn  3419:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3420:     my $status = &Apache::lonnet::critical(
1.740     www      3421:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3422:        &escape($message),$server);
1.662     raeburn  3423:     return $status;
                   3424: }
                   3425: 
1.658     raeburn  3426: sub dcmaildump {
                   3427:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3428:     my %returnhash=();
1.846     albertel 3429: 
                   3430:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3431:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3432:                                                          &escape($enddate).':';
                   3433: 	my @esc_senders=map { &escape($_)} @$senders;
                   3434: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3435: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3436:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3437:             if (($key) && ($value)) {
                   3438:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3439:             }
                   3440:         }
                   3441:     }
                   3442:     return %returnhash;
                   3443: }
1.662     raeburn  3444: # ---------------------------------------------------------- Domain roles
                   3445: 
                   3446: sub get_domain_roles {
                   3447:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3448:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3449:         $startdate = '.';
                   3450:     }
1.1018    raeburn  3451:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3452:         $enddate = '.';
                   3453:     }
1.922     raeburn  3454:     my $rolelist;
                   3455:     if (ref($roles) eq 'ARRAY') {
                   3456:         $rolelist = join(':',@{$roles});
                   3457:     }
1.662     raeburn  3458:     my %personnel = ();
1.841     albertel 3459: 
                   3460:     my %servers = &get_servers($dom,'library');
                   3461:     foreach my $tryserver (keys(%servers)) {
                   3462: 	%{$personnel{$tryserver}}=();
                   3463: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3464: 					    &escape($startdate).':'.
                   3465: 					    &escape($enddate).':'.
                   3466: 					    &escape($rolelist), $tryserver))) {
                   3467: 	    my ($key,$value) = split(/\=/,$line,2);
                   3468: 	    if (($key) && ($value)) {
                   3469: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3470: 	    }
                   3471: 	}
1.662     raeburn  3472:     }
                   3473:     return %personnel;
                   3474: }
1.658     raeburn  3475: 
1.149     www      3476: # ----------------------------------------------------------- Check out an item
                   3477: 
1.504     albertel 3478: sub get_first_access {
                   3479:     my ($type,$argsymb)=@_;
1.790     albertel 3480:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3481:     if ($argsymb) { $symb=$argsymb; }
                   3482:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3483:     if ($type eq 'course') {
                   3484: 	$res='course';
                   3485:     } elsif ($type eq 'map') {
1.588     albertel 3486: 	$res=&symbread($map);
                   3487:     } else {
                   3488: 	$res=$symb;
                   3489:     }
                   3490:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3491:     return $times{"$courseid\0$res"};
1.504     albertel 3492: }
                   3493: 
                   3494: sub set_first_access {
                   3495:     my ($type)=@_;
1.790     albertel 3496:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3497:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3498:     if ($type eq 'course') {
                   3499: 	$res='course';
                   3500:     } elsif ($type eq 'map') {
1.588     albertel 3501: 	$res=&symbread($map);
                   3502:     } else {
                   3503: 	$res=$symb;
                   3504:     }
                   3505:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3506:     if (!$firstaccess) {
1.588     albertel 3507: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3508:     }
                   3509:     return 'already_set';
1.504     albertel 3510: }
                   3511: 
1.149     www      3512: sub checkout {
                   3513:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3514:     my $now=time;
                   3515:     my $lonhost=$perlvar{'lonHostID'};
                   3516:     my $infostr=&escape(
1.234     www      3517:                  'CHECKOUTTOKEN&'.
1.149     www      3518:                  $tuname.'&'.
                   3519:                  $tudom.'&'.
                   3520:                  $tcrsid.'&'.
                   3521:                  $symb.'&'.
                   3522: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3523:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3524:     if ($token=~/^error\:/) { 
1.672     albertel 3525:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3526:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3527:                  "</font>");
                   3528:         return ''; 
                   3529:     }
                   3530: 
1.149     www      3531:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3532:     $token=~tr/a-z/A-Z/;
                   3533: 
1.153     www      3534:     my %infohash=('resource.0.outtoken' => $token,
                   3535:                   'resource.0.checkouttime' => $now,
                   3536:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3537: 
                   3538:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3539:        return '';
1.151     www      3540:     } else {
1.672     albertel 3541:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3542:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3543:                  "</font>");
1.149     www      3544:     }    
                   3545: 
                   3546:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3547:                          &escape('Checkout '.$infostr.' - '.
                   3548:                                                  $token)) ne 'ok') {
                   3549: 	return '';
1.151     www      3550:     } else {
1.672     albertel 3551:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3552:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3553:                  "</font>");
1.149     www      3554:     }
1.151     www      3555:     return $token;
1.149     www      3556: }
                   3557: 
                   3558: # ------------------------------------------------------------ Check in an item
                   3559: 
                   3560: sub checkin {
                   3561:     my $token=shift;
1.150     www      3562:     my $now=time;
                   3563:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3564:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3565:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3566:     $dtoken=~s/\W/\_/g;
1.234     www      3567:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3568:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3569: 
1.154     www      3570:     unless (($tuname) && ($tudom)) {
                   3571:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3572:         return '';
                   3573:     }
                   3574:     
                   3575:     unless (&allowed('mgr',$tcrsid)) {
                   3576:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3577:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3578:         return '';
                   3579:     }
                   3580: 
1.153     www      3581:     my %infohash=('resource.0.intoken' => $token,
                   3582:                   'resource.0.checkintime' => $now,
                   3583:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3584: 
                   3585:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3586:        return '';
                   3587:     }    
                   3588: 
                   3589:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3590:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3591: 	return '';
                   3592:     }
                   3593: 
                   3594:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3595: }
                   3596: 
                   3597: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3598: 
                   3599: sub expirespread {
                   3600:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3601:     my $cid=$env{'request.course.id'}; 
1.110     www      3602:     if ($cid) {
                   3603:        my $now=time;
                   3604:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3605:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3606:                             $env{'course.'.$cid.'.num'}.
1.110     www      3607: 	        	    ':nohist_expirationdates:'.
                   3608:                             &escape($key).'='.$now,
1.620     albertel 3609:                             $env{'course.'.$cid.'.home'})
1.110     www      3610:     }
                   3611:     return 'ok';
1.14      www      3612: }
                   3613: 
1.109     www      3614: # ----------------------------------------------------- Devalidate Spreadsheets
                   3615: 
                   3616: sub devalidate {
1.325     www      3617:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3618:     my $cid=$env{'request.course.id'}; 
1.109     www      3619:     if ($cid) {
1.391     matthew  3620:         # delete the stored spreadsheets for
                   3621:         # - the student level sheet of this user in course's homespace
                   3622:         # - the assessment level sheet for this resource 
                   3623:         #   for this user in user's homespace
1.553     albertel 3624: 	# - current conditional state info
1.325     www      3625: 	my $key=$uname.':'.$udom.':';
1.109     www      3626:         my $status=
1.299     matthew  3627: 	    &del('nohist_calculatedsheets',
1.391     matthew  3628: 		 [$key.'studentcalc:'],
1.620     albertel 3629: 		 $env{'course.'.$cid.'.domain'},
                   3630: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3631: 		.' '.
                   3632: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3633: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3634:         unless ($status eq 'ok ok') {
                   3635:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3636:                     $uname.' at '.$udom.' for '.
1.109     www      3637: 		    $symb.': '.$status);
1.133     albertel 3638:         }
1.553     albertel 3639: 	&delenv('user.state.'.$cid);
1.109     www      3640:     }
                   3641: }
                   3642: 
1.265     albertel 3643: sub get_scalar {
                   3644:     my ($string,$end) = @_;
                   3645:     my $value;
                   3646:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3647: 	$value = $1;
                   3648:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3649: 	$value = $1;
                   3650:     }
                   3651:     return &unescape($value);
                   3652: }
                   3653: 
                   3654: sub array2str {
                   3655:   my (@array) = @_;
                   3656:   my $result=&arrayref2str(\@array);
                   3657:   $result=~s/^__ARRAY_REF__//;
                   3658:   $result=~s/__END_ARRAY_REF__$//;
                   3659:   return $result;
                   3660: }
                   3661: 
1.204     albertel 3662: sub arrayref2str {
                   3663:   my ($arrayref) = @_;
1.265     albertel 3664:   my $result='__ARRAY_REF__';
1.204     albertel 3665:   foreach my $elem (@$arrayref) {
1.265     albertel 3666:     if(ref($elem) eq 'ARRAY') {
                   3667:       $result.=&arrayref2str($elem).'&';
                   3668:     } elsif(ref($elem) eq 'HASH') {
                   3669:       $result.=&hashref2str($elem).'&';
                   3670:     } elsif(ref($elem)) {
                   3671:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3672:     } else {
                   3673:       $result.=&escape($elem).'&';
                   3674:     }
                   3675:   }
                   3676:   $result=~s/\&$//;
1.265     albertel 3677:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3678:   return $result;
                   3679: }
                   3680: 
1.168     albertel 3681: sub hash2str {
1.204     albertel 3682:   my (%hash) = @_;
                   3683:   my $result=&hashref2str(\%hash);
1.265     albertel 3684:   $result=~s/^__HASH_REF__//;
                   3685:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3686:   return $result;
                   3687: }
                   3688: 
                   3689: sub hashref2str {
                   3690:   my ($hashref)=@_;
1.265     albertel 3691:   my $result='__HASH_REF__';
1.800     albertel 3692:   foreach my $key (sort(keys(%$hashref))) {
                   3693:     if (ref($key) eq 'ARRAY') {
                   3694:       $result.=&arrayref2str($key).'=';
                   3695:     } elsif (ref($key) eq 'HASH') {
                   3696:       $result.=&hashref2str($key).'=';
                   3697:     } elsif (ref($key)) {
1.265     albertel 3698:       $result.='=';
1.800     albertel 3699:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3700:     } else {
1.800     albertel 3701: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3702:     }
                   3703: 
1.800     albertel 3704:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3705:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3706:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3707:       $result.=&hashref2str($hashref->{$key}).'&';
                   3708:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3709:        $result.='&';
1.800     albertel 3710:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3711:     } else {
1.800     albertel 3712:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3713:     }
                   3714:   }
1.168     albertel 3715:   $result=~s/\&$//;
1.265     albertel 3716:   $result .= '__END_HASH_REF__';
1.168     albertel 3717:   return $result;
                   3718: }
                   3719: 
                   3720: sub str2hash {
1.265     albertel 3721:     my ($string)=@_;
                   3722:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3723:     return %$hash;
                   3724: }
                   3725: 
                   3726: sub str2hashref {
1.168     albertel 3727:   my ($string) = @_;
1.265     albertel 3728: 
                   3729:   my %hash;
                   3730: 
                   3731:   if($string !~ /^__HASH_REF__/) {
                   3732:       if (! ($string eq '' || !defined($string))) {
                   3733: 	  $hash{'error'}='Not hash reference';
                   3734:       }
                   3735:       return (\%hash, $string);
                   3736:   }
                   3737: 
                   3738:   $string =~ s/^__HASH_REF__//;
                   3739: 
                   3740:   while($string !~ /^__END_HASH_REF__/) {
                   3741:       #key
                   3742:       my $key='';
                   3743:       if($string =~ /^__HASH_REF__/) {
                   3744:           ($key, $string)=&str2hashref($string);
                   3745:           if(defined($key->{'error'})) {
                   3746:               $hash{'error'}='Bad data';
                   3747:               return (\%hash, $string);
                   3748:           }
                   3749:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3750:           ($key, $string)=&str2arrayref($string);
                   3751:           if($key->[0] eq 'Array reference error') {
                   3752:               $hash{'error'}='Bad data';
                   3753:               return (\%hash, $string);
                   3754:           }
                   3755:       } else {
                   3756:           $string =~ s/^(.*?)=//;
1.267     albertel 3757: 	  $key=&unescape($1);
1.265     albertel 3758:       }
                   3759:       $string =~ s/^=//;
                   3760: 
                   3761:       #value
                   3762:       my $value='';
                   3763:       if($string =~ /^__HASH_REF__/) {
                   3764:           ($value, $string)=&str2hashref($string);
                   3765:           if(defined($value->{'error'})) {
                   3766:               $hash{'error'}='Bad data';
                   3767:               return (\%hash, $string);
                   3768:           }
                   3769:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3770:           ($value, $string)=&str2arrayref($string);
                   3771:           if($value->[0] eq 'Array reference error') {
                   3772:               $hash{'error'}='Bad data';
                   3773:               return (\%hash, $string);
                   3774:           }
                   3775:       } else {
                   3776: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3777:       }
                   3778:       $string =~ s/^&//;
                   3779: 
                   3780:       $hash{$key}=$value;
1.204     albertel 3781:   }
1.265     albertel 3782: 
                   3783:   $string =~ s/^__END_HASH_REF__//;
                   3784: 
                   3785:   return (\%hash, $string);
1.204     albertel 3786: }
                   3787: 
                   3788: sub str2array {
1.265     albertel 3789:     my ($string)=@_;
                   3790:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3791:     return @$array;
                   3792: }
                   3793: 
                   3794: sub str2arrayref {
1.204     albertel 3795:   my ($string) = @_;
1.265     albertel 3796:   my @array;
                   3797: 
                   3798:   if($string !~ /^__ARRAY_REF__/) {
                   3799:       if (! ($string eq '' || !defined($string))) {
                   3800: 	  $array[0]='Array reference error';
                   3801:       }
                   3802:       return (\@array, $string);
                   3803:   }
                   3804: 
                   3805:   $string =~ s/^__ARRAY_REF__//;
                   3806: 
                   3807:   while($string !~ /^__END_ARRAY_REF__/) {
                   3808:       my $value='';
                   3809:       if($string =~ /^__HASH_REF__/) {
                   3810:           ($value, $string)=&str2hashref($string);
                   3811:           if(defined($value->{'error'})) {
                   3812:               $array[0] ='Array reference error';
                   3813:               return (\@array, $string);
                   3814:           }
                   3815:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3816:           ($value, $string)=&str2arrayref($string);
                   3817:           if($value->[0] eq 'Array reference error') {
                   3818:               $array[0] ='Array reference error';
                   3819:               return (\@array, $string);
                   3820:           }
                   3821:       } else {
                   3822: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3823:       }
                   3824:       $string =~ s/^&//;
                   3825: 
                   3826:       push(@array, $value);
1.191     harris41 3827:   }
1.265     albertel 3828: 
                   3829:   $string =~ s/^__END_ARRAY_REF__//;
                   3830: 
                   3831:   return (\@array, $string);
1.168     albertel 3832: }
                   3833: 
1.167     albertel 3834: # -------------------------------------------------------------------Temp Store
                   3835: 
1.168     albertel 3836: sub tmpreset {
                   3837:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3838:   if (!$symb) {
                   3839:     $symb=&symbread();
1.620     albertel 3840:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3841:   }
                   3842:   $symb=escape($symb);
                   3843: 
1.620     albertel 3844:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3845:   $namespace=~s/\//\_/g;
                   3846:   $namespace=~s/\W//g;
                   3847: 
1.620     albertel 3848:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3849:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3850:   if ($domain eq 'public' && $stuname eq 'public') {
                   3851:       $stuname=$ENV{'REMOTE_ADDR'};
                   3852:   }
1.168     albertel 3853:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3854:   my %hash;
                   3855:   if (tie(%hash,'GDBM_File',
                   3856: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3857: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3858:     foreach my $key (keys(%hash)) {
1.180     albertel 3859:       if ($key=~ /:$symb/) {
1.168     albertel 3860: 	delete($hash{$key});
                   3861:       }
                   3862:     }
                   3863:   }
                   3864: }
                   3865: 
1.167     albertel 3866: sub tmpstore {
1.168     albertel 3867:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3868: 
                   3869:   if (!$symb) {
                   3870:     $symb=&symbread();
1.620     albertel 3871:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3872:   }
                   3873:   $symb=escape($symb);
                   3874: 
                   3875:   if (!$namespace) {
                   3876:     # I don't think we would ever want to store this for a course.
                   3877:     # it seems this will only be used if we don't have a course.
1.620     albertel 3878:     #$namespace=$env{'request.course.id'};
1.168     albertel 3879:     #if (!$namespace) {
1.620     albertel 3880:       $namespace=$env{'request.state'};
1.168     albertel 3881:     #}
                   3882:   }
                   3883:   $namespace=~s/\//\_/g;
                   3884:   $namespace=~s/\W//g;
1.620     albertel 3885:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3886:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3887:   if ($domain eq 'public' && $stuname eq 'public') {
                   3888:       $stuname=$ENV{'REMOTE_ADDR'};
                   3889:   }
1.168     albertel 3890:   my $now=time;
                   3891:   my %hash;
                   3892:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3893:   if (tie(%hash,'GDBM_File',
                   3894: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3895: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3896:     $hash{"version:$symb"}++;
                   3897:     my $version=$hash{"version:$symb"};
                   3898:     my $allkeys=''; 
                   3899:     foreach my $key (keys(%$storehash)) {
                   3900:       $allkeys.=$key.':';
1.591     albertel 3901:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3902:     }
                   3903:     $hash{"$version:$symb:timestamp"}=$now;
                   3904:     $allkeys.='timestamp';
                   3905:     $hash{"$version:keys:$symb"}=$allkeys;
                   3906:     if (untie(%hash)) {
                   3907:       return 'ok';
                   3908:     } else {
                   3909:       return "error:$!";
                   3910:     }
                   3911:   } else {
                   3912:     return "error:$!";
                   3913:   }
                   3914: }
1.167     albertel 3915: 
1.168     albertel 3916: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3917: 
1.168     albertel 3918: sub tmprestore {
                   3919:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3920: 
1.168     albertel 3921:   if (!$symb) {
                   3922:     $symb=&symbread();
1.620     albertel 3923:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3924:   }
                   3925:   $symb=escape($symb);
                   3926: 
1.620     albertel 3927:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3928: 
1.620     albertel 3929:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3930:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3931:   if ($domain eq 'public' && $stuname eq 'public') {
                   3932:       $stuname=$ENV{'REMOTE_ADDR'};
                   3933:   }
1.168     albertel 3934:   my %returnhash;
                   3935:   $namespace=~s/\//\_/g;
                   3936:   $namespace=~s/\W//g;
                   3937:   my %hash;
                   3938:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3939:   if (tie(%hash,'GDBM_File',
                   3940: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3941: 	  &GDBM_READER(),0640)) {
1.168     albertel 3942:     my $version=$hash{"version:$symb"};
                   3943:     $returnhash{'version'}=$version;
                   3944:     my $scope;
                   3945:     for ($scope=1;$scope<=$version;$scope++) {
                   3946:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3947:       my @keys=split(/:/,$vkeys);
                   3948:       my $key;
                   3949:       $returnhash{"$scope:keys"}=$vkeys;
                   3950:       foreach $key (@keys) {
1.591     albertel 3951: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3952: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3953:       }
                   3954:     }
1.168     albertel 3955:     if (!(untie(%hash))) {
                   3956:       return "error:$!";
                   3957:     }
                   3958:   } else {
                   3959:     return "error:$!";
                   3960:   }
                   3961:   return %returnhash;
1.167     albertel 3962: }
                   3963: 
1.9       www      3964: # ----------------------------------------------------------------------- Store
                   3965: 
                   3966: sub store {
1.124     www      3967:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3968:     my $home='';
                   3969: 
1.168     albertel 3970:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3971: 
1.213     www      3972:     $symb=&symbclean($symb);
1.122     albertel 3973:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3974: 
1.620     albertel 3975:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3976:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3977: 
                   3978:     &devalidate($symb,$stuname,$domain);
1.109     www      3979: 
                   3980:     $symb=escape($symb);
1.187     www      3981:     if (!$namespace) { 
1.620     albertel 3982:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3983:           return ''; 
                   3984:        } 
                   3985:     }
1.620     albertel 3986:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3987: 
                   3988:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3989:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3990: 
1.12      www      3991:     my $namevalue='';
1.800     albertel 3992:     foreach my $key (keys(%$storehash)) {
                   3993:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3994:     }
1.12      www      3995:     $namevalue=~s/\&$//;
1.187     www      3996:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3997:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3998: }
                   3999: 
1.47      www      4000: # -------------------------------------------------------------- Critical Store
                   4001: 
                   4002: sub cstore {
1.124     www      4003:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4004:     my $home='';
                   4005: 
1.168     albertel 4006:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4007: 
1.213     www      4008:     $symb=&symbclean($symb);
1.122     albertel 4009:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4010: 
1.620     albertel 4011:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4012:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4013: 
                   4014:     &devalidate($symb,$stuname,$domain);
1.109     www      4015: 
                   4016:     $symb=escape($symb);
1.187     www      4017:     if (!$namespace) { 
1.620     albertel 4018:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4019:           return ''; 
                   4020:        } 
                   4021:     }
1.620     albertel 4022:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4023: 
                   4024:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4025:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4026: 
1.47      www      4027:     my $namevalue='';
1.800     albertel 4028:     foreach my $key (keys(%$storehash)) {
                   4029:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4030:     }
1.47      www      4031:     $namevalue=~s/\&$//;
1.187     www      4032:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4033:     return critical
                   4034:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4035: }
                   4036: 
1.9       www      4037: # --------------------------------------------------------------------- Restore
                   4038: 
                   4039: sub restore {
1.124     www      4040:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4041:     my $home='';
                   4042: 
1.168     albertel 4043:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4044: 
1.122     albertel 4045:     if (!$symb) {
                   4046:       unless ($symb=escape(&symbread())) { return ''; }
                   4047:     } else {
1.213     www      4048:       $symb=&escape(&symbclean($symb));
1.122     albertel 4049:     }
1.188     www      4050:     if (!$namespace) { 
1.620     albertel 4051:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4052:           return ''; 
                   4053:        } 
                   4054:     }
1.620     albertel 4055:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4056:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4057:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4058:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4059: 
1.12      www      4060:     my %returnhash=();
1.800     albertel 4061:     foreach my $line (split(/\&/,$answer)) {
                   4062: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4063:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4064:     }
1.75      www      4065:     my $version;
                   4066:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4067:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4068:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4069:        }
1.75      www      4070:     }
1.13      www      4071:     return %returnhash;
1.34      www      4072: }
                   4073: 
                   4074: # ---------------------------------------------------------- Course Description
                   4075: 
                   4076: sub coursedescription {
1.731     albertel 4077:     my ($courseid,$args)=@_;
1.34      www      4078:     $courseid=~s/^\///;
1.49      www      4079:     $courseid=~s/\_/\//g;
1.34      www      4080:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4081:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4082:     my $normalid=$cdomain.'_'.$cnum;
                   4083:     # need to always cache even if we get errors otherwise we keep 
                   4084:     # trying and trying and trying to get the course description.
                   4085:     my %envhash=();
                   4086:     my %returnhash=();
1.731     albertel 4087:     
                   4088:     my $expiretime=600;
                   4089:     if ($env{'request.course.id'} eq $normalid) {
                   4090: 	$expiretime=120;
                   4091:     }
                   4092: 
                   4093:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4094:     if (!$args->{'freshen_cache'}
                   4095: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4096: 	foreach my $key (keys(%env)) {
                   4097: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4098: 	    my ($setting) = $1;
                   4099: 	    $returnhash{$setting} = $env{$key};
                   4100: 	}
                   4101: 	return %returnhash;
                   4102:     }
                   4103: 
                   4104:     # get the data agin
                   4105:     if (!$args->{'one_time'}) {
                   4106: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4107:     }
1.811     albertel 4108: 
1.34      www      4109:     if ($chome ne 'no_host') {
1.302     albertel 4110:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4111:        if (!exists($returnhash{'con_lost'})) {
                   4112:            $returnhash{'home'}= $chome;
                   4113: 	   $returnhash{'domain'} = $cdomain;
                   4114: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4115:            if (!defined($returnhash{'type'})) {
                   4116:                $returnhash{'type'} = 'Course';
                   4117:            }
1.130     albertel 4118:            while (my ($name,$value) = each %returnhash) {
1.53      www      4119:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4120:            }
1.270     www      4121:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4122:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4123: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4124:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4125:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4126:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4127:        }
                   4128:     }
1.731     albertel 4129:     if (!$args->{'one_time'}) {
1.949     raeburn  4130: 	&appenv(\%envhash);
1.731     albertel 4131:     }
1.302     albertel 4132:     return %returnhash;
1.461     www      4133: }
                   4134: 
1.1056.4.5  raeburn  4135: sub update_released_required {
                   4136:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4137:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4138:         $cid = $env{'request.course.id'};
                   4139:         $cdom = $env{'course.'.$cid.'.domain'};
                   4140:         $cnum = $env{'course.'.$cid.'.num'};
                   4141:         $chome = $env{'course.'.$cid.'.home'};
                   4142:     }
                   4143:     if ($needsrelease) {
                   4144:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4145:         my $needsupdate;
                   4146:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4147:             $needsupdate = 1;
                   4148:         } else {
                   4149:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4150:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4151:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4152:                 $needsupdate = 1;
                   4153:             }
                   4154:         }
                   4155:         if ($needsupdate) {
                   4156:             my %needshash = (
                   4157:                              'internal.releaserequired' => $needsrelease,
                   4158:                             );
                   4159:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4160:             if ($putresult eq 'ok') {
                   4161:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4162:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4163:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4164:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4165:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4166:                 }
                   4167:             }
                   4168:         }
                   4169:     }
                   4170:     return;
                   4171: }
                   4172: 
1.461     www      4173: # -------------------------------------------------See if a user is privileged
                   4174: 
                   4175: sub privileged {
                   4176:     my ($username,$domain)=@_;
                   4177:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4178: 			&homeserver($username,$domain));
1.1033    raeburn  4179:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4180:         ($rolesdump =~ /^error:/)) {
                   4181:         return 0;
                   4182:     }
1.461     www      4183:     my $now=time;
                   4184:     if ($rolesdump ne '') {
1.800     albertel 4185:         foreach my $entry (split(/&/,$rolesdump)) {
                   4186: 	    if ($entry!~/^rolesdef_/) {
                   4187: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4188: 		$area=~s/\_\w\w$//;
                   4189: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4190: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4191: 		    my $active=1;
                   4192: 		    if ($tend) {
                   4193: 			if ($tend<$now) { $active=0; }
                   4194: 		    }
                   4195: 		    if ($tstart) {
                   4196: 			if ($tstart>$now) { $active=0; }
                   4197: 		    }
                   4198: 		    if ($active) { return 1; }
                   4199: 		}
                   4200: 	    }
                   4201: 	}
                   4202:     }
                   4203:     return 0;
1.9       www      4204: }
1.1       albertel 4205: 
1.103     harris41 4206: # -------------------------------------------------------- Get user privileges
1.11      www      4207: 
                   4208: sub rolesinit {
                   4209:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4210:     my $now=time;
                   4211:     my %userroles = ('user.login.time' => $now);
1.1056.4.10  raeburn  4212:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3  raeburn  4213:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4214:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4215:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4216:         return \%userroles;
                   4217:     }
1.11      www      4218:     my %allroles=();
1.678     raeburn  4219:     my %allgroups=();   
                   4220:     my $group_privs;
1.11      www      4221: 
                   4222:     if ($rolesdump ne '') {
1.800     albertel 4223:         foreach my $entry (split(/&/,$rolesdump)) {
                   4224: 	  if ($entry!~/^rolesdef_/) {
                   4225:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4226: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4227:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4228: 	    if ($role=~/^cr/) { 
1.807     albertel 4229: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4230: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4231: 		    ($tend,$tstart)=split('_',$trest);
                   4232: 		} else {
                   4233: 		    $trole=$role;
                   4234: 		}
1.678     raeburn  4235:             } elsif ($role =~ m|^gr/|) {
                   4236:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4237:                 ($trole,$group_privs) = split(/\//,$trole);
                   4238:                 $group_privs = &unescape($group_privs);
1.587     albertel 4239: 	    } else {
                   4240: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4241: 	    }
1.743     albertel 4242: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4243: 					 $username);
                   4244: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4245:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4246:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4247:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4248: 		my $spec=$trole.'.'.$area;
                   4249: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4250: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4251:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4252:                 } elsif ($trole eq 'gr') {
                   4253:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4254: 		} else {
1.567     raeburn  4255:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4256: 		}
1.12      www      4257:             }
1.662     raeburn  4258:           }
1.191     harris41 4259:         }
1.743     albertel 4260:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4261:         $userroles{'user.adv'}    = $adv;
                   4262: 	$userroles{'user.author'} = $author;
1.620     albertel 4263:         $env{'user.adv'}=$adv;
1.11      www      4264:     }
1.743     albertel 4265:     return \%userroles;  
1.11      www      4266: }
                   4267: 
1.567     raeburn  4268: sub set_arearole {
                   4269:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4270: # log the associated role with the area
                   4271:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4272:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4273: }
                   4274: 
                   4275: sub custom_roleprivs {
                   4276:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4277:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4278:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4279:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4280:         my ($rdummy,$roledef)=
                   4281:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4282:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4283:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4284:             if (defined($syspriv)) {
1.1043    raeburn  4285:                 if ($trest =~ /^$match_community$/) {
                   4286:                     $syspriv =~ s/bre\&S//; 
                   4287:                 }
1.567     raeburn  4288:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4289:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4290:             }
                   4291:             if ($tdomain ne '') {
                   4292:                 if (defined($dompriv)) {
                   4293:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4294:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4295:                 }
                   4296:                 if (($trest ne '') && (defined($coursepriv))) {
                   4297:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4298:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4299:                 }
                   4300:             }
                   4301:         }
                   4302:     }
                   4303: }
                   4304: 
1.678     raeburn  4305: sub group_roleprivs {
                   4306:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4307:     my $access = 1;
                   4308:     my $now = time;
                   4309:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4310:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4311:     if ($access) {
1.811     albertel 4312:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4313:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4314:     }
                   4315: }
1.567     raeburn  4316: 
                   4317: sub standard_roleprivs {
                   4318:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4319:     if (defined($pr{$trole.':s'})) {
                   4320:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4321:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4322:     }
                   4323:     if ($tdomain ne '') {
                   4324:         if (defined($pr{$trole.':d'})) {
                   4325:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4326:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4327:         }
                   4328:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4329:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4330:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4331:         }
                   4332:     }
                   4333: }
                   4334: 
                   4335: sub set_userprivs {
1.1056.4.2  raeburn  4336:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4337:     my $author=0;
                   4338:     my $adv=0;
1.678     raeburn  4339:     my %grouproles = ();
                   4340:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4341:         my @groupkeys;
1.1000    raeburn  4342:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4343:             push(@groupkeys,$role);
                   4344:         }
                   4345:         if (ref($groups_roles) eq 'HASH') {
                   4346:             foreach my $key (keys(%{$groups_roles})) {
                   4347:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4348:                     push(@groupkeys,$key);
                   4349:                 }
                   4350:             }
                   4351:         }
                   4352:         if (@groupkeys > 0) {
                   4353:             foreach my $role (@groupkeys) {
                   4354:                 my ($trole,$area,$sec,$extendedarea);
                   4355:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4356:                     $trole = $1;
                   4357:                     $area = $2;
                   4358:                     $sec = $3;
                   4359:                     $extendedarea = $area.$sec;
                   4360:                     if (exists($$allgroups{$area})) {
                   4361:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4362:                             my $spec = $trole.'.'.$extendedarea;
                   4363:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4364:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4365:                         }
1.678     raeburn  4366:                     }
                   4367:                 }
                   4368:             }
                   4369:         }
                   4370:     }
1.800     albertel 4371:     foreach my $group (keys(%grouproles)) {
                   4372:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4373:     }
1.800     albertel 4374:     foreach my $role (keys(%{$allroles})) {
                   4375:         my %thesepriv;
1.941     raeburn  4376:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4377:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4378:             if ($item ne '') {
                   4379:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4380:                 if ($restrictions eq '') {
                   4381:                     $thesepriv{$privilege}='F';
                   4382:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4383:                     $thesepriv{$privilege}.=$restrictions;
                   4384:                 }
                   4385:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4386:             }
                   4387:         }
                   4388:         my $thesestr='';
1.800     albertel 4389:         foreach my $priv (keys(%thesepriv)) {
                   4390: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4391: 	}
                   4392:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4393:     }
                   4394:     return ($author,$adv);
                   4395: }
                   4396: 
1.994     raeburn  4397: sub role_status {
1.1002    raeburn  4398:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4399:     my @pwhere = ();
                   4400:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4401:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4402:         unless (!defined($$role) || $$role eq '') {
                   4403:             $$where=join('.',@pwhere);
                   4404:             $$trolecode=$$role.'.'.$$where;
                   4405:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4406:             $$tstatus='is';
                   4407:             if ($$tstart && $$tstart>$then) {
                   4408:                 $$tstatus='future';
1.1034    raeburn  4409:                 if ($$tstart<$now) {
                   4410:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4411:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4412:                             my (%allroles,%allgroups,$group_privs,
                   4413:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4414:                             my %userroles = (
                   4415:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4416:                             );
1.1056.4.2  raeburn  4417:                             @rolecodes = ('cm');
1.1002    raeburn  4418:                             my $spec=$$role.'.'.$$where;
                   4419:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4420:                             if ($$role =~ /^cr\//) {
                   4421:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4422:                                 push(@rolecodes,'cr');
1.1002    raeburn  4423:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4424:                                 push(@rolecodes,$$role);
1.1002    raeburn  4425:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4426:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4427:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4428:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4429:                                 $group_privs = &unescape($group_privs);
                   4430:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4431:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4432:                                 if (keys(%course_roles) > 0) {
                   4433:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4434:                                     if ($tdomain ne '' && $tnum ne '') {
                   4435:                                         foreach my $key (keys(%course_roles)) {
                   4436:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4437:                                                 my $crsrole = $1;
                   4438:                                                 my $crssec = $2;
                   4439:                                                 if ($crsrole =~ /^cr/) {
                   4440:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4441:                                                         push(@rolecodes,'cr');
                   4442:                                                     }
                   4443:                                                 } else {
                   4444:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4445:                                                         push(@rolecodes,$crsrole);
                   4446:                                                     }
                   4447:                                                 }
                   4448:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4449:                                                 if ($crssec ne '') {
                   4450:                                                     $rolekey .= '/'.$crssec;
                   4451:                                                 }
                   4452:                                                 $rolekey .= './';
                   4453:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4454:                                             }
                   4455:                                         }
                   4456:                                     }
                   4457:                                 }
1.1002    raeburn  4458:                             } else {
1.1056.4.2  raeburn  4459:                                 push(@rolecodes,$$role);
1.1002    raeburn  4460:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4461:                             }
1.1056.4.2  raeburn  4462:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4463:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4464:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4465:                         }
                   4466:                     }
1.1034    raeburn  4467:                     $$tstatus = 'is';
1.1002    raeburn  4468:                 }
1.994     raeburn  4469:             }
                   4470:             if ($$tend) {
                   4471:                 if ($$tend<$then) {
                   4472:                     $$tstatus='expired';
                   4473:                 } elsif ($$tend<$now) {
                   4474:                     $$tstatus='will_not';
                   4475:                 }
                   4476:             }
                   4477:         }
                   4478:     }
                   4479: }
                   4480: 
                   4481: sub check_adhoc_privs {
1.1056.4.12  raeburn  4482:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4483:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4484:     if ($env{$cckey}) {
                   4485:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4486:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4487:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12  raeburn  4488:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4489:         }
                   4490:     } else {
1.1056.4.12  raeburn  4491:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4492:     }
                   4493: }
                   4494: 
                   4495: sub set_adhoc_privileges {
                   4496: # role can be cc or ca
1.1056.4.12  raeburn  4497:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4498:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4499:     my $spec = $role.'.'.$area;
                   4500:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4501:                                   $env{'user.name'});
                   4502:     my %ccrole = ();
                   4503:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4504:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4505:     &appenv(\%userroles,[$role,'cm']);
                   4506:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12  raeburn  4507:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4508:         &appenv( {'request.role'        => $spec,
                   4509:                   'request.role.domain' => $dcdom,
                   4510:                   'request.course.sec'  => ''
                   4511:                  }
                   4512:                );
                   4513:         my $tadv=0;
                   4514:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4515:         &appenv({'request.role.adv'    => $tadv});
                   4516:     }
1.994     raeburn  4517: }
                   4518: 
1.12      www      4519: # --------------------------------------------------------------- get interface
                   4520: 
                   4521: sub get {
1.131     albertel 4522:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4523:    my $items='';
1.800     albertel 4524:    foreach my $item (@$storearr) {
                   4525:        $items.=&escape($item).'&';
1.191     harris41 4526:    }
1.12      www      4527:    $items=~s/\&$//;
1.620     albertel 4528:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4529:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4530:    my $uhome=&homeserver($uname,$udomain);
                   4531: 
1.133     albertel 4532:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4533:    my @pairs=split(/\&/,$rep);
1.273     albertel 4534:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4535:      return @pairs;
                   4536:    }
1.15      www      4537:    my %returnhash=();
1.42      www      4538:    my $i=0;
1.800     albertel 4539:    foreach my $item (@$storearr) {
                   4540:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4541:       $i++;
1.191     harris41 4542:    }
1.15      www      4543:    return %returnhash;
1.27      www      4544: }
                   4545: 
                   4546: # --------------------------------------------------------------- del interface
                   4547: 
                   4548: sub del {
1.133     albertel 4549:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4550:    my $items='';
1.800     albertel 4551:    foreach my $item (@$storearr) {
                   4552:        $items.=&escape($item).'&';
1.191     harris41 4553:    }
1.984     neumanie 4554: 
1.27      www      4555:    $items=~s/\&$//;
1.620     albertel 4556:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4557:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4558:    my $uhome=&homeserver($uname,$udomain);
                   4559:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4560: }
                   4561: 
                   4562: # -------------------------------------------------------------- dump interface
                   4563: 
                   4564: sub dump {
1.1056.4.10  raeburn  4565:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4566:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4567:     if (!$uname) { $uname=$env{'user.name'}; }
                   4568:     my $uhome=&homeserver($uname,$udomain);
                   4569:     if ($regexp) {
                   4570: 	$regexp=&escape($regexp);
                   4571:     } else {
                   4572: 	$regexp='.';
                   4573:     }
1.1056.4.10  raeburn  4574:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4575:     my @pairs=split(/\&/,$rep);
                   4576:     my %returnhash=();
                   4577:     foreach my $item (@pairs) {
                   4578: 	my ($key,$value)=split(/=/,$item,2);
                   4579: 	$key = &unescape($key);
                   4580: 	next if ($key =~ /^error: 2 /);
                   4581: 	$returnhash{$key}=&thaw_unescape($value);
                   4582:     }
                   4583:     return %returnhash;
1.407     www      4584: }
                   4585: 
1.717     albertel 4586: # --------------------------------------------------------- dumpstore interface
                   4587: 
                   4588: sub dumpstore {
                   4589:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4590:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4591:    if (!$uname) { $uname=$env{'user.name'}; }
                   4592:    my $uhome=&homeserver($uname,$udomain);
                   4593:    if ($regexp) {
                   4594:        $regexp=&escape($regexp);
                   4595:    } else {
                   4596:        $regexp='.';
                   4597:    }
                   4598:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4599:    my @pairs=split(/\&/,$rep);
                   4600:    my %returnhash=();
                   4601:    foreach my $item (@pairs) {
                   4602:        my ($key,$value)=split(/=/,$item,2);
                   4603:        next if ($key =~ /^error: 2 /);
                   4604:        $returnhash{$key}=&thaw_unescape($value);
                   4605:    }
                   4606:    return %returnhash;
1.717     albertel 4607: }
                   4608: 
1.407     www      4609: # -------------------------------------------------------------- keys interface
                   4610: 
                   4611: sub getkeys {
                   4612:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4613:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4614:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4615:    my $uhome=&homeserver($uname,$udomain);
                   4616:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4617:    my @keyarray=();
1.800     albertel 4618:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4619:       next if ($key =~ /^error: 2 /);
1.800     albertel 4620:       push(@keyarray,&unescape($key));
1.407     www      4621:    }
                   4622:    return @keyarray;
1.318     matthew  4623: }
                   4624: 
1.319     matthew  4625: # --------------------------------------------------------------- currentdump
                   4626: sub currentdump {
1.328     matthew  4627:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4628:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4629:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4630:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4631:    my $uhome = &homeserver($sname,$sdom);
                   4632:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4633:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4634:    #
1.318     matthew  4635:    my %returnhash=();
1.319     matthew  4636:    #
                   4637:    if ($rep eq "unknown_cmd") { 
                   4638:        # an old lond will not know currentdump
                   4639:        # Do a dump and make it look like a currentdump
1.822     albertel 4640:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4641:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4642:        my %hash = @tmp;
                   4643:        @tmp=();
1.424     matthew  4644:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4645:    } else {
                   4646:        my @pairs=split(/\&/,$rep);
1.800     albertel 4647:        foreach my $pair (@pairs) {
                   4648:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4649:            my ($symb,$param) = split(/:/,$key);
                   4650:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4651:                                                         &thaw_unescape($value);
1.319     matthew  4652:        }
1.191     harris41 4653:    }
1.12      www      4654:    return %returnhash;
1.424     matthew  4655: }
                   4656: 
                   4657: sub convert_dump_to_currentdump{
                   4658:     my %hash = %{shift()};
                   4659:     my %returnhash;
                   4660:     # Code ripped from lond, essentially.  The only difference
                   4661:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4662:     # we might run in to problems with parameter names =~ /^v\./
                   4663:     while (my ($key,$value) = each(%hash)) {
                   4664:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4665: 	$symb  = &unescape($symb);
                   4666: 	$param = &unescape($param);
1.424     matthew  4667:         next if ($v eq 'version' || $symb eq 'keys');
                   4668:         next if (exists($returnhash{$symb}) &&
                   4669:                  exists($returnhash{$symb}->{$param}) &&
                   4670:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4671:         $returnhash{$symb}->{$param}=$value;
                   4672:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4673:     }
                   4674:     #
                   4675:     # Remove all of the keys in the hashes which keep track of
                   4676:     # the version of the parameter.
                   4677:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4678:         # use a foreach because we are going to delete from the hash.
                   4679:         foreach my $key (keys(%$param_hash)) {
                   4680:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4681:         }
                   4682:     }
                   4683:     return \%returnhash;
1.12      www      4684: }
                   4685: 
1.627     albertel 4686: # ------------------------------------------------------ critical inc interface
                   4687: 
                   4688: sub cinc {
                   4689:     return &inc(@_,'critical');
                   4690: }
                   4691: 
1.449     matthew  4692: # --------------------------------------------------------------- inc interface
                   4693: 
                   4694: sub inc {
1.627     albertel 4695:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4696:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4697:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4698:     my $uhome=&homeserver($uname,$udomain);
                   4699:     my $items='';
                   4700:     if (! ref($store)) {
                   4701:         # got a single value, so use that instead
                   4702:         $items = &escape($store).'=&';
                   4703:     } elsif (ref($store) eq 'SCALAR') {
                   4704:         $items = &escape($$store).'=&';        
                   4705:     } elsif (ref($store) eq 'ARRAY') {
                   4706:         $items = join('=&',map {&escape($_);} @{$store});
                   4707:     } elsif (ref($store) eq 'HASH') {
                   4708:         while (my($key,$value) = each(%{$store})) {
                   4709:             $items.= &escape($key).'='.&escape($value).'&';
                   4710:         }
                   4711:     }
                   4712:     $items=~s/\&$//;
1.627     albertel 4713:     if ($critical) {
                   4714: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4715:     } else {
                   4716: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4717:     }
1.449     matthew  4718: }
                   4719: 
1.12      www      4720: # --------------------------------------------------------------- put interface
                   4721: 
                   4722: sub put {
1.134     albertel 4723:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4724:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4725:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4726:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4727:    my $items='';
1.800     albertel 4728:    foreach my $item (keys(%$storehash)) {
                   4729:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4730:    }
1.12      www      4731:    $items=~s/\&$//;
1.134     albertel 4732:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4733: }
                   4734: 
1.631     albertel 4735: # ------------------------------------------------------------ newput interface
                   4736: 
                   4737: sub newput {
                   4738:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4739:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4740:    if (!$uname) { $uname=$env{'user.name'}; }
                   4741:    my $uhome=&homeserver($uname,$udomain);
                   4742:    my $items='';
                   4743:    foreach my $key (keys(%$storehash)) {
                   4744:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4745:    }
                   4746:    $items=~s/\&$//;
                   4747:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4748: }
                   4749: 
                   4750: # ---------------------------------------------------------  putstore interface
                   4751: 
1.524     raeburn  4752: sub putstore {
1.715     albertel 4753:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4754:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4755:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4756:    my $uhome=&homeserver($uname,$udomain);
                   4757:    my $items='';
1.715     albertel 4758:    foreach my $key (keys(%$storehash)) {
                   4759:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4760:    }
1.715     albertel 4761:    $items=~s/\&$//;
1.716     albertel 4762:    my $esc_symb=&escape($symb);
                   4763:    my $esc_v=&escape($version);
1.715     albertel 4764:    my $reply =
1.716     albertel 4765:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4766: 	      $uhome);
                   4767:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4768:        # gfall back to way things use to be done
1.715     albertel 4769:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4770: 			    $uname);
1.524     raeburn  4771:    }
1.715     albertel 4772:    return $reply;
                   4773: }
                   4774: 
                   4775: sub old_putstore {
1.716     albertel 4776:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4777:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4778:     if (!$uname) { $uname=$env{'user.name'}; }
                   4779:     my $uhome=&homeserver($uname,$udomain);
                   4780:     my %newstorehash;
1.800     albertel 4781:     foreach my $item (keys(%$storehash)) {
                   4782: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4783: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4784:     }
                   4785:     my $items='';
                   4786:     my %allitems = ();
1.800     albertel 4787:     foreach my $item (keys(%newstorehash)) {
                   4788: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4789: 	    my $key = $1.':keys:'.$2;
                   4790: 	    $allitems{$key} .= $3.':';
                   4791: 	}
1.800     albertel 4792: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4793:     }
1.800     albertel 4794:     foreach my $item (keys(%allitems)) {
                   4795: 	$allitems{$item} =~ s/\:$//;
                   4796: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4797:     }
                   4798:     $items=~s/\&$//;
                   4799:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4800: }
                   4801: 
1.47      www      4802: # ------------------------------------------------------ critical put interface
                   4803: 
                   4804: sub cput {
1.134     albertel 4805:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4806:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4807:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4808:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4809:    my $items='';
1.800     albertel 4810:    foreach my $item (keys(%$storehash)) {
                   4811:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4812:    }
1.47      www      4813:    $items=~s/\&$//;
1.134     albertel 4814:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4815: }
                   4816: 
                   4817: # -------------------------------------------------------------- eget interface
                   4818: 
                   4819: sub eget {
1.133     albertel 4820:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4821:    my $items='';
1.800     albertel 4822:    foreach my $item (@$storearr) {
                   4823:        $items.=&escape($item).'&';
1.191     harris41 4824:    }
1.12      www      4825:    $items=~s/\&$//;
1.620     albertel 4826:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4827:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4828:    my $uhome=&homeserver($uname,$udomain);
                   4829:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4830:    my @pairs=split(/\&/,$rep);
                   4831:    my %returnhash=();
1.42      www      4832:    my $i=0;
1.800     albertel 4833:    foreach my $item (@$storearr) {
                   4834:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4835:       $i++;
1.191     harris41 4836:    }
1.12      www      4837:    return %returnhash;
                   4838: }
                   4839: 
1.667     albertel 4840: # ------------------------------------------------------------ tmpput interface
                   4841: sub tmpput {
1.802     raeburn  4842:     my ($storehash,$server,$context)=@_;
1.667     albertel 4843:     my $items='';
1.800     albertel 4844:     foreach my $item (keys(%$storehash)) {
                   4845: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4846:     }
                   4847:     $items=~s/\&$//;
1.802     raeburn  4848:     if (defined($context)) {
                   4849:         $items .= ':'.&escape($context);
                   4850:     }
1.667     albertel 4851:     return &reply("tmpput:$items",$server);
                   4852: }
                   4853: 
                   4854: # ------------------------------------------------------------ tmpget interface
                   4855: sub tmpget {
1.688     albertel 4856:     my ($token,$server)=@_;
                   4857:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4858:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4859:     my %returnhash;
                   4860:     foreach my $item (split(/\&/,$rep)) {
                   4861: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4862:         next if ($key =~ /^error: 2 /);
1.667     albertel 4863: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4864:     }
                   4865:     return %returnhash;
                   4866: }
                   4867: 
1.688     albertel 4868: # ------------------------------------------------------------ tmpget interface
                   4869: sub tmpdel {
                   4870:     my ($token,$server)=@_;
                   4871:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4872:     return &reply("tmpdel:$token",$server);
                   4873: }
                   4874: 
1.765     albertel 4875: # -------------------------------------------------- portfolio access checking
                   4876: 
                   4877: sub portfolio_access {
1.766     albertel 4878:     my ($requrl) = @_;
1.765     albertel 4879:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4880:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4881:     if ($result) {
                   4882:         my %setters;
                   4883:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4884:             my ($startblock,$endblock) =
                   4885:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4886:             if ($startblock && $endblock) {
                   4887:                 return 'B';
                   4888:             }
                   4889:         } else {
                   4890:             my ($startblock,$endblock) =
                   4891:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4892:             if ($startblock && $endblock) {
                   4893:                 return 'B';
                   4894:             }
                   4895:         }
                   4896:     }
1.765     albertel 4897:     if ($result eq 'ok') {
1.766     albertel 4898:        return 'F';
1.765     albertel 4899:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4900:        return 'A';
1.765     albertel 4901:     }
1.766     albertel 4902:     return '';
1.765     albertel 4903: }
                   4904: 
                   4905: sub get_portfolio_access {
1.767     albertel 4906:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4907: 
                   4908:     if (!ref($access_hash)) {
                   4909: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4910: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4911: 						   $file_name);
                   4912: 	$access_hash = $access_controls{$file_name};
                   4913:     }
                   4914: 
1.765     albertel 4915:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4916:     my $now = time;
                   4917:     if (ref($access_hash) eq 'HASH') {
                   4918:         foreach my $key (keys(%{$access_hash})) {
                   4919:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4920:             if ($start > $now) {
                   4921:                 next;
                   4922:             }
                   4923:             if ($end && $end<$now) {
                   4924:                 next;
                   4925:             }
                   4926:             if ($scope eq 'public') {
                   4927:                 $public = $key;
                   4928:                 last;
                   4929:             } elsif ($scope eq 'guest') {
                   4930:                 $guest = $key;
                   4931:             } elsif ($scope eq 'domains') {
                   4932:                 push(@domains,$key);
                   4933:             } elsif ($scope eq 'users') {
                   4934:                 push(@users,$key);
                   4935:             } elsif ($scope eq 'course') {
                   4936:                 push(@courses,$key);
                   4937:             } elsif ($scope eq 'group') {
                   4938:                 push(@groups,$key);
                   4939:             }
                   4940:         }
                   4941:         if ($public) {
                   4942:             return 'ok';
                   4943:         }
                   4944:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4945:             if ($guest) {
                   4946:                 return $guest;
                   4947:             }
                   4948:         } else {
                   4949:             if (@domains > 0) {
                   4950:                 foreach my $domkey (@domains) {
                   4951:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4952:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4953:                             return 'ok';
                   4954:                         }
                   4955:                     }
                   4956:                 }
                   4957:             }
                   4958:             if (@users > 0) {
                   4959:                 foreach my $userkey (@users) {
1.865     raeburn  4960:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4961:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4962:                             if (ref($item) eq 'HASH') {
                   4963:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4964:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4965:                                     return 'ok';
                   4966:                                 }
                   4967:                             }
                   4968:                         }
                   4969:                     } 
1.765     albertel 4970:                 }
                   4971:             }
                   4972:             my %roleshash;
                   4973:             my @courses_and_groups = @courses;
                   4974:             push(@courses_and_groups,@groups); 
                   4975:             if (@courses_and_groups > 0) {
                   4976:                 my (%allgroups,%allroles); 
                   4977:                 my ($start,$end,$role,$sec,$group);
                   4978:                 foreach my $envkey (%env) {
1.1056.4.1  raeburn  4979:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4980:                         my $cid = $2.'_'.$3; 
                   4981:                         if ($1 eq 'gr') {
                   4982:                             $group = $4;
                   4983:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4984:                         } else {
                   4985:                             if ($4 eq '') {
                   4986:                                 $sec = 'none';
                   4987:                             } else {
                   4988:                                 $sec = $4;
                   4989:                             }
                   4990:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4991:                         }
1.811     albertel 4992:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4993:                         my $cid = $2.'_'.$3;
                   4994:                         if ($4 eq '') {
                   4995:                             $sec = 'none';
                   4996:                         } else {
                   4997:                             $sec = $4;
                   4998:                         }
                   4999:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5000:                     }
                   5001:                 }
                   5002:                 if (keys(%allroles) == 0) {
                   5003:                     return;
                   5004:                 }
                   5005:                 foreach my $key (@courses_and_groups) {
                   5006:                     my %content = %{$$access_hash{$key}};
                   5007:                     my $cnum = $content{'number'};
                   5008:                     my $cdom = $content{'domain'};
                   5009:                     my $cid = $cdom.'_'.$cnum;
                   5010:                     if (!exists($allroles{$cid})) {
                   5011:                         next;
                   5012:                     }    
                   5013:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5014:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5015:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5016:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5017:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5018:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5019:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5020:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5021:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5022:                                         if (grep/^all$/,@sections) {
                   5023:                                             return 'ok';
                   5024:                                         } else {
                   5025:                                             if (grep/^$sec$/,@sections) {
                   5026:                                                 return 'ok';
                   5027:                                             }
                   5028:                                         }
                   5029:                                     }
                   5030:                                 }
                   5031:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5032:                                     if (grep/^none$/,@groups) {
                   5033:                                         return 'ok';
                   5034:                                     }
                   5035:                                 } else {
                   5036:                                     if (grep/^all$/,@groups) {
                   5037:                                         return 'ok';
                   5038:                                     } 
                   5039:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5040:                                         if (grep/^$group$/,@groups) {
                   5041:                                             return 'ok';
                   5042:                                         }
                   5043:                                     }
                   5044:                                 } 
                   5045:                             }
                   5046:                         }
                   5047:                     }
                   5048:                 }
                   5049:             }
                   5050:             if ($guest) {
                   5051:                 return $guest;
                   5052:             }
                   5053:         }
                   5054:     }
                   5055:     return;
                   5056: }
                   5057: 
                   5058: sub course_group_datechecker {
                   5059:     my ($dates,$now,$status) = @_;
                   5060:     my ($start,$end) = split(/\./,$dates);
                   5061:     if (!$start && !$end) {
                   5062:         return 'ok';
                   5063:     }
                   5064:     if (grep/^active$/,@{$status}) {
                   5065:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5066:             return 'ok';
                   5067:         }
                   5068:     }
                   5069:     if (grep/^previous$/,@{$status}) {
                   5070:         if ($end > $now ) {
                   5071:             return 'ok';
                   5072:         }
                   5073:     }
                   5074:     if (grep/^future$/,@{$status}) {
                   5075:         if ($start > $now) {
                   5076:             return 'ok';
                   5077:         }
                   5078:     }
                   5079:     return; 
                   5080: }
                   5081: 
                   5082: sub parse_portfolio_url {
                   5083:     my ($url) = @_;
                   5084: 
                   5085:     my ($type,$udom,$unum,$group,$file_name);
                   5086:     
1.823     albertel 5087:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5088: 	$type = 1;
                   5089:         $udom = $1;
                   5090:         $unum = $2;
                   5091:         $file_name = $3;
1.823     albertel 5092:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5093: 	$type = 2;
                   5094:         $udom = $1;
                   5095:         $unum = $2;
                   5096:         $group = $3;
                   5097:         $file_name = $3.'/'.$4;
                   5098:     }
                   5099:     if (wantarray) {
                   5100: 	return ($type,$udom,$unum,$file_name,$group);
                   5101:     }
                   5102:     return $type;
                   5103: }
                   5104: 
                   5105: sub is_portfolio_url {
                   5106:     my ($url) = @_;
                   5107:     return scalar(&parse_portfolio_url($url));
                   5108: }
                   5109: 
1.798     raeburn  5110: sub is_portfolio_file {
                   5111:     my ($file) = @_;
1.820     raeburn  5112:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5113:         return 1;
                   5114:     }
                   5115:     return;
                   5116: }
                   5117: 
1.976     raeburn  5118: sub usertools_access {
1.1056.4.9  raeburn  5119:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985     raeburn  5120:     my ($access,%tools);
                   5121:     if ($context eq '') {
                   5122:         $context = 'tools';
                   5123:     }
                   5124:     if ($context eq 'requestcourses') {
                   5125:         %tools = (
                   5126:                       official   => 1,
                   5127:                       unofficial => 1,
1.1006    raeburn  5128:                       community  => 1,
1.985     raeburn  5129:                  );
                   5130:     } else {
                   5131:         %tools = (
                   5132:                       aboutme   => 1,
                   5133:                       blog      => 1,
                   5134:                       portfolio => 1,
                   5135:                  );
                   5136:     }
1.976     raeburn  5137:     return if (!defined($tools{$tool}));
                   5138: 
                   5139:     if ((!defined($udom)) || (!defined($uname))) {
                   5140:         $udom = $env{'user.domain'};
                   5141:         $uname = $env{'user.name'};
                   5142:     }
                   5143: 
1.978     raeburn  5144:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5145:         if ($action ne 'reload') {
1.985     raeburn  5146:             if ($context eq 'requestcourses') {
                   5147:                 return $env{'environment.canrequest.'.$tool};
                   5148:             } else {
                   5149:                 return $env{'environment.availabletools.'.$tool};
                   5150:             }
                   5151:         }
1.976     raeburn  5152:     }
                   5153: 
                   5154:     my ($toolstatus,$inststatus);
                   5155: 
1.985     raeburn  5156:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5157:          ($action ne 'reload')) {
                   5158:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5159:         $inststatus = $env{'environment.inststatus'};
                   5160:     } else {
1.1056.4.9  raeburn  5161:         if (ref($userenvref) eq 'HASH') {
                   5162:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5163:             $inststatus = $userenvref->{'inststatus'};
                   5164:         } else {
                   5165:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5166:             $toolstatus = $userenv{$context.'.'.$tool};
                   5167:             $inststatus = $userenv{'inststatus'};
                   5168:         }
1.976     raeburn  5169:     }
                   5170: 
                   5171:     if ($toolstatus ne '') {
                   5172:         if ($toolstatus) {
                   5173:             $access = 1;
                   5174:         } else {
                   5175:             $access = 0;
                   5176:         }
                   5177:         return $access;
                   5178:     }
                   5179: 
1.1056.4.9  raeburn  5180:     my ($is_adv,%domdef);
                   5181:     if (ref($is_advref) eq 'HASH') {
                   5182:         $is_adv = $is_advref->{'is_adv'};
                   5183:     } else {
                   5184:         $is_adv = &is_advanced_user($udom,$uname);
                   5185:     }
                   5186:     if (ref($domdefref) eq 'HASH') {
                   5187:         %domdef = %{$domdefref};
                   5188:     } else {
                   5189:         %domdef = &get_domain_defaults($udom);
                   5190:     }
1.976     raeburn  5191:     if (ref($domdef{$tool}) eq 'HASH') {
                   5192:         if ($is_adv) {
                   5193:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5194:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5195:                     $access = 1;
                   5196:                 } else {
                   5197:                     $access = 0;
                   5198:                 }
                   5199:                 return $access;
                   5200:             }
                   5201:         }
                   5202:         if ($inststatus ne '') {
                   5203:             my ($hasaccess,$hasnoaccess);
                   5204:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5205:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5206:                     if ($domdef{$tool}{$affiliation}) {
                   5207:                         $hasaccess = 1;
                   5208:                     } else {
                   5209:                         $hasnoaccess = 1;
                   5210:                     }
                   5211:                 }
                   5212:             }
                   5213:             if ($hasaccess || $hasnoaccess) {
                   5214:                 if ($hasaccess) {
                   5215:                     $access = 1;
                   5216:                 } elsif ($hasnoaccess) {
                   5217:                     $access = 0; 
                   5218:                 }
                   5219:                 return $access;
                   5220:             }
                   5221:         } else {
                   5222:             if ($domdef{$tool}{'default'} ne '') {
                   5223:                 if ($domdef{$tool}{'default'}) {
                   5224:                     $access = 1;
                   5225:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5226:                     $access = 0;
                   5227:                 }
                   5228:                 return $access;
                   5229:             }
                   5230:         }
                   5231:     } else {
1.985     raeburn  5232:         if ($context eq 'tools') {
                   5233:             $access = 1;
                   5234:         } else {
                   5235:             $access = 0;
                   5236:         }
1.976     raeburn  5237:         return $access;
                   5238:     }
                   5239: }
                   5240: 
1.1050    raeburn  5241: sub is_course_owner {
                   5242:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5243:     if (($udom eq '') || ($uname eq '')) {
                   5244:         $udom = $env{'user.domain'};
                   5245:         $uname = $env{'user.name'};
                   5246:     }
                   5247:     unless (($udom eq '') || ($uname eq '')) {
                   5248:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5249:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5250:                 return 1;
                   5251:             } else {
                   5252:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5253:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5254:                     return 1;
                   5255:                 }
                   5256:             }
                   5257:         }
                   5258:     }
                   5259:     return;
                   5260: }
                   5261: 
1.976     raeburn  5262: sub is_advanced_user {
                   5263:     my ($udom,$uname) = @_;
1.1056.4.10  raeburn  5264:     if ($udom ne '' && $uname ne '') {
                   5265:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5266:             return $env{'user.adv'};
                   5267:         }
                   5268:     }
1.976     raeburn  5269:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5270:     my %allroles;
                   5271:     my $is_adv;
                   5272:     foreach my $role (keys(%roleshash)) {
                   5273:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5274:         my $area = '/'.$tdomain.'/'.$trest;
                   5275:         if ($sec ne '') {
                   5276:             $area .= '/'.$sec;
                   5277:         }
                   5278:         if (($area ne '') && ($trole ne '')) {
                   5279:             my $spec=$trole.'.'.$area;
                   5280:             if ($trole =~ /^cr\//) {
                   5281:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5282:             } elsif ($trole ne 'gr') {
                   5283:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5284:             }
                   5285:         }
                   5286:     }
                   5287:     foreach my $role (keys(%allroles)) {
                   5288:         last if ($is_adv);
                   5289:         foreach my $item (split(/:/,$allroles{$role})) {
                   5290:             if ($item ne '') {
                   5291:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5292:                 if ($privilege eq 'adv') {
                   5293:                     $is_adv = 1;
                   5294:                     last;
                   5295:                 }
                   5296:             }
                   5297:         }
                   5298:     }
                   5299:     return $is_adv;
                   5300: }
1.798     raeburn  5301: 
1.1035    raeburn  5302: sub check_can_request {
1.1036    raeburn  5303:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5304:     my $canreq = 0;
                   5305:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5306:     my @options = ('approval','validate','autolimit');
                   5307:     my $optregex = join('|',@options);
                   5308:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5309:         foreach my $type (@{$types}) {
                   5310:             if (&usertools_access($env{'user.name'},
                   5311:                                   $env{'user.domain'},
                   5312:                                   $type,undef,'requestcourses')) {
                   5313:                 $canreq ++;
1.1036    raeburn  5314:                 if (ref($request_domains) eq 'HASH') {
                   5315:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5316:                 }
1.1035    raeburn  5317:                 if ($dom eq $env{'user.domain'}) {
                   5318:                     $can_request->{$type} = 1;
                   5319:                 }
                   5320:             }
                   5321:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5322:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5323:                 if (@curr > 0) {
1.1036    raeburn  5324:                     foreach my $item (@curr) {
                   5325:                         if (ref($request_domains) eq 'HASH') {
                   5326:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5327:                             if ($otherdom ne '') {
                   5328:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5329:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5330:                                         push(@{$request_domains->{$type}},$otherdom);
                   5331:                                     }
                   5332:                                 } else {
                   5333:                                     push(@{$request_domains->{$type}},$otherdom);
                   5334:                                 }
                   5335:                             }
                   5336:                         }
                   5337:                     }
                   5338:                     unless($dom eq $env{'user.domain'}) {
                   5339:                         $canreq ++;
1.1035    raeburn  5340:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5341:                             $can_request->{$type} = 1;
                   5342:                         }
                   5343:                     }
                   5344:                 }
                   5345:             }
                   5346:         }
                   5347:     }
                   5348:     return $canreq;
                   5349: }
                   5350: 
1.341     www      5351: # ---------------------------------------------- Custom access rule evaluation
                   5352: 
                   5353: sub customaccess {
                   5354:     my ($priv,$uri)=@_;
1.807     albertel 5355:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5356:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5357:     $udom = &LONCAPA::clean_domain($udom);
                   5358:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5359:     my $access=0;
1.800     albertel 5360:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5361: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5362: 	if ($type eq 'user') {
                   5363: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5364: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5365: 		if ($tdom) {
                   5366: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5367: 		}
1.896     albertel 5368: 		if ($tuname) {
                   5369: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5370: 		}
                   5371: 		$access=($effect eq 'allow');
                   5372: 		last;
                   5373: 	    }
                   5374: 	} else {
                   5375: 	    if ($role) {
                   5376: 		if ($role ne $urole) { next; }
                   5377: 	    }
                   5378: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5379: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5380: 		if ($tdom) {
                   5381: 		    if ($tdom ne $udom) { next; }
                   5382: 		}
                   5383: 		if ($tcrs) {
                   5384: 		    if ($tcrs ne $ucrs) { next; }
                   5385: 		}
                   5386: 		if ($tsec) {
                   5387: 		    if ($tsec ne $usec) { next; }
                   5388: 		}
                   5389: 		$access=($effect eq 'allow');
                   5390: 		last;
                   5391: 	    }
                   5392: 	    if ($realm eq '' && $role eq '') {
                   5393: 		$access=($effect eq 'allow');
                   5394: 	    }
1.402     bowersj2 5395: 	}
1.341     www      5396:     }
                   5397:     return $access;
                   5398: }
                   5399: 
1.103     harris41 5400: # ------------------------------------------------- Check for a user privilege
1.12      www      5401: 
                   5402: sub allowed {
1.810     raeburn  5403:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5404:     my $ver_orguri=$uri;
1.439     www      5405:     $uri=&deversion($uri);
1.152     www      5406:     my $orguri=$uri;
1.52      www      5407:     $uri=&declutter($uri);
1.809     raeburn  5408: 
1.810     raeburn  5409:     if ($priv eq 'evb') {
                   5410: # Evade communication block restrictions for specified role in a course
                   5411:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5412:             return $1;
                   5413:         } else {
                   5414:             return;
                   5415:         }
                   5416:     }
                   5417: 
1.620     albertel 5418:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5419: # Free bre access to adm and meta resources
1.775     albertel 5420:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5421: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5422: 	&& ($priv eq 'bre')) {
1.14      www      5423: 	return 'F';
1.159     www      5424:     }
                   5425: 
1.545     banghart 5426: # Free bre access to user's own portfolio contents
1.714     raeburn  5427:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5428:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5429: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5430:         my %setters;
                   5431:         my ($startblock,$endblock) = 
                   5432:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5433:         if ($startblock && $endblock) {
                   5434:             return 'B';
                   5435:         } else {
                   5436:             return 'F';
                   5437:         }
1.545     banghart 5438:     }
                   5439: 
1.762     raeburn  5440: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5441:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5442:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5443:         if (exists($env{'request.course.id'})) {
                   5444:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5445:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5446:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5447:                 my $courseprivid=$env{'request.course.id'};
                   5448:                 $courseprivid=~s/\_/\//;
                   5449:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5450:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5451:                     return $1; 
1.762     raeburn  5452:                 } else {
                   5453:                     if ($env{'request.course.sec'}) {
                   5454:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5455:                     }
                   5456:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5457:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5458:                         return $2;
                   5459:                     }
1.714     raeburn  5460:                 }
                   5461:             }
                   5462:         }
                   5463:     }
                   5464: 
1.159     www      5465: # Free bre to public access
                   5466: 
                   5467:     if ($priv eq 'bre') {
1.238     www      5468:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5469: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5470:            return 'F'; 
                   5471:         }
1.238     www      5472:         if ($copyright eq 'priv') {
                   5473:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5474: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5475: 		return '';
                   5476:             }
                   5477:         }
                   5478:         if ($copyright eq 'domain') {
                   5479:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5480: 	    unless (($env{'user.domain'} eq $1) ||
                   5481:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5482: 		return '';
                   5483:             }
1.262     matthew  5484:         }
1.620     albertel 5485:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5486:             # Library role, so allow browsing of resources in this domain.
                   5487:             return 'F';
1.238     www      5488:         }
1.341     www      5489:         if ($copyright eq 'custom') {
                   5490: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5491:         }
1.14      www      5492:     }
1.264     matthew  5493:     # Domain coordinator is trying to create a course
1.620     albertel 5494:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5495:         # uri is the requested domain in this case.
                   5496:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5497:         # a role of dc for the domain in question.
1.620     albertel 5498:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5499:     }
1.29      www      5500: 
1.52      www      5501:     my $thisallowed='';
                   5502:     my $statecond=0;
                   5503:     my $courseprivid='';
                   5504: 
1.1039    raeburn  5505:     my $ownaccess;
1.1043    raeburn  5506:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5507:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5508:         if ($uri eq '') {
                   5509:             $ownaccess = 1;
                   5510:         } else {
                   5511:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5512:                 my $udom = $env{'user.domain'};
                   5513:                 my $uname = $env{'user.name'};
                   5514:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5515:                     $ownaccess = 1;
1.1040    raeburn  5516:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5517:                     unless ($uri =~ m{\.\./}) {
                   5518:                         $ownaccess = 1;
                   5519:                     }
                   5520:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5521:                     my $now = time;
                   5522:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5523:                         my $adom = $1;
                   5524:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5525:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5526:                                 my ($start,$end) = split('.',$env{$key});
                   5527:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5528:                                     $ownaccess = 1;
                   5529:                                     last;
                   5530:                                 }
                   5531:                             }
                   5532:                         }
                   5533:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5534:                         my $adom = $1;
                   5535:                         my $aname = $2;
1.1042    raeburn  5536:                         foreach my $role ('ca','aa') { 
                   5537:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5538:                                 my ($start,$end) =
                   5539:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5540:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5541:                                     $ownaccess = 1;
                   5542:                                     last;
                   5543:                                 }
1.1039    raeburn  5544:                             }
                   5545:                         }
                   5546:                     }
                   5547:                 }
                   5548:             }
                   5549:         }
                   5550:     }
                   5551: 
1.52      www      5552: # Course
                   5553: 
1.620     albertel 5554:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5555:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5556:             $thisallowed.=$1;
                   5557:         }
1.52      www      5558:     }
1.29      www      5559: 
1.52      www      5560: # Domain
                   5561: 
1.620     albertel 5562:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5563:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5564:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5565:             $thisallowed.=$1;
                   5566:         }
1.12      www      5567:     }
1.52      www      5568: 
                   5569: # Course: uri itself is a course
1.66      www      5570:     my $courseuri=$uri;
                   5571:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5572:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5573: 
1.620     albertel 5574:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5575:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5576:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5577:             $thisallowed.=$1;
                   5578:         }
1.12      www      5579:     }
1.29      www      5580: 
1.665     albertel 5581: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5582: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5583:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5584: 	$thisallowed='';
1.671     raeburn  5585:         my ($match)=&is_on_map($uri);
                   5586:         if ($match) {
                   5587:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5588:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5589:                 $thisallowed.=$1;
                   5590:             }
                   5591:         } else {
1.705     albertel 5592:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5593:             if ($refuri) {
                   5594:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5595:                     $thisallowed='F';
1.671     raeburn  5596:                 } else {
                   5597:                     $refuri=&declutter($refuri);
                   5598:                     my ($match) = &is_on_map($refuri);
                   5599:                     if ($match) {
                   5600:                         $thisallowed='F';
                   5601:                     }
1.669     raeburn  5602:                 }
1.671     raeburn  5603:             }
                   5604:         }
1.314     www      5605:     }
1.492     albertel 5606: 
1.766     albertel 5607:     if ($priv eq 'bre'
                   5608: 	&& $thisallowed ne 'F' 
                   5609: 	&& $thisallowed ne '2'
                   5610: 	&& &is_portfolio_url($uri)) {
                   5611: 	$thisallowed = &portfolio_access($uri);
                   5612:     }
                   5613:     
1.52      www      5614: # Full access at system, domain or course-wide level? Exit.
1.29      www      5615:     if ($thisallowed=~/F/) {
                   5616: 	return 'F';
                   5617:     }
                   5618: 
1.52      www      5619: # If this is generating or modifying users, exit with special codes
1.29      www      5620: 
1.643     www      5621:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5622: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5623: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5624: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5625: 	    unless ($auname) { return $thisallowed; }
                   5626: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5627: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5628: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5629: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5630: 	}
1.52      www      5631: 	return $thisallowed;
                   5632:     }
                   5633: #
1.103     harris41 5634: # Gathered so far: system, domain and course wide privileges
1.52      www      5635: #
                   5636: # Course: See if uri or referer is an individual resource that is part of 
                   5637: # the course
                   5638: 
1.620     albertel 5639:     if ($env{'request.course.id'}) {
1.232     www      5640: 
1.620     albertel 5641:        $courseprivid=$env{'request.course.id'};
                   5642:        if ($env{'request.course.sec'}) {
                   5643:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5644:        }
                   5645:        $courseprivid=~s/\_/\//;
                   5646:        my $checkreferer=1;
1.232     www      5647:        my ($match,$cond)=&is_on_map($uri);
                   5648:        if ($match) {
                   5649:            $statecond=$cond;
1.620     albertel 5650:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5651:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5652:                $thisallowed.=$1;
                   5653:                $checkreferer=0;
                   5654:            }
1.29      www      5655:        }
1.83      www      5656:        
1.148     www      5657:        if ($checkreferer) {
1.620     albertel 5658: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5659:             unless ($refuri) {
1.800     albertel 5660:                 foreach my $key (keys(%env)) {
                   5661: 		    if ($key=~/^httpref\..*\*/) {
                   5662: 			my $pattern=$key;
1.156     www      5663:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5664:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5665:                         $pattern=~s/\//\\\//g;
1.152     www      5666:                         if ($orguri=~/$pattern/) {
1.800     albertel 5667: 			    $refuri=$env{$key};
1.148     www      5668:                         }
                   5669:                     }
1.191     harris41 5670:                 }
1.148     www      5671:             }
1.232     www      5672: 
1.148     www      5673:          if ($refuri) { 
1.152     www      5674: 	  $refuri=&declutter($refuri);
1.232     www      5675:           my ($match,$cond)=&is_on_map($refuri);
                   5676:             if ($match) {
                   5677:               my $refstatecond=$cond;
1.620     albertel 5678:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5679:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5680:                   $thisallowed.=$1;
1.53      www      5681:                   $uri=$refuri;
                   5682:                   $statecond=$refstatecond;
1.52      www      5683:               }
                   5684:           }
1.148     www      5685:         }
1.29      www      5686:        }
1.52      www      5687:    }
1.29      www      5688: 
1.52      www      5689: #
1.103     harris41 5690: # Gathered now: all privileges that could apply, and condition number
1.52      www      5691: # 
                   5692: #
                   5693: # Full or no access?
                   5694: #
1.29      www      5695: 
1.52      www      5696:     if ($thisallowed=~/F/) {
                   5697: 	return 'F';
                   5698:     }
1.29      www      5699: 
1.52      www      5700:     unless ($thisallowed) {
                   5701:         return '';
                   5702:     }
1.29      www      5703: 
1.52      www      5704: # Restrictions exist, deal with them
                   5705: #
                   5706: #   C:according to course preferences
                   5707: #   R:according to resource settings
                   5708: #   L:unless locked
                   5709: #   X:according to user session state
                   5710: #
                   5711: 
                   5712: # Possibly locked functionality, check all courses
1.54      www      5713: # Locks might take effect only after 10 minutes cache expiration for other
                   5714: # courses, and 2 minutes for current course
1.52      www      5715: 
                   5716:     my $envkey;
                   5717:     if ($thisallowed=~/L/) {
1.1000    raeburn  5718:         foreach $envkey (keys(%env)) {
1.54      www      5719:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5720:                my $courseid=$2;
                   5721:                my $roleid=$1.'.'.$2;
1.92      www      5722:                $courseid=~s/^\///;
1.54      www      5723:                my $expiretime=600;
1.620     albertel 5724:                if ($env{'request.role'} eq $roleid) {
1.54      www      5725: 		  $expiretime=120;
                   5726:                }
                   5727: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5728:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5729:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5730: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5731:                }
1.620     albertel 5732:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5733:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5734: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5735:                        &log($env{'user.domain'},$env{'user.name'},
                   5736:                             $env{'user.home'},
1.57      www      5737:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5738:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5739:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5740: 		       return '';
                   5741:                    }
                   5742:                }
1.620     albertel 5743:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5744:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5745: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5746:                        &log($env{'user.domain'},$env{'user.name'},
                   5747:                             $env{'user.home'},
1.57      www      5748:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5749:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5750:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5751: 		       return '';
                   5752:                    }
                   5753:                }
                   5754: 	   }
1.29      www      5755:        }
1.52      www      5756:     }
                   5757:    
                   5758: #
                   5759: # Rest of the restrictions depend on selected course
                   5760: #
                   5761: 
1.620     albertel 5762:     unless ($env{'request.course.id'}) {
1.766     albertel 5763: 	if ($thisallowed eq 'A') {
                   5764: 	    return 'A';
1.814     raeburn  5765:         } elsif ($thisallowed eq 'B') {
                   5766:             return 'B';
1.766     albertel 5767: 	} else {
                   5768: 	    return '1';
                   5769: 	}
1.52      www      5770:     }
1.29      www      5771: 
1.52      www      5772: #
                   5773: # Now user is definitely in a course
                   5774: #
1.53      www      5775: 
                   5776: 
                   5777: # Course preferences
                   5778: 
                   5779:    if ($thisallowed=~/C/) {
1.620     albertel 5780:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5781:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5782:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5783: 	   =~/\Q$rolecode\E/) {
1.1056.4.22  raeburn  5784:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5785: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5786: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5787: 			$env{'request.course.id'});
                   5788: 	   }
1.237     www      5789:            return '';
                   5790:        }
                   5791: 
1.620     albertel 5792:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5793: 	   =~/\Q$unamedom\E/) {
1.1056.4.22  raeburn  5794:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5795: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5796: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5797: 			$env{'request.course.id'});
                   5798: 	   }
1.54      www      5799:            return '';
                   5800:        }
1.53      www      5801:    }
                   5802: 
                   5803: # Resource preferences
                   5804: 
                   5805:    if ($thisallowed=~/R/) {
1.620     albertel 5806:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5807:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1056.4.22  raeburn  5808:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5809: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5810: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5811: 	   }
                   5812: 	   return '';
1.54      www      5813:        }
1.53      www      5814:    }
1.30      www      5815: 
1.246     www      5816: # Restricted by state or randomout?
1.30      www      5817: 
1.52      www      5818:    if ($thisallowed=~/X/) {
1.620     albertel 5819:       if ($env{'acc.randomout'}) {
1.579     albertel 5820: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5821:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5822:             return ''; 
                   5823:          }
1.247     www      5824:       }
                   5825:       if (&condval($statecond)) {
1.52      www      5826: 	 return '2';
                   5827:       } else {
                   5828:          return '';
                   5829:       }
                   5830:    }
1.30      www      5831: 
1.766     albertel 5832:     if ($thisallowed eq 'A') {
                   5833: 	return 'A';
1.814     raeburn  5834:     } elsif ($thisallowed eq 'B') {
                   5835:         return 'B';
1.766     albertel 5836:     }
1.52      www      5837:    return 'F';
1.232     www      5838: }
                   5839: 
1.710     albertel 5840: sub split_uri_for_cond {
                   5841:     my $uri=&deversion(&declutter(shift));
                   5842:     my @uriparts=split(/\//,$uri);
                   5843:     my $filename=pop(@uriparts);
                   5844:     my $pathname=join('/',@uriparts);
                   5845:     return ($pathname,$filename);
                   5846: }
1.232     www      5847: # --------------------------------------------------- Is a resource on the map?
                   5848: 
                   5849: sub is_on_map {
1.710     albertel 5850:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5851:     #Trying to find the conditional for the file
1.620     albertel 5852:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5853: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5854:     if ($match) {
1.289     bowersj2 5855: 	return (1,$1);
                   5856:     } else {
1.434     www      5857: 	return (0,0);
1.289     bowersj2 5858:     }
1.12      www      5859: }
                   5860: 
1.427     www      5861: # --------------------------------------------------------- Get symb from alias
                   5862: 
                   5863: sub get_symb_from_alias {
                   5864:     my $symb=shift;
                   5865:     my ($map,$resid,$url)=&decode_symb($symb);
                   5866: # Already is a symb
                   5867:     if ($url) { return $symb; }
                   5868: # Must be an alias
                   5869:     my $aliassymb='';
                   5870:     my %bighash;
1.620     albertel 5871:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5872:                             &GDBM_READER(),0640)) {
                   5873:         my $rid=$bighash{'mapalias_'.$symb};
                   5874: 	if ($rid) {
                   5875: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5876: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5877: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5878: 	}
                   5879:         untie %bighash;
                   5880:     }
                   5881:     return $aliassymb;
                   5882: }
                   5883: 
1.12      www      5884: # ----------------------------------------------------------------- Define Role
                   5885: 
                   5886: sub definerole {
                   5887:   if (allowed('mcr','/')) {
                   5888:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5889:     foreach my $role (split(':',$sysrole)) {
                   5890: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5891:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5892:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5893: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5894:                return "refused:s:$crole&$cqual"; 
                   5895:             }
                   5896:         }
1.191     harris41 5897:     }
1.800     albertel 5898:     foreach my $role (split(':',$domrole)) {
                   5899: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5900:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5901:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5902: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5903:                return "refused:d:$crole&$cqual"; 
                   5904:             }
                   5905:         }
1.191     harris41 5906:     }
1.800     albertel 5907:     foreach my $role (split(':',$courole)) {
                   5908: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5909:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5910:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5911: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5912:                return "refused:c:$crole&$cqual"; 
                   5913:             }
                   5914:         }
1.191     harris41 5915:     }
1.620     albertel 5916:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5917:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5918: 	        "rolesdef_$rolename=".
                   5919:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5920:     return reply($command,$env{'user.home'});
1.12      www      5921:   } else {
                   5922:     return 'refused';
                   5923:   }
1.105     harris41 5924: }
                   5925: 
                   5926: # ---------------- Make a metadata query against the network of library servers
                   5927: 
                   5928: sub metadata_query {
1.244     matthew  5929:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5930:     my %rhash;
1.845     albertel 5931:     my %libserv = &all_library();
1.244     matthew  5932:     my @server_list = (defined($server_array) ? @$server_array
                   5933:                                               : keys(%libserv) );
                   5934:     for my $server (@server_list) {
1.118     harris41 5935: 	unless ($custom or $customshow) {
                   5936: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5937: 	    $rhash{$server}=$reply;
                   5938: 	}
                   5939: 	else {
                   5940: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5941: 			     &escape($custom).':'.&escape($customshow),
                   5942: 			     $server);
                   5943: 	    $rhash{$server}=$reply;
                   5944: 	}
1.112     harris41 5945:     }
1.118     harris41 5946:     return \%rhash;
1.240     www      5947: }
                   5948: 
                   5949: # ----------------------------------------- Send log queries and wait for reply
                   5950: 
                   5951: sub log_query {
                   5952:     my ($uname,$udom,$query,%filters)=@_;
                   5953:     my $uhome=&homeserver($uname,$udom);
                   5954:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5955:     my $uhost=&hostname($uhome);
1.800     albertel 5956:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5957:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5958:                        $uhome);
1.479     albertel 5959:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5960:     return get_query_reply($queryid);
                   5961: }
                   5962: 
1.818     raeburn  5963: # -------------------------- Update MySQL table for portfolio file
                   5964: 
                   5965: sub update_portfolio_table {
1.821     raeburn  5966:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5967:     if ($group ne '') {
                   5968:         $file_name =~s /^\Q$group\E//;
                   5969:     }
1.818     raeburn  5970:     my $homeserver = &homeserver($uname,$udom);
                   5971:     my $queryid=
1.821     raeburn  5972:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5973:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5974:     my $reply = &get_query_reply($queryid);
                   5975:     return $reply;
                   5976: }
                   5977: 
1.899     raeburn  5978: # -------------------------- Update MySQL allusers table
                   5979: 
                   5980: sub update_allusers_table {
                   5981:     my ($uname,$udom,$names) = @_;
                   5982:     my $homeserver = &homeserver($uname,$udom);
                   5983:     my $queryid=
                   5984:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5985:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5986:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5987:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5988:                'generation='.&escape($names->{'generation'}).'%%'.
                   5989:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5990:                'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4  raeburn  5991:     return;
1.899     raeburn  5992: }
                   5993: 
1.508     raeburn  5994: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5995: 
                   5996: sub fetch_enrollment_query {
1.511     raeburn  5997:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5998:     my $homeserver;
1.547     raeburn  5999:     my $maxtries = 1;
1.508     raeburn  6000:     if ($context eq 'automated') {
                   6001:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6002:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6003:     } else {
                   6004:         $homeserver = &homeserver($cnum,$dom);
                   6005:     }
1.838     albertel 6006:     my $host=&hostname($homeserver);
1.506     raeburn  6007:     my $cmd = '';
1.1000    raeburn  6008:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6009:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6010:     }
                   6011:     $cmd =~ s/%%$//;
                   6012:     $cmd = &escape($cmd);
                   6013:     my $query = 'fetchenrollment';
1.620     albertel 6014:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6015:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6016:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6017:         return 'error: '.$queryid;
                   6018:     }
1.506     raeburn  6019:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6020:     my $tries = 1;
                   6021:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6022:         $reply = &get_query_reply($queryid);
                   6023:         $tries ++;
                   6024:     }
1.526     raeburn  6025:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6026:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6027:     } else {
1.901     albertel 6028:         my @responses = split(/:/,$reply);
1.515     raeburn  6029:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6030:             foreach my $line (@responses) {
                   6031:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6032:                 $$replyref{$key} = $value;
                   6033:             }
                   6034:         } else {
1.506     raeburn  6035:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 6036:             foreach my $line (@responses) {
                   6037:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6038:                 $$replyref{$key} = $value;
                   6039:                 if ($value > 0) {
1.800     albertel 6040:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6041:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6042:                         my $destname = $pathname.'/'.$filename;
                   6043:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6044:                         if ($xml_classlist =~ /^error/) {
                   6045:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6046:                         } else {
1.506     raeburn  6047:                             if ( open(FILE,">$destname") ) {
                   6048:                                 print FILE &unescape($xml_classlist);
                   6049:                                 close(FILE);
1.526     raeburn  6050:                             } else {
                   6051:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6052:                             }
                   6053:                         }
                   6054:                     }
                   6055:                 }
                   6056:             }
                   6057:         }
                   6058:         return 'ok';
                   6059:     }
                   6060:     return 'error';
                   6061: }
                   6062: 
1.242     www      6063: sub get_query_reply {
                   6064:     my $queryid=shift;
1.240     www      6065:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   6066:     my $reply='';
                   6067:     for (1..100) {
                   6068: 	sleep 2;
                   6069:         if (-e $replyfile.'.end') {
1.448     albertel 6070: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6071: 		$reply = join('',<$fh>);
                   6072: 		close($fh);
1.240     www      6073: 	   } else { return 'error: reply_file_error'; }
1.242     www      6074:            return &unescape($reply);
                   6075: 	}
1.240     www      6076:     }
1.242     www      6077:     return 'timeout:'.$queryid;
1.240     www      6078: }
                   6079: 
                   6080: sub courselog_query {
1.241     www      6081: #
                   6082: # possible filters:
                   6083: # url: url or symb
                   6084: # username
                   6085: # domain
                   6086: # action: view, submit, grade
                   6087: # start: timestamp
                   6088: # end: timestamp
                   6089: #
1.240     www      6090:     my (%filters)=@_;
1.620     albertel 6091:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6092:     if ($filters{'url'}) {
                   6093: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6094:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6095:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6096:     }
1.620     albertel 6097:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6098:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6099:     return &log_query($cname,$cdom,'courselog',%filters);
                   6100: }
                   6101: 
                   6102: sub userlog_query {
1.858     raeburn  6103: #
                   6104: # possible filters:
                   6105: # action: log check role
                   6106: # start: timestamp
                   6107: # end: timestamp
                   6108: #
1.240     www      6109:     my ($uname,$udom,%filters)=@_;
                   6110:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6111: }
                   6112: 
1.506     raeburn  6113: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6114: 
                   6115: sub auto_run {
1.508     raeburn  6116:     my ($cnum,$cdom) = @_;
1.876     raeburn  6117:     my $response = 0;
                   6118:     my $settings;
                   6119:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6120:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6121:         $settings = $domconfig{'autoenroll'};
                   6122:         if ($settings->{'run'} eq '1') {
                   6123:             $response = 1;
                   6124:         }
                   6125:     } else {
1.934     raeburn  6126:         my $homeserver;
                   6127:         if (&is_course($cdom,$cnum)) {
                   6128:             $homeserver = &homeserver($cnum,$cdom);
                   6129:         } else {
                   6130:             $homeserver = &domain($cdom,'primary');
                   6131:         }
                   6132:         if ($homeserver ne 'no_host') {
                   6133:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6134:         }
1.876     raeburn  6135:     }
1.506     raeburn  6136:     return $response;
                   6137: }
1.776     albertel 6138: 
1.506     raeburn  6139: sub auto_get_sections {
1.508     raeburn  6140:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6141:     my $homeserver;
                   6142:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6143:         $homeserver = &homeserver($cnum,$cdom);
                   6144:     }
                   6145:     if (!defined($homeserver)) { 
                   6146:         if ($cdom =~ /^$match_domain$/) {
                   6147:             $homeserver = &domain($cdom,'primary');
                   6148:         }
                   6149:     }
                   6150:     my @secs;
                   6151:     if (defined($homeserver)) {
                   6152:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6153:         unless ($response eq 'refused') {
                   6154:             @secs = split(/:/,$response);
                   6155:         }
1.506     raeburn  6156:     }
                   6157:     return @secs;
                   6158: }
1.776     albertel 6159: 
1.506     raeburn  6160: sub auto_new_course {
1.1056.4.19  raeburn  6161:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6162:     my $homeserver = &homeserver($cnum,$cdom);
1.1056.4.19  raeburn  6163:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6164:     return $response;
                   6165: }
1.776     albertel 6166: 
1.506     raeburn  6167: sub auto_validate_courseID {
1.508     raeburn  6168:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6169:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6170:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6171:     return $response;
                   6172: }
1.776     albertel 6173: 
1.1007    raeburn  6174: sub auto_validate_instcode {
1.1020    raeburn  6175:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6176:     my ($homeserver,$response);
                   6177:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6178:         $homeserver = &homeserver($cnum,$cdom);
                   6179:     }
                   6180:     if (!defined($homeserver)) {
                   6181:         if ($cdom =~ /^$match_domain$/) {
                   6182:             $homeserver = &domain($cdom,'primary');
                   6183:         }
                   6184:     }
1.1056.4.2  raeburn  6185:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6186:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6187:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6188:     return ($outcome,$description);
1.1007    raeburn  6189: }
                   6190: 
1.506     raeburn  6191: sub auto_create_password {
1.873     raeburn  6192:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6193:     my ($homeserver,$response);
1.506     raeburn  6194:     my $create_passwd = 0;
                   6195:     my $authchk = '';
1.873     raeburn  6196:     if ($udom =~ /^$match_domain$/) {
                   6197:         $homeserver = &domain($udom,'primary');
                   6198:     }
                   6199:     if ($homeserver eq '') {
                   6200:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6201:             $homeserver = &homeserver($cnum,$cdom);
                   6202:         }
                   6203:     }
                   6204:     if ($homeserver eq '') {
                   6205:         $authchk = 'nodomain';
1.506     raeburn  6206:     } else {
1.873     raeburn  6207:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6208:         if ($response eq 'refused') {
                   6209:             $authchk = 'refused';
                   6210:         } else {
1.901     albertel 6211:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6212:         }
1.506     raeburn  6213:     }
                   6214:     return ($authparam,$create_passwd,$authchk);
                   6215: }
                   6216: 
1.706     raeburn  6217: sub auto_photo_permission {
                   6218:     my ($cnum,$cdom,$students) = @_;
                   6219:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6220:     my ($outcome,$perm_reqd,$conditions) = 
                   6221: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6222:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6223: 	return (undef,undef);
                   6224:     }
1.706     raeburn  6225:     return ($outcome,$perm_reqd,$conditions);
                   6226: }
                   6227: 
                   6228: sub auto_checkphotos {
                   6229:     my ($uname,$udom,$pid) = @_;
                   6230:     my $homeserver = &homeserver($uname,$udom);
                   6231:     my ($result,$resulttype);
                   6232:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6233: 				   &escape($uname).':'.&escape($pid),
                   6234: 				   $homeserver));
1.709     albertel 6235:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6236: 	return (undef,undef);
                   6237:     }
1.706     raeburn  6238:     if ($outcome) {
                   6239:         ($result,$resulttype) = split(/:/,$outcome);
                   6240:     } 
                   6241:     return ($result,$resulttype);
                   6242: }
                   6243: 
                   6244: sub auto_photochoice {
                   6245:     my ($cnum,$cdom) = @_;
                   6246:     my $homeserver = &homeserver($cnum,$cdom);
                   6247:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6248: 						       &escape($cdom),
                   6249: 						       $homeserver)));
1.709     albertel 6250:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6251: 	return (undef,undef);
                   6252:     }
1.706     raeburn  6253:     return ($update,$comment);
                   6254: }
                   6255: 
                   6256: sub auto_photoupdate {
                   6257:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6258:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6259:     my $host=&hostname($homeserver);
1.706     raeburn  6260:     my $cmd = '';
                   6261:     my $maxtries = 1;
1.800     albertel 6262:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6263:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6264:     }
                   6265:     $cmd =~ s/%%$//;
                   6266:     $cmd = &escape($cmd);
                   6267:     my $query = 'institutionalphotos';
                   6268:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6269:     unless ($queryid=~/^\Q$host\E\_/) {
                   6270:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6271:         return 'error: '.$queryid;
                   6272:     }
                   6273:     my $reply = &get_query_reply($queryid);
                   6274:     my $tries = 1;
                   6275:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6276:         $reply = &get_query_reply($queryid);
                   6277:         $tries ++;
                   6278:     }
                   6279:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6280:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6281:     } else {
                   6282:         my @responses = split(/:/,$reply);
                   6283:         my $outcome = shift(@responses); 
                   6284:         foreach my $item (@responses) {
                   6285:             my ($key,$value) = split(/=/,$item);
                   6286:             $$photo{$key} = $value;
                   6287:         }
                   6288:         return $outcome;
                   6289:     }
                   6290:     return 'error';
                   6291: }
                   6292: 
1.521     raeburn  6293: sub auto_instcode_format {
1.793     albertel 6294:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6295: 	$cat_order) = @_;
1.521     raeburn  6296:     my $courses = '';
1.772     raeburn  6297:     my @homeservers;
1.521     raeburn  6298:     if ($caller eq 'global') {
1.841     albertel 6299: 	my %servers = &get_servers($codedom,'library');
                   6300: 	foreach my $tryserver (keys(%servers)) {
                   6301: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6302: 		push(@homeservers,$tryserver);
                   6303: 	    }
1.584     raeburn  6304:         }
1.1022    raeburn  6305:     } elsif ($caller eq 'requests') {
                   6306:         if ($codedom =~ /^$match_domain$/) {
                   6307:             my $chome = &domain($codedom,'primary');
                   6308:             unless ($chome eq 'no_host') {
                   6309:                 push(@homeservers,$chome);
                   6310:             }
                   6311:         }
1.521     raeburn  6312:     } else {
1.772     raeburn  6313:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6314:     }
1.793     albertel 6315:     foreach my $code (keys(%{$instcodes})) {
                   6316:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6317:     }
                   6318:     chop($courses);
1.772     raeburn  6319:     my $ok_response = 0;
                   6320:     my $response;
                   6321:     while (@homeservers > 0 && $ok_response == 0) {
                   6322:         my $server = shift(@homeservers); 
                   6323:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6324:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6325:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6326: 		split(/:/,$response);
1.772     raeburn  6327:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6328:             push(@{$codetitles},&str2array($codetitles_str));
                   6329:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6330:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6331:             $ok_response = 1;
                   6332:         }
                   6333:     }
                   6334:     if ($ok_response) {
1.521     raeburn  6335:         return 'ok';
1.772     raeburn  6336:     } else {
                   6337:         return $response;
1.521     raeburn  6338:     }
                   6339: }
                   6340: 
1.792     raeburn  6341: sub auto_instcode_defaults {
                   6342:     my ($domain,$returnhash,$code_order) = @_;
                   6343:     my @homeservers;
1.841     albertel 6344: 
                   6345:     my %servers = &get_servers($domain,'library');
                   6346:     foreach my $tryserver (keys(%servers)) {
                   6347: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6348: 	    push(@homeservers,$tryserver);
                   6349: 	}
1.792     raeburn  6350:     }
1.841     albertel 6351: 
1.792     raeburn  6352:     my $response;
1.841     albertel 6353:     foreach my $server (@homeservers) {
1.792     raeburn  6354:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6355:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6356: 	
                   6357: 	foreach my $pair (split(/\&/,$response)) {
                   6358: 	    my ($name,$value)=split(/\=/,$pair);
                   6359: 	    if ($name eq 'code_order') {
                   6360: 		@{$code_order} = split(/\&/,&unescape($value));
                   6361: 	    } else {
                   6362: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6363: 	    }
                   6364: 	}
                   6365: 	return 'ok';
1.792     raeburn  6366:     }
1.841     albertel 6367: 
                   6368:     return $response;
1.1003    raeburn  6369: }
                   6370: 
                   6371: sub auto_possible_instcodes {
1.1007    raeburn  6372:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6373:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6374:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6375:         return;
                   6376:     }
1.1003    raeburn  6377:     my (@homeservers,$uhome);
                   6378:     if (defined(&domain($domain,'primary'))) {
                   6379:         $uhome=&domain($domain,'primary');
                   6380:         push(@homeservers,&domain($domain,'primary'));
                   6381:     } else {
                   6382:         my %servers = &get_servers($domain,'library');
                   6383:         foreach my $tryserver (keys(%servers)) {
                   6384:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6385:                 push(@homeservers,$tryserver);
                   6386:             }
                   6387:         }
                   6388:     }
                   6389:     my $response;
                   6390:     foreach my $server (@homeservers) {
                   6391:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6392:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6393:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6394:             split(':',$response);
                   6395:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6396:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6397:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6398:             my ($name,$value)=split('=',$item);
                   6399:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6400:         }
                   6401:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6402:             my ($name,$value)=split('=',$item);
                   6403:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6404:         }
                   6405:         return 'ok';
                   6406:     }
                   6407:     return $response;
                   6408: }
1.792     raeburn  6409: 
1.1010    raeburn  6410: sub auto_courserequest_checks {
                   6411:     my ($dom) = @_;
1.1020    raeburn  6412:     my ($homeserver,%validations);
                   6413:     if ($dom =~ /^$match_domain$/) {
                   6414:         $homeserver = &domain($dom,'primary');
                   6415:     }
                   6416:     unless ($homeserver eq 'no_host') {
                   6417:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6418:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6419:             my @items = split(/&/,$response);
                   6420:             foreach my $item (@items) {
                   6421:                 my ($key,$value) = split('=',$item);
                   6422:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6423:             }
                   6424:         }
                   6425:     }
1.1010    raeburn  6426:     return %validations; 
                   6427: }
                   6428: 
1.1020    raeburn  6429: sub auto_courserequest_validation {
                   6430:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6431:     my ($homeserver,$response);
                   6432:     if ($dom =~ /^$match_domain$/) {
                   6433:         $homeserver = &domain($dom,'primary');
                   6434:     }
                   6435:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6436:           
1.1020    raeburn  6437:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6438:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6439:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6440:                                     $homeserver));
                   6441:     }
                   6442:     return $response;
                   6443: }
                   6444: 
1.777     albertel 6445: sub auto_validate_class_sec {
1.918     raeburn  6446:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6447:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6448:     my $ownerlist;
                   6449:     if (ref($owners) eq 'ARRAY') {
                   6450:         $ownerlist = join(',',@{$owners});
                   6451:     } else {
                   6452:         $ownerlist = $owners;
                   6453:     }
1.773     raeburn  6454:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6455:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6456:     return $response;
                   6457: }
                   6458: 
1.679     raeburn  6459: # ------------------------------------------------------- Course Group routines
                   6460: 
                   6461: sub get_coursegroups {
1.809     raeburn  6462:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6463:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6464: }
                   6465: 
1.679     raeburn  6466: sub modify_coursegroup {
                   6467:     my ($cdom,$cnum,$groupsettings) = @_;
                   6468:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6469: }
                   6470: 
1.809     raeburn  6471: sub toggle_coursegroup_status {
                   6472:     my ($cdom,$cnum,$group,$action) = @_;
                   6473:     my ($from_namespace,$to_namespace);
                   6474:     if ($action eq 'delete') {
                   6475:         $from_namespace = 'coursegroups';
                   6476:         $to_namespace = 'deleted_groups';
                   6477:     } else {
                   6478:         $from_namespace = 'deleted_groups';
                   6479:         $to_namespace = 'coursegroups';
                   6480:     }
                   6481:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6482:     if (my $tmp = &error(%curr_group)) {
                   6483:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6484:         return ('read error',$tmp);
                   6485:     } else {
                   6486:         my %savedsettings = %curr_group; 
1.809     raeburn  6487:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6488:         my $deloutcome;
                   6489:         if ($result eq 'ok') {
1.809     raeburn  6490:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6491:         } else {
                   6492:             return ('write error',$result);
                   6493:         }
                   6494:         if ($deloutcome eq 'ok') {
                   6495:             return 'ok';
                   6496:         } else {
                   6497:             return ('delete error',$deloutcome);
                   6498:         }
                   6499:     }
                   6500: }
                   6501: 
1.679     raeburn  6502: sub modify_group_roles {
1.957     raeburn  6503:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6504:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6505:     my $role = 'gr/'.&escape($userprivs);
                   6506:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6507:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6508:     if ($result eq 'ok') {
                   6509:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6510:     }
1.679     raeburn  6511:     return $result;
                   6512: }
                   6513: 
                   6514: sub modify_coursegroup_membership {
                   6515:     my ($cdom,$cnum,$membership) = @_;
                   6516:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6517:     return $result;
                   6518: }
                   6519: 
1.682     raeburn  6520: sub get_active_groups {
                   6521:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6522:     my $now = time;
                   6523:     my %groups = ();
                   6524:     foreach my $key (keys(%env)) {
1.811     albertel 6525:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6526:             my ($start,$end) = split(/\./,$env{$key});
                   6527:             if (($end!=0) && ($end<$now)) { next; }
                   6528:             if (($start!=0) && ($start>$now)) { next; }
                   6529:             if ($1 eq $cdom && $2 eq $cnum) {
                   6530:                 $groups{$3} = $env{$key} ;
                   6531:             }
                   6532:         }
                   6533:     }
                   6534:     return %groups;
                   6535: }
                   6536: 
1.683     raeburn  6537: sub get_group_membership {
                   6538:     my ($cdom,$cnum,$group) = @_;
                   6539:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6540: }
                   6541: 
                   6542: sub get_users_groups {
                   6543:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6544:     my @usersgroups;
1.683     raeburn  6545:     my $cachetime=1800;
                   6546: 
                   6547:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6548:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6549:     if (defined($cached)) {
1.734     albertel 6550:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6551:     } else {  
                   6552:         $grouplist = '';
1.816     raeburn  6553:         my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  6554:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6555:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6556:         my $access_end = $env{'course.'.$courseid.
                   6557:                               '.default_enrollment_end_date'};
                   6558:         my $now = time;
                   6559:         foreach my $key (keys(%roleshash)) {
                   6560:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6561:                 my $group = $1;
                   6562:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6563:                     my $start = $2;
                   6564:                     my $end = $1;
                   6565:                     if ($start == -1) { next; } # deleted from group
                   6566:                     if (($start!=0) && ($start>$now)) { next; }
                   6567:                     if (($end!=0) && ($end<$now)) {
                   6568:                         if ($access_end && $access_end < $now) {
                   6569:                             if ($access_end - $end < 86400) {
                   6570:                                 push(@usersgroups,$group);
1.733     raeburn  6571:                             }
                   6572:                         }
1.817     raeburn  6573:                         next;
1.733     raeburn  6574:                     }
1.817     raeburn  6575:                     push(@usersgroups,$group);
1.683     raeburn  6576:                 }
                   6577:             }
                   6578:         }
1.817     raeburn  6579:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6580:         $grouplist = join(':',@usersgroups);
                   6581:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6582:     }
1.733     raeburn  6583:     return @usersgroups;
1.683     raeburn  6584: }
                   6585: 
                   6586: sub devalidate_getgroups_cache {
                   6587:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6588:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6589: 
1.683     raeburn  6590:     my $hashid="$udom:$uname:$courseid";
                   6591:     &devalidate_cache_new('getgroups',$hashid);
                   6592: }
                   6593: 
1.12      www      6594: # ------------------------------------------------------------------ Plain Text
                   6595: 
                   6596: sub plaintext {
1.988     raeburn  6597:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6598:     if ($short =~ m{^cr/}) {
1.758     albertel 6599: 	return (split('/',$short))[-1];
                   6600:     }
1.742     raeburn  6601:     if (!defined($cid)) {
                   6602:         $cid = $env{'request.course.id'};
                   6603:     }
                   6604:     my %rolenames = (
1.1008    raeburn  6605:                       Course    => 'std',
                   6606:                       Community => 'alt1',
1.742     raeburn  6607:                     );
1.1037    raeburn  6608:     if ($cid ne '') {
                   6609:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6610:             unless ($forcedefault) {
                   6611:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6612:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6613:                 return &Apache::lonlocal::mt($roletext);
                   6614:             }
                   6615:         }
                   6616:     }
                   6617:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6618:         (defined($rolenames{$type})) && 
                   6619:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6620:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6621:     } elsif ($cid ne '') {
                   6622:         my $crstype = $env{'course.'.$cid.'.type'};
                   6623:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6624:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6625:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6626:         }
1.742     raeburn  6627:     }
1.1037    raeburn  6628:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6629: }
                   6630: 
                   6631: # ----------------------------------------------------------------- Assign Role
                   6632: 
                   6633: sub assignrole {
1.957     raeburn  6634:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6635:         $context)=@_;
1.21      www      6636:     my $mrole;
                   6637:     if ($role =~ /^cr\//) {
1.393     www      6638:         my $cwosec=$url;
1.811     albertel 6639:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6640: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6641:            my $refused = 1;
                   6642:            if ($context eq 'requestcourses') {
                   6643:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6644:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6645:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6646:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6647:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6648:                            if ($crsenv{'internal.courseowner'} eq
                   6649:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6650:                                $refused = '';
                   6651:                            }
                   6652:                        }
                   6653:                    }
                   6654:                }
                   6655:            }
                   6656:            if ($refused) {
                   6657:                &logthis('Refused custom assignrole: '.
                   6658:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6659:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6660:                return 'refused';
                   6661:            }
1.104     www      6662:         }
1.21      www      6663:         $mrole='cr';
1.678     raeburn  6664:     } elsif ($role =~ /^gr\//) {
                   6665:         my $cwogrp=$url;
1.811     albertel 6666:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6667:         unless (&allowed('mdg',$cwogrp)) {
                   6668:             &logthis('Refused group assignrole: '.
                   6669:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6670:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6671:             return 'refused';
                   6672:         }
                   6673:         $mrole='gr';
1.21      www      6674:     } else {
1.82      www      6675:         my $cwosec=$url;
1.811     albertel 6676:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6677:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6678:             my $refused;
                   6679:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6680:                 if (!(&allowed('c'.$role,$url))) {
                   6681:                     $refused = 1;
                   6682:                 }
                   6683:             } else {
                   6684:                 $refused = 1;
                   6685:             }
1.947     raeburn  6686:             if ($refused) {
1.1045    raeburn  6687:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6688:                 if (!$selfenroll && $context eq 'course') {
                   6689:                     my %crsenv;
                   6690:                     if ($role eq 'cc' || $role eq 'co') {
                   6691:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6692:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6693:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6694:                                 if ($crsenv{'internal.courseowner'} eq 
                   6695:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6696:                                     $refused = '';
                   6697:                                 }
                   6698:                             }
                   6699:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6700:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6701:                                 if ($crsenv{'internal.courseowner'} eq 
                   6702:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6703:                                     $refused = '';
                   6704:                                 }
                   6705:                             }
                   6706:                         }
                   6707:                     }
                   6708:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6709:                     $refused = '';
1.1017    raeburn  6710:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6711:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6712:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6713:                         my $wrongcc;
                   6714:                         if ($cnum =~ /^$match_community$/) {
                   6715:                             $wrongcc = 1 if ($role eq 'cc');
                   6716:                         } else {
                   6717:                             $wrongcc = 1 if ($role eq 'co');
                   6718:                         }
                   6719:                         unless ($wrongcc) {
                   6720:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6721:                             if ($crsenv{'internal.courseowner'} eq 
                   6722:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6723:                                 $refused = '';
                   6724:                             }
1.1017    raeburn  6725:                         }
                   6726:                     }
                   6727:                 }
                   6728:                 if ($refused) {
1.947     raeburn  6729:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6730:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6731: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6732:                     return 'refused';
                   6733:                 }
1.932     raeburn  6734:             }
1.104     www      6735:         }
1.21      www      6736:         $mrole=$role;
                   6737:     }
1.620     albertel 6738:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6739:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6740:     if ($end) { $command.='_'.$end; }
1.21      www      6741:     if ($start) {
                   6742: 	if ($end) { 
1.81      www      6743:            $command.='_'.$start; 
1.21      www      6744:         } else {
1.81      www      6745:            $command.='_0_'.$start;
1.21      www      6746:         }
                   6747:     }
1.739     raeburn  6748:     my $origstart = $start;
                   6749:     my $origend = $end;
1.957     raeburn  6750:     my $delflag;
1.357     www      6751: # actually delete
                   6752:     if ($deleteflag) {
1.373     www      6753: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6754: # modify command to delete the role
1.620     albertel 6755:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6756:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6757: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6758: # set start and finish to negative values for userrolelog
                   6759:            $start=-1;
                   6760:            $end=-1;
1.957     raeburn  6761:            $delflag = 1;
1.357     www      6762:         }
                   6763:     }
                   6764: # send command
1.349     www      6765:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6766: # log new user role if status is ok
1.349     www      6767:     if ($answer eq 'ok') {
1.663     raeburn  6768: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6769: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6770:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6771:         unless ($role =~ /^gr/) {
                   6772:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6773:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6774:         }
1.1053    raeburn  6775:         if ($role eq 'cc') {
                   6776:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6777:         }
1.349     www      6778:     }
                   6779:     return $answer;
1.169     harris41 6780: }
                   6781: 
1.1053    raeburn  6782: sub autoupdate_coowners {
                   6783:     my ($url,$end,$start,$uname,$udom) = @_;
                   6784:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6785:     if (($cdom ne '') && ($cnum ne '')) {
                   6786:         my $now = time;
                   6787:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6788:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6789:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6790:             my $instcode = $coursehash{'internal.coursecode'};
                   6791:             if ($instcode ne '') {
1.1056    raeburn  6792:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6793:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6794:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6795:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6796:                         if ($result eq 'valid') {
                   6797:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6798:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6799:                                     push(@newcoowners,$coowner);
                   6800:                                 }
                   6801:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6802:                                     push(@newcoowners,$uname.':'.$udom);
                   6803:                                 }
                   6804:                                 @newcoowners = sort(@newcoowners);
                   6805:                             } else {
                   6806:                                 push(@newcoowners,$uname.':'.$udom);
                   6807:                             }
                   6808:                         } else {
                   6809:                             if ($coursehash{'internal.co-owners'}) {
                   6810:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6811:                                     unless ($coowner eq $uname.':'.$udom) {
                   6812:                                         push(@newcoowners,$coowner);
                   6813:                                     }
                   6814:                                 }
                   6815:                                 unless (@newcoowners > 0) {
                   6816:                                     $delcoowners = 1;
                   6817:                                     $coowners = '';
                   6818:                                 }
                   6819:                             }
                   6820:                         }
                   6821:                         if (@newcoowners || $delcoowners) {
                   6822:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6823:                                             $delcoowners,@newcoowners);
                   6824:                         }
                   6825:                     }
                   6826:                 }
                   6827:             }
                   6828:         }
                   6829:     }
                   6830: }
                   6831: 
                   6832: sub store_coowners {
                   6833:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6834:     my $cid = $cdom.'_'.$cnum;
                   6835:     my ($coowners,$delresult,$putresult);
                   6836:     if (@newcoowners) {
                   6837:         $coowners = join(',',@newcoowners);
                   6838:         my %coownershash = (
                   6839:                             'internal.co-owners' => $coowners,
                   6840:                            );
                   6841:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6842:         if ($putresult eq 'ok') {
                   6843:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6844:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6845:             }
                   6846:         }
                   6847:     }
                   6848:     if ($delcoowners) {
                   6849:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6850:         if ($delresult eq 'ok') {
                   6851:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6852:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6853:             }
                   6854:         }
                   6855:     }
                   6856:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6857:         my %crsinfo =
                   6858:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6859:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6860:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6861:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6862:         }
                   6863:     }
                   6864: }
                   6865: 
1.169     harris41 6866: # -------------------------------------------------- Modify user authentication
1.197     www      6867: # Overrides without validation
                   6868: 
1.169     harris41 6869: sub modifyuserauth {
                   6870:     my ($udom,$uname,$umode,$upass)=@_;
                   6871:     my $uhome=&homeserver($uname,$udom);
1.197     www      6872:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6873:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6874:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6875:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6876:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6877: 		     &escape($upass),$uhome);
1.620     albertel 6878:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6879:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6880:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6881:     &log($udom,,$uname,$uhome,
1.620     albertel 6882:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6883:                                      $env{'user.name'}.', '.$umode.
1.197     www      6884:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6885:     unless ($reply eq 'ok') {
1.197     www      6886:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6887: 	return 'error: '.$reply;
                   6888:     }   
1.170     harris41 6889:     return 'ok';
1.80      www      6890: }
                   6891: 
1.81      www      6892: # --------------------------------------------------------------- Modify a user
1.80      www      6893: 
1.81      www      6894: sub modifyuser {
1.206     matthew  6895:     my ($udom,    $uname, $uid,
                   6896:         $umode,   $upass, $first,
                   6897:         $middle,  $last,  $gene,
1.1056.4.1  raeburn  6898:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6899:     $udom= &LONCAPA::clean_domain($udom);
                   6900:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  raeburn  6901:     my $showcandelete = 'none';
                   6902:     if (ref($candelete) eq 'ARRAY') {
                   6903:         if (@{$candelete} > 0) {
                   6904:             $showcandelete = join(', ',@{$candelete});
                   6905:         }
                   6906:     }
1.81      www      6907:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6908:              $umode.', '.$first.', '.$middle.', '.
1.1056.4.1  raeburn  6909:              $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6910:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6911:                                      ' desiredhome not specified'). 
1.620     albertel 6912:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6913:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6914:     my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4  raeburn  6915:     my $newuser;
                   6916:     if ($uhome eq 'no_host') {
                   6917:         $newuser = 1;
                   6918:     }
1.80      www      6919: # ----------------------------------------------------------------- Create User
1.406     albertel 6920:     if (($uhome eq 'no_host') && 
                   6921: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6922:         my $unhome='';
1.844     albertel 6923:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6924:             $unhome = $desiredhome;
1.620     albertel 6925: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6926: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6927:         } else { # load balancing routine for determining $unhome
1.81      www      6928:             my $loadm=10000000;
1.841     albertel 6929: 	    my %servers = &get_servers($udom,'library');
                   6930: 	    foreach my $tryserver (keys(%servers)) {
                   6931: 		my $answer=reply('load',$tryserver);
                   6932: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6933: 		    $loadm=$answer;
                   6934: 		    $unhome=$tryserver;
                   6935: 		}
1.80      www      6936: 	    }
                   6937:         }
                   6938:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6939: 	    return 'error: unable to find a home server for '.$uname.
                   6940:                    ' in domain '.$udom;
1.80      www      6941:         }
                   6942:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6943:                          &escape($upass),$unhome);
                   6944: 	unless ($reply eq 'ok') {
                   6945:             return 'error: '.$reply;
                   6946:         }   
1.230     stredwic 6947:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6948:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6949: 	    return 'error: unable verify users home machine.';
1.80      www      6950:         }
1.209     matthew  6951:     }   # End of creation of new user
1.80      www      6952: # ---------------------------------------------------------------------- Add ID
                   6953:     if ($uid) {
                   6954:        $uid=~tr/A-Z/a-z/;
                   6955:        my %uidhash=&idrget($udom,$uname);
1.196     www      6956:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6957:          && (!$forceid)) {
1.80      www      6958: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6959: 	      return 'error: user id "'.$uid.'" does not match '.
                   6960:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6961:           }
                   6962:        } else {
                   6963: 	  &idput($udom,($uname => $uid));
                   6964:        }
                   6965:     }
                   6966: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6967:     my @tmp=&get('environment',
1.899     raeburn  6968: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6969:                     'permanentemail','inststatus'],
1.134     albertel 6970: 		   $udom,$uname);
1.1056.4.4  raeburn  6971:     my (%names,%oldnames);
1.313     matthew  6972:     if ($tmp[0] =~ m/^error:.*/) { 
                   6973:         %names=(); 
                   6974:     } else {
                   6975:         %names = @tmp;
1.1056.4.4  raeburn  6976:         %oldnames = %names;
1.313     matthew  6977:     }
1.1056.4.6  raeburn  6978: #
1.1056.4.1  raeburn  6979: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6980: # of users did not contain them), do not overwrite existing values
                   6981: # unless field is in $candelete array ref.  
                   6982: #
                   6983: 
                   6984:     my @fields = ('firstname','middlename','lastname','generation',
                   6985:                   'permanentemail','id');
                   6986:     my %newvalues;
                   6987:     if (ref($candelete) eq 'ARRAY') {
                   6988:         foreach my $field (@fields) {
                   6989:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6990:                 if ($field eq 'firstname') {
                   6991:                     $names{$field} = $first;
                   6992:                 } elsif ($field eq 'middlename') {
                   6993:                     $names{$field} = $middle;
                   6994:                 } elsif ($field eq 'lastname') {
                   6995:                     $names{$field} = $last;
                   6996:                 } elsif ($field eq 'generation') { 
                   6997:                     $names{$field} = $gene;
                   6998:                 } elsif ($field eq 'permanentemail') {
                   6999:                     $names{$field} = $email;
                   7000:                 } elsif ($field eq 'id') {
                   7001:                     $names{$field}  = $uid;
                   7002:                 }
                   7003:             }
                   7004:         }
                   7005:     }
1.388     www      7006:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7007:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7008:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7009:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7010:     if ($email) {
                   7011:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7012:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7013:     }
1.899     raeburn  7014:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7015:     if (defined($inststatus)) {
                   7016:         $names{'inststatus'} = '';
                   7017:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7018:         if (ref($usertypes) eq 'HASH') {
                   7019:             my @okstatuses; 
                   7020:             foreach my $item (split(/:/,$inststatus)) {
                   7021:                 if (defined($usertypes->{$item})) {
                   7022:                     push(@okstatuses,$item);  
                   7023:                 }
                   7024:             }
                   7025:             if (@okstatuses) {
                   7026:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7027:             }
                   7028:         }
                   7029:     }
1.1056.4.4  raeburn  7030:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7031:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  raeburn  7032:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7033:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7034:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7035:     } else {
                   7036:         $logmsg .= ' during self creation';
                   7037:     }
1.1056.4.4  raeburn  7038:     my $changed;
                   7039:     if ($newuser) {
                   7040:         $changed = 1;
                   7041:     } else {
                   7042:         foreach my $field (@fields) {
                   7043:             if ($names{$field} ne $oldnames{$field}) {
                   7044:                 $changed = 1;
                   7045:                 last;
                   7046:             }
                   7047:         }
                   7048:     }
                   7049:     unless ($changed) {
                   7050:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7051:         &logthis($logmsg);
                   7052:         return 'ok';
                   7053:     }
                   7054:     my $reply = &put('environment', \%names, $udom,$uname);
                   7055:     if ($reply ne 'ok') {
                   7056:         return 'error: '.$reply;
                   7057:     }
1.1056.4.11  raeburn  7058:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7059:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7060:     }
1.1056.4.4  raeburn  7061:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7062:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7063:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7064:     &logthis($logmsg);
1.134     albertel 7065:     return 'ok';
1.80      www      7066: }
                   7067: 
1.81      www      7068: # -------------------------------------------------------------- Modify student
1.80      www      7069: 
1.81      www      7070: sub modifystudent {
                   7071:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7072:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7073:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7074:     if (!$cid) {
1.620     albertel 7075: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7076: 	    return 'not_in_class';
                   7077: 	}
1.80      www      7078:     }
                   7079: # --------------------------------------------------------------- Make the user
1.81      www      7080:     my $reply=&modifyuser
1.209     matthew  7081: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7082:          $desiredhome,$email,$inststatus);
1.80      www      7083:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7084:     # This will cause &modify_student_enrollment to get the uid from the
                   7085:     # students environment
                   7086:     $uid = undef if (!$forceid);
1.455     albertel 7087:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7088: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7089:     return $reply;
                   7090: }
                   7091: 
                   7092: sub modify_student_enrollment {
1.957     raeburn  7093:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7094:     my ($cdom,$cnum,$chome);
                   7095:     if (!$cid) {
1.620     albertel 7096: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7097: 	    return 'not_in_class';
                   7098: 	}
1.620     albertel 7099: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7100: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7101:     } else {
                   7102: 	($cdom,$cnum)=split(/_/,$cid);
                   7103:     }
1.620     albertel 7104:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7105:     if (!$chome) {
1.457     raeburn  7106: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7107:     }
1.455     albertel 7108:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7109:     # Make sure the user exists
1.81      www      7110:     my $uhome=&homeserver($uname,$udom);
                   7111:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7112: 	return 'error: no such user';
                   7113:     }
1.297     matthew  7114:     # Get student data if we were not given enough information
                   7115:     if (!defined($first)  || $first  eq '' || 
                   7116:         !defined($last)   || $last   eq '' || 
                   7117:         !defined($uid)    || $uid    eq '' || 
                   7118:         !defined($middle) || $middle eq '' || 
                   7119:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7120:         # They did not supply us with enough data to enroll the student, so
                   7121:         # we need to pick up more information.
1.297     matthew  7122:         my %tmp = &get('environment',
1.294     matthew  7123:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7124:                        ,$udom,$uname);
                   7125: 
1.800     albertel 7126:         #foreach my $key (keys(%tmp)) {
                   7127:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7128:         #}
1.294     matthew  7129:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7130:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7131:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7132:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7133:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7134:     }
1.556     albertel 7135:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7136:     my $reply=cput('classlist',
                   7137: 		   {"$uname:$udom" => 
1.515     raeburn  7138: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7139: 		   $cdom,$cnum);
1.81      www      7140:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7141: 	return 'error: '.$reply;
1.652     albertel 7142:     } else {
                   7143: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7144:     }
1.297     matthew  7145:     # Add student role to user
1.83      www      7146:     my $uurl='/'.$cid;
1.81      www      7147:     $uurl=~s/\_/\//g;
                   7148:     if ($usec) {
                   7149: 	$uurl.='/'.$usec;
                   7150:     }
1.957     raeburn  7151:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7152: }
                   7153: 
1.556     albertel 7154: sub format_name {
                   7155:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7156:     my $name;
                   7157:     if ($first ne 'lastname') {
                   7158: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7159:     } else {
                   7160: 	if ($lastname=~/\S/) {
                   7161: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7162: 	    $name=~s/\s+,/,/;
                   7163: 	} else {
                   7164: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7165: 	}
                   7166:     }
                   7167:     $name=~s/^\s+//;
                   7168:     $name=~s/\s+$//;
                   7169:     $name=~s/\s+/ /g;
                   7170:     return $name;
                   7171: }
                   7172: 
1.84      www      7173: # ------------------------------------------------- Write to course preferences
                   7174: 
                   7175: sub writecoursepref {
                   7176:     my ($courseid,%prefs)=@_;
                   7177:     $courseid=~s/^\///;
                   7178:     $courseid=~s/\_/\//g;
                   7179:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7180:     my $chome=homeserver($cnum,$cdomain);
                   7181:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7182: 	return 'error: no such course';
                   7183:     }
                   7184:     my $cstring='';
1.800     albertel 7185:     foreach my $pref (keys(%prefs)) {
                   7186: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7187:     }
1.84      www      7188:     $cstring=~s/\&$//;
                   7189:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7190: }
                   7191: 
                   7192: # ---------------------------------------------------------- Make/modify course
                   7193: 
                   7194: sub createcourse {
1.741     raeburn  7195:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7196:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7197:     $url=&declutter($url);
                   7198:     my $cid='';
1.1028    raeburn  7199:     if ($context eq 'requestcourses') {
                   7200:         my $can_create = 0;
                   7201:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7202:         if ($udom eq $ownerdom) {
                   7203:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7204:                                   $context)) {
                   7205:                 $can_create = 1;
                   7206:             }
                   7207:         } else {
                   7208:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7209:                                            $category);
                   7210:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7211:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7212:                 if (@curr > 0) {
                   7213:                     my @options = qw(approval validate autolimit);
                   7214:                     my $optregex = join('|',@options);
                   7215:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7216:                         $can_create = 1;
                   7217:                     }
                   7218:                 }
                   7219:             }
                   7220:         }
                   7221:         if ($can_create) {
                   7222:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7223:                 unless (&allowed('ccc',$udom)) {
                   7224:                     return 'refused'; 
                   7225:                 }
1.1017    raeburn  7226:             }
                   7227:         } else {
                   7228:             return 'refused';
                   7229:         }
1.1028    raeburn  7230:     } elsif (!&allowed('ccc',$udom)) {
                   7231:         return 'refused';
1.84      www      7232:     }
1.1011    raeburn  7233: # --------------------------------------------------------------- Get Unique ID
                   7234:     my $uname;
                   7235:     if ($cnum =~ /^$match_courseid$/) {
                   7236:         my $chome=&homeserver($cnum,$udom,'true');
                   7237:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7238:             $uname = $cnum;
                   7239:         } else {
1.1038    raeburn  7240:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7241:         }
                   7242:     } else {
1.1038    raeburn  7243:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7244:     }
                   7245:     return $uname if ($uname =~ /^error/);
                   7246: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7247:     if (!defined($course_server)) {
                   7248:         if (defined(&domain($udom,'primary'))) {
                   7249:             $course_server = &domain($udom,'primary');
                   7250:         } else {
                   7251:             $course_server = $env{'user.home'}; 
                   7252:         }
                   7253:     }
                   7254:     my %host_servers =
                   7255:         &Apache::lonnet::get_servers($udom,'library');
                   7256:     unless ($host_servers{$course_server}) {
                   7257:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7258:     }
1.84      www      7259: # ------------------------------------------------------------- Make the course
                   7260:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7261:                       $course_server);
1.84      www      7262:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7263:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7264:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7265: 	return 'error: no such course';
                   7266:     }
1.271     www      7267: # ----------------------------------------------------------------- Course made
1.516     raeburn  7268: # log existence
1.1029    raeburn  7269:     my $now = time;
1.918     raeburn  7270:     my $newcourse = {
                   7271:                     $udom.'_'.$uname => {
1.921     raeburn  7272:                                      description => $description,
                   7273:                                      inst_code   => $inst_code,
                   7274:                                      owner       => $course_owner,
                   7275:                                      type        => $crstype,
1.1029    raeburn  7276:                                      creator     => $env{'user.name'}.':'.
                   7277:                                                     $env{'user.domain'},
                   7278:                                      created     => $now,
                   7279:                                      context     => $context,
1.918     raeburn  7280:                                                 },
                   7281:                     };
1.921     raeburn  7282:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7283: # set toplevel url
1.271     www      7284:     my $topurl=$url;
                   7285:     unless ($nonstandard) {
                   7286: # ------------------------------------------ For standard courses, make top url
                   7287:         my $mapurl=&clutter($url);
1.278     www      7288:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7289:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7290: <map>
                   7291: <resource id="1" type="start"></resource>
                   7292: <resource id="2" src="$mapurl"></resource>
                   7293: <resource id="3" type="finish"></resource>
                   7294: <link index="1" from="1" to="2"></link>
                   7295: <link index="2" from="2" to="3"></link>
                   7296: </map>
                   7297: ENDINITMAP
                   7298:         $topurl=&declutter(
1.638     albertel 7299:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7300:                           );
                   7301:     }
                   7302: # ----------------------------------------------------------- Write preferences
1.84      www      7303:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7304:                      ('description'              => $description,
                   7305:                       'url'                      => $topurl,
                   7306:                       'internal.creator'         => $env{'user.name'}.':'.
                   7307:                                                     $env{'user.domain'},
                   7308:                       'internal.created'         => $now,
                   7309:                       'internal.creationcontext' => $context)
                   7310:                     );
1.84      www      7311:     return '/'.$udom.'/'.$uname;
                   7312: }
                   7313: 
1.1011    raeburn  7314: # ------------------------------------------------------------------- Create ID
                   7315: sub generate_coursenum {
1.1038    raeburn  7316:     my ($udom,$crstype) = @_;
1.1011    raeburn  7317:     my $domdesc = &domain($udom);
                   7318:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7319:     my $first;
                   7320:     if ($crstype eq 'Community') {
                   7321:         $first = '0';
                   7322:     } else {
                   7323:         $first = int(1+rand(9)); 
                   7324:     } 
                   7325:     my $uname=$first.
1.1011    raeburn  7326:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7327:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7328:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7329: # ----------------------------------------------- Make sure that does not exist
                   7330:     my $uhome=&homeserver($uname,$udom,'true');
                   7331:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7332:         if ($crstype eq 'Community') {
                   7333:             $first = '0';
                   7334:         } else {
                   7335:             $first = int(1+rand(9));
                   7336:         }
                   7337:         $uname=$first.
1.1011    raeburn  7338:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7339:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7340:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7341:         $uhome=&homeserver($uname,$udom,'true');
                   7342:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7343:             return 'error: unable to generate unique course-ID';
                   7344:         }
                   7345:     }
                   7346:     return $uname;
                   7347: }
                   7348: 
1.813     albertel 7349: sub is_course {
                   7350:     my ($cdom,$cnum) = @_;
                   7351:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7352: 				undef,'.');
1.813     albertel 7353:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7354:         return 1;
                   7355:     }
                   7356:     return 0;
                   7357: }
                   7358: 
1.1015    raeburn  7359: sub store_userdata {
                   7360:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7361:     my $result;
1.1016    raeburn  7362:     if ($datakey ne '') {
1.1013    raeburn  7363:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7364:             if ($udom eq '' || $uname eq '') {
                   7365:                 $udom = $env{'user.domain'};
                   7366:                 $uname = $env{'user.name'};
                   7367:             }
                   7368:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7369:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7370:                 $result = 'error: no_host';
                   7371:             } else {
                   7372:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7373:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7374: 
                   7375:                 my $namevalue='';
                   7376:                 foreach my $key (keys(%{$storehash})) {
                   7377:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7378:                 }
                   7379:                 $namevalue=~s/\&$//;
1.1056.4.24  raeburn  7380:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7381:                                   $namevalue,$uhome);
1.1013    raeburn  7382:             }
                   7383:         } else {
                   7384:             $result = 'error: data to store was not a hash reference'; 
                   7385:         }
                   7386:     } else {
                   7387:         $result= 'error: invalid requestkey'; 
                   7388:     }
                   7389:     return $result;
                   7390: }
                   7391: 
1.21      www      7392: # ---------------------------------------------------------- Assign Custom Role
                   7393: 
                   7394: sub assigncustomrole {
1.957     raeburn  7395:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7396:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7397:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7398: }
                   7399: 
                   7400: # ----------------------------------------------------------------- Revoke Role
                   7401: 
                   7402: sub revokerole {
1.957     raeburn  7403:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7404:     my $now=time;
1.965     raeburn  7405:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7406: }
                   7407: 
                   7408: # ---------------------------------------------------------- Revoke Custom Role
                   7409: 
                   7410: sub revokecustomrole {
1.957     raeburn  7411:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7412:     my $now=time;
1.357     www      7413:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7414:            $deleteflag,$selfenroll,$context);
1.17      www      7415: }
                   7416: 
1.533     banghart 7417: # ------------------------------------------------------------ Disk usage
1.535     albertel 7418: sub diskusage {
1.955     raeburn  7419:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7420:     $directorypath =~ s/\/$//;
                   7421:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7422:                        .&escape($getpropath).':'.&escape($uname).':'
                   7423:                        .&escape($udom),homeserver($uname,$udom));
                   7424:     if ($listing eq 'unknown_cmd') {
                   7425:         if ($getpropath) {
                   7426:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7427:         }
                   7428:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7429:     }
1.514     albertel 7430:     return $listing;
1.512     banghart 7431: }
                   7432: 
1.566     banghart 7433: sub is_locked {
1.1056.4.17  raeburn  7434:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7435:     my @check;
                   7436:     my $is_locked;
1.1056.4.14  raeburn  7437:     push(@check,$file_name);
1.613     albertel 7438:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7439: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7440:     my ($tmp)=keys(%locked);
                   7441:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7442:     
1.566     banghart 7443:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7444:         $is_locked = 'false';
                   7445:         foreach my $entry (@{$locked{$file_name}}) {
1.1056.4.17  raeburn  7446:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7447:                $is_locked = 'true';
1.1056.4.17  raeburn  7448:                if (ref($which) eq 'ARRAY') {
                   7449:                    push(@{$which},$entry);
                   7450:                } else {
                   7451:                    last;
                   7452:                }
1.745     raeburn  7453:            }
                   7454:        }
1.566     banghart 7455:     } else {
                   7456:         $is_locked = 'false';
                   7457:     }
1.1056.4.14  raeburn  7458:     return $is_locked;
1.566     banghart 7459: }
                   7460: 
1.759     albertel 7461: sub declutter_portfile {
                   7462:     my ($file) = @_;
1.833     albertel 7463:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7464:     return $file;
                   7465: }
                   7466: 
1.559     banghart 7467: # ------------------------------------------------------------- Mark as Read Only
                   7468: 
                   7469: sub mark_as_readonly {
                   7470:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7471:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7472:     my ($tmp)=keys(%current_permissions);
                   7473:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7474:     foreach my $file (@{$files}) {
1.759     albertel 7475: 	$file = &declutter_portfile($file);
1.561     banghart 7476:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7477:     }
1.613     albertel 7478:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7479:     return;
                   7480: }
                   7481: 
1.572     banghart 7482: # ------------------------------------------------------------Save Selected Files
                   7483: 
                   7484: sub save_selected_files {
                   7485:     my ($user, $path, @files) = @_;
                   7486:     my $filename = $user."savedfiles";
1.573     banghart 7487:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7488:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7489:     foreach my $file (@files) {
1.620     albertel 7490:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7491:     }
                   7492:     foreach my $file (@other_files) {
1.574     banghart 7493:         print (OUT $file."\n");
1.572     banghart 7494:     }
1.574     banghart 7495:     close (OUT);
1.572     banghart 7496:     return 'ok';
                   7497: }
                   7498: 
1.574     banghart 7499: sub clear_selected_files {
                   7500:     my ($user) = @_;
                   7501:     my $filename = $user."savedfiles";
                   7502:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7503:     print (OUT undef);
                   7504:     close (OUT);
                   7505:     return ("ok");    
                   7506: }
                   7507: 
1.572     banghart 7508: sub files_in_path {
                   7509:     my ($user, $path) = @_;
                   7510:     my $filename = $user."savedfiles";
                   7511:     my %return_files;
1.574     banghart 7512:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7513:     while (my $line_in = <IN>) {
1.574     banghart 7514:         chomp ($line_in);
                   7515:         my @paths_and_file = split (m!/!, $line_in);
                   7516:         my $file_part = pop (@paths_and_file);
                   7517:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7518:         $path_part.='/';
                   7519:         my $path_and_file = $path_part.$file_part;
                   7520:         if ($path_part eq $path) {
                   7521:             $return_files{$file_part}= 'selected';
                   7522:         }
                   7523:     }
1.574     banghart 7524:     close (IN);
                   7525:     return (\%return_files);
1.572     banghart 7526: }
                   7527: 
                   7528: # called in portfolio select mode, to show files selected NOT in current directory
                   7529: sub files_not_in_path {
                   7530:     my ($user, $path) = @_;
                   7531:     my $filename = $user."savedfiles";
                   7532:     my @return_files;
                   7533:     my $path_part;
1.800     albertel 7534:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7535:     while (my $line = <IN>) {
1.572     banghart 7536:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7537:         my @paths_and_file = split(m|/|, $line);
                   7538:         my $file_part = pop(@paths_and_file);
                   7539:         chomp($file_part);
                   7540:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7541:         $path_part .= '/';
                   7542:         my $path_and_file = $path_part.$file_part;
                   7543:         if ($path_part ne $path) {
1.800     albertel 7544:             push(@return_files, ($path_and_file));
1.572     banghart 7545:         }
                   7546:     }
1.800     albertel 7547:     close(OUT);
1.574     banghart 7548:     return (@return_files);
1.572     banghart 7549: }
                   7550: 
1.745     raeburn  7551: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7552: 
1.745     raeburn  7553: sub get_portfile_permissions {
                   7554:     my ($domain,$user) = @_;
1.613     albertel 7555:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7556:     my ($tmp)=keys(%current_permissions);
                   7557:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7558:     return \%current_permissions;
                   7559: }
                   7560: 
                   7561: #---------------------------------------------Get portfolio file access controls
                   7562: 
1.749     raeburn  7563: sub get_access_controls {
1.745     raeburn  7564:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7565:     my %access;
                   7566:     my $real_file = $file;
                   7567:     $file =~ s/\.meta$//;
1.745     raeburn  7568:     if (defined($file)) {
1.749     raeburn  7569:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7570:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7571:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7572:             }
                   7573:         }
1.745     raeburn  7574:     } else {
1.749     raeburn  7575:         foreach my $key (keys(%{$current_permissions})) {
                   7576:             if ($key =~ /\0accesscontrol$/) {
                   7577:                 if (defined($group)) {
                   7578:                     if ($key !~ m-^\Q$group\E/-) {
                   7579:                         next;
                   7580:                     }
                   7581:                 }
                   7582:                 my ($fullpath) = split(/\0/,$key);
                   7583:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7584:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7585:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7586:                     }
                   7587:                 }
                   7588:             }
                   7589:         }
                   7590:     }
                   7591:     return %access;
                   7592: }
                   7593: 
                   7594: sub modify_access_controls {
                   7595:     my ($file_name,$changes,$domain,$user)=@_;
                   7596:     my ($outcome,$deloutcome);
                   7597:     my %store_permissions;
                   7598:     my %new_values;
                   7599:     my %new_control;
                   7600:     my %translation;
                   7601:     my @deletions = ();
                   7602:     my $now = time;
                   7603:     if (exists($$changes{'activate'})) {
                   7604:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7605:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7606:             my $numnew = scalar(@newitems);
                   7607:             for (my $i=0; $i<$numnew; $i++) {
                   7608:                 my $newkey = $newitems[$i];
                   7609:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7610:                 if ($newkey =~ /^\d+:/) { 
                   7611:                     $newkey =~ s/^(\d+)/$newid/;
                   7612:                     $translation{$1} = $newid;
                   7613:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7614:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7615:                     $translation{$1} = $newid;
                   7616:                 }
1.749     raeburn  7617:                 $new_values{$file_name."\0".$newkey} = 
                   7618:                                           $$changes{'activate'}{$newitems[$i]};
                   7619:                 $new_control{$newkey} = $now;
                   7620:             }
                   7621:         }
                   7622:     }
                   7623:     my %todelete;
                   7624:     my %changed_items;
                   7625:     foreach my $action ('delete','update') {
                   7626:         if (exists($$changes{$action})) {
                   7627:             if (ref($$changes{$action}) eq 'HASH') {
                   7628:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7629:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7630:                     if ($action eq 'delete') { 
                   7631:                         $todelete{$itemnum} = 1;
                   7632:                     } else {
                   7633:                         $changed_items{$itemnum} = $key;
                   7634:                     }
                   7635:                 }
1.745     raeburn  7636:             }
                   7637:         }
1.749     raeburn  7638:     }
                   7639:     # get lock on access controls for file.
                   7640:     my $lockhash = {
                   7641:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7642:                                                        ':'.$env{'user.domain'},
                   7643:                    }; 
                   7644:     my $tries = 0;
                   7645:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7646:    
                   7647:     while (($gotlock ne 'ok') && $tries <3) {
                   7648:         $tries ++;
                   7649:         sleep 1;
                   7650:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7651:     }
                   7652:     if ($gotlock eq 'ok') {
                   7653:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7654:         my ($tmp)=keys(%curr_permissions);
                   7655:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7656:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7657:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7658:             if (ref($curr_controls) eq 'HASH') {
                   7659:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7660:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7661:                     if (defined($todelete{$itemnum})) {
                   7662:                         push(@deletions,$file_name."\0".$control_item);
                   7663:                     } else {
                   7664:                         if (defined($changed_items{$itemnum})) {
                   7665:                             $new_control{$changed_items{$itemnum}} = $now;
                   7666:                             push(@deletions,$file_name."\0".$control_item);
                   7667:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7668:                         } else {
                   7669:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7670:                         }
                   7671:                     }
1.745     raeburn  7672:                 }
                   7673:             }
                   7674:         }
1.970     raeburn  7675:         my ($group);
                   7676:         if (&is_course($domain,$user)) {
                   7677:             ($group,my $file) = split(/\//,$file_name,2);
                   7678:         }
1.749     raeburn  7679:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7680:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7681:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7682:         #  remove lock
                   7683:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7684:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7685:         my $sqlresult =
1.970     raeburn  7686:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7687:                                     $group);
1.749     raeburn  7688:     } else {
                   7689:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7690:     }
1.749     raeburn  7691:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7692: }
                   7693: 
1.827     raeburn  7694: sub make_public_indefinitely {
                   7695:     my ($requrl) = @_;
                   7696:     my $now = time;
                   7697:     my $action = 'activate';
                   7698:     my $aclnum = 0;
                   7699:     if (&is_portfolio_url($requrl)) {
                   7700:         my (undef,$udom,$unum,$file_name,$group) =
                   7701:             &parse_portfolio_url($requrl);
                   7702:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7703:         my %access_controls = &get_access_controls($current_perms,
                   7704:                                                    $group,$file_name);
                   7705:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7706:             my ($num,$scope,$end,$start) = 
                   7707:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7708:             if ($scope eq 'public') {
                   7709:                 if ($start <= $now && $end == 0) {
                   7710:                     $action = 'none';
                   7711:                 } else {
                   7712:                     $action = 'update';
                   7713:                     $aclnum = $num;
                   7714:                 }
                   7715:                 last;
                   7716:             }
                   7717:         }
                   7718:         if ($action eq 'none') {
                   7719:              return 'ok';
                   7720:         } else {
                   7721:             my %changes;
                   7722:             my $newend = 0;
                   7723:             my $newstart = $now;
                   7724:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7725:             $changes{$action}{$newkey} = {
                   7726:                 type => 'public',
                   7727:                 time => {
                   7728:                     start => $newstart,
                   7729:                     end   => $newend,
                   7730:                 },
                   7731:             };
                   7732:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7733:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7734:             return $outcome;
                   7735:         }
                   7736:     } else {
                   7737:         return 'invalid';
                   7738:     }
                   7739: }
                   7740: 
1.745     raeburn  7741: #------------------------------------------------------Get Marked as Read Only
                   7742: 
                   7743: sub get_marked_as_readonly {
                   7744:     my ($domain,$user,$what,$group) = @_;
                   7745:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7746:     my @readonly_files;
1.629     banghart 7747:     my $cmp1=$what;
                   7748:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7749:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7750:         if (defined($group)) {
                   7751:             if ($file_name !~ m-^\Q$group\E/-) {
                   7752:                 next;
                   7753:             }
                   7754:         }
1.561     banghart 7755:         if (ref($value) eq "ARRAY"){
                   7756:             foreach my $stored_what (@{$value}) {
1.629     banghart 7757:                 my $cmp2=$stored_what;
1.759     albertel 7758:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7759:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7760:                 }
1.629     banghart 7761:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7762:                     push(@readonly_files, $file_name);
1.745     raeburn  7763:                     last;
1.563     banghart 7764:                 } elsif (!defined($what)) {
                   7765:                     push(@readonly_files, $file_name);
1.745     raeburn  7766:                     last;
1.561     banghart 7767:                 }
                   7768:             }
1.745     raeburn  7769:         }
1.561     banghart 7770:     }
                   7771:     return @readonly_files;
                   7772: }
1.577     banghart 7773: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7774: 
1.577     banghart 7775: sub get_marked_as_readonly_hash {
1.745     raeburn  7776:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7777:     my %readonly_files;
1.745     raeburn  7778:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7779:         if (defined($group)) {
                   7780:             if ($file_name !~ m-^\Q$group\E/-) {
                   7781:                 next;
                   7782:             }
                   7783:         }
1.577     banghart 7784:         if (ref($value) eq "ARRAY"){
                   7785:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7786:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7787:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7788:                         if ($lock_descriptor eq 'graded') {
                   7789:                             $readonly_files{$file_name} = 'graded';
                   7790:                         } elsif ($lock_descriptor eq 'handback') {
                   7791:                             $readonly_files{$file_name} = 'handback';
                   7792:                         } else {
                   7793:                             if (!exists($readonly_files{$file_name})) {
                   7794:                                 $readonly_files{$file_name} = 'locked';
                   7795:                             }
                   7796:                         }
1.745     raeburn  7797:                     }
1.750     banghart 7798:                 } 
1.577     banghart 7799:             }
                   7800:         } 
                   7801:     }
                   7802:     return %readonly_files;
                   7803: }
1.559     banghart 7804: # ------------------------------------------------------------ Unmark as Read Only
                   7805: 
                   7806: sub unmark_as_readonly {
1.629     banghart 7807:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7808:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7809:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7810:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7811:     my $symb_crs = $what;
                   7812:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7813:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7814:     my ($tmp)=keys(%current_permissions);
                   7815:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7816:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7817:     foreach my $file (@readonly_files) {
1.759     albertel 7818: 	my $clean_file = &declutter_portfile($file);
                   7819: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7820: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7821:         my @new_locks;
                   7822:         my @del_keys;
                   7823:         if (ref($current_locks) eq "ARRAY"){
                   7824:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7825:                 my $compare=$locker;
1.749     raeburn  7826:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7827:                     $compare=join('',@{$locker});
1.746     raeburn  7828:                     if ($compare ne $symb_crs) {
                   7829:                         push(@new_locks, $locker);
                   7830:                     }
1.563     banghart 7831:                 }
                   7832:             }
1.650     albertel 7833:             if (scalar(@new_locks) > 0) {
1.563     banghart 7834:                 $current_permissions{$file} = \@new_locks;
                   7835:             } else {
                   7836:                 push(@del_keys, $file);
1.613     albertel 7837:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7838:                 delete($current_permissions{$file});
1.563     banghart 7839:             }
                   7840:         }
1.561     banghart 7841:     }
1.613     albertel 7842:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7843:     return;
                   7844: }
1.512     banghart 7845: 
1.17      www      7846: # ------------------------------------------------------------ Directory lister
                   7847: 
                   7848: sub dirlist {
1.955     raeburn  7849:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7850:     $uri=~s/^\///;
                   7851:     $uri=~s/\/$//;
1.253     stredwic 7852:     my ($udom, $uname);
1.955     raeburn  7853:     if ($getuserdir) {
1.253     stredwic 7854:         $udom = $userdomain;
                   7855:         $uname = $username;
1.955     raeburn  7856:     } else {
                   7857:         (undef,$udom,$uname)=split(/\//,$uri);
                   7858:         if(defined($userdomain)) {
                   7859:             $udom = $userdomain;
                   7860:         }
                   7861:         if(defined($username)) {
                   7862:             $uname = $username;
                   7863:         }
1.253     stredwic 7864:     }
1.955     raeburn  7865:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7866: 
1.955     raeburn  7867:     $dirRoot = $perlvar{'lonDocRoot'};
                   7868:     if (defined($getpropath)) {
                   7869:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7870:         $dirRoot =~ s/\/$//;
1.955     raeburn  7871:     } elsif (defined($getuserdir)) {
                   7872:         my $subdir=$uname.'__';
                   7873:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7874:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7875:                    ."/$udom/$subdir/$uname";
                   7876:     } elsif (defined($alternateRoot)) {
                   7877:         $dirRoot = $alternateRoot;
1.751     banghart 7878:     }
1.253     stredwic 7879: 
                   7880:     if($udom) {
                   7881:         if($uname) {
1.955     raeburn  7882:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7883:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7884:                               .':'.&escape($uname).':'.&escape($udom),
                   7885:                               &homeserver($uname,$udom));
                   7886:             if ($listing eq 'unknown_cmd') {
                   7887:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7888:                                   &homeserver($uname,$udom));
                   7889:             } else {
                   7890:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7891:             }
1.605     matthew  7892:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7893:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7894: 				  &homeserver($uname,$udom));
1.605     matthew  7895:                 @listing_results = split(/:/,$listing);
                   7896:             } else {
                   7897:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7898:             }
                   7899:             return @listing_results;
1.955     raeburn  7900:         } elsif(!$alternateRoot) {
1.800     albertel 7901:             my %allusers;
1.841     albertel 7902: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7903:  	    foreach my $tryserver (keys(%servers)) {
                   7904:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7905:                                   &escape($udom),$tryserver);
                   7906:                 if ($listing eq 'unknown_cmd') {
                   7907: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7908: 				      $udom, $tryserver);
                   7909:                 } else {
                   7910:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7911:                 }
1.841     albertel 7912: 		if ($listing eq 'unknown_cmd') {
                   7913: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7914: 				      $udom, $tryserver);
                   7915: 		    @listing_results = split(/:/,$listing);
                   7916: 		} else {
                   7917: 		    @listing_results =
                   7918: 			map { &unescape($_); } split(/:/,$listing);
                   7919: 		}
                   7920: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7921: 		    $listing_results[0] ne 'empty'       &&
                   7922: 		    $listing_results[0] ne 'con_lost') {
                   7923: 		    foreach my $line (@listing_results) {
                   7924: 			my ($entry) = split(/&/,$line,2);
                   7925: 			$allusers{$entry} = 1;
                   7926: 		    }
                   7927: 		}
1.253     stredwic 7928:             }
                   7929:             my $alluserstr='';
1.800     albertel 7930:             foreach my $user (sort(keys(%allusers))) {
                   7931:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7932:             }
                   7933:             $alluserstr=~s/:$//;
                   7934:             return split(/:/,$alluserstr);
                   7935:         } else {
1.800     albertel 7936:             return ('missing user name');
1.253     stredwic 7937:         }
1.955     raeburn  7938:     } elsif(!defined($getpropath)) {
1.841     albertel 7939:         my @all_domains = sort(&all_domains());
1.955     raeburn  7940:         foreach my $domain (@all_domains) {
                   7941:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7942:         }
                   7943:         return @all_domains;
                   7944:     } else {
1.800     albertel 7945:         return ('missing domain');
1.275     stredwic 7946:     }
                   7947: }
                   7948: 
                   7949: # --------------------------------------------- GetFileTimestamp
                   7950: # This function utilizes dirlist and returns the date stamp for
                   7951: # when it was last modified.  It will also return an error of -1
                   7952: # if an error occurs
                   7953: 
                   7954: sub GetFileTimestamp {
1.955     raeburn  7955:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7956:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7957:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7958:     my ($fileStat) = 
                   7959:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7960:                                  undef,$getuserdir);
1.275     stredwic 7961:     my @stats = split('&', $fileStat);
                   7962:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7963:         # @stats contains first the filename, then the stat output
                   7964:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7965:     } else {
                   7966:         return -1;
1.253     stredwic 7967:     }
1.26      www      7968: }
                   7969: 
1.712     albertel 7970: sub stat_file {
                   7971:     my ($uri) = @_;
1.787     albertel 7972:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7973: 
1.955     raeburn  7974:     my ($udom,$uname,$file);
1.712     albertel 7975:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7976: 	($udom,$uname,$file) =
1.811     albertel 7977: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7978: 	$file = 'userfiles/'.$file;
                   7979:     }
                   7980:     if ($uri =~ m-^/res/-) {
                   7981: 	($udom,$uname) = 
1.807     albertel 7982: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7983: 	$file = $uri;
                   7984:     }
                   7985: 
                   7986:     if (!$udom || !$uname || !$file) {
                   7987: 	# unable to handle the uri
                   7988: 	return ();
                   7989:     }
1.956     raeburn  7990:     my $getpropath;
                   7991:     if ($file =~ /^userfiles\//) {
                   7992:         $getpropath = 1;
                   7993:     }
1.955     raeburn  7994:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7995:     my @stats = split('&', $result);
1.721     banghart 7996:     
1.712     albertel 7997:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7998: 	shift(@stats); #filename is first
                   7999: 	return @stats;
                   8000:     }
                   8001:     return ();
                   8002: }
                   8003: 
1.26      www      8004: # -------------------------------------------------------- Value of a Condition
                   8005: 
1.713     albertel 8006: # gets the value of a specific preevaluated condition
                   8007: #    stored in the string  $env{user.state.<cid>}
                   8008: # or looks up a condition reference in the bighash and if if hasn't
                   8009: # already been evaluated recurses into docondval to get the value of
                   8010: # the condition, then memoizing it to 
                   8011: #   $env{user.state.<cid>.<condition>}
1.40      www      8012: sub directcondval {
                   8013:     my $number=shift;
1.620     albertel 8014:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8015: 	&Apache::lonuserstate::evalstate();
                   8016:     }
1.713     albertel 8017:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8018: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8019:     } elsif ($number =~ /^_/) {
                   8020: 	my $sub_condition;
                   8021: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8022: 		&GDBM_READER(),0640)) {
                   8023: 	    $sub_condition=$bighash{'conditions'.$number};
                   8024: 	    untie(%bighash);
                   8025: 	}
                   8026: 	my $value = &docondval($sub_condition);
1.949     raeburn  8027: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8028: 	return $value;
                   8029:     }
1.620     albertel 8030:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8031:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8032:     } else {
                   8033:        return 2;
                   8034:     }
                   8035: }
                   8036: 
1.713     albertel 8037: # get the collection of conditions for this resource
1.26      www      8038: sub condval {
                   8039:     my $condidx=shift;
1.54      www      8040:     my $allpathcond='';
1.713     albertel 8041:     foreach my $cond (split(/\|/,$condidx)) {
                   8042: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8043: 	    $allpathcond.=
                   8044: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8045: 	}
1.191     harris41 8046:     }
1.54      www      8047:     $allpathcond=~s/\|$//;
1.713     albertel 8048:     return &docondval($allpathcond);
                   8049: }
                   8050: 
                   8051: #evaluates an expression of conditions
                   8052: sub docondval {
                   8053:     my ($allpathcond) = @_;
                   8054:     my $result=0;
                   8055:     if ($env{'request.course.id'}
                   8056: 	&& defined($allpathcond)) {
                   8057: 	my $operand='|';
                   8058: 	my @stack;
                   8059: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8060: 	    if ($chunk eq '(') {
                   8061: 		push @stack,($operand,$result);
                   8062: 	    } elsif ($chunk eq ')') {
                   8063: 		my $before=pop @stack;
                   8064: 		if (pop @stack eq '&') {
                   8065: 		    $result=$result>$before?$before:$result;
                   8066: 		} else {
                   8067: 		    $result=$result>$before?$result:$before;
                   8068: 		}
                   8069: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8070: 		$operand=$chunk;
                   8071: 	    } else {
                   8072: 		my $new=directcondval($chunk);
                   8073: 		if ($operand eq '&') {
                   8074: 		    $result=$result>$new?$new:$result;
                   8075: 		} else {
                   8076: 		    $result=$result>$new?$result:$new;
                   8077: 		}
                   8078: 	    }
                   8079: 	}
1.26      www      8080:     }
                   8081:     return $result;
1.421     albertel 8082: }
                   8083: 
                   8084: # ---------------------------------------------------- Devalidate courseresdata
                   8085: 
                   8086: sub devalidatecourseresdata {
                   8087:     my ($coursenum,$coursedomain)=@_;
                   8088:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8089:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8090: }
                   8091: 
1.763     www      8092: 
1.200     www      8093: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8094: #
                   8095: #  Parameters:
                   8096: #      $coursenum    - Number of the course.
                   8097: #      $coursedomain - Domain at which the course was created.
                   8098: #  Returns:
                   8099: #     A hash of the course parameters along (I think) with timestamps
                   8100: #     and version info.
1.877     foxr     8101: 
1.624     albertel 8102: sub get_courseresdata {
                   8103:     my ($coursenum,$coursedomain)=@_;
1.200     www      8104:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8105:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8106:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8107:     my %dumpreply;
1.417     albertel 8108:     unless (defined($cached)) {
1.624     albertel 8109: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8110: 	$result=\%dumpreply;
1.251     albertel 8111: 	my ($tmp) = keys(%dumpreply);
                   8112: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8113: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8114: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8115: 	    return $tmp;
1.416     albertel 8116: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8117: 	    $result=undef;
1.599     albertel 8118: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8119: 	}
                   8120:     }
1.624     albertel 8121:     return $result;
                   8122: }
                   8123: 
1.633     albertel 8124: sub devalidateuserresdata {
                   8125:     my ($uname,$udom)=@_;
                   8126:     my $hashid="$udom:$uname";
                   8127:     &devalidate_cache_new('userres',$hashid);
                   8128: }
                   8129: 
1.624     albertel 8130: sub get_userresdata {
                   8131:     my ($uname,$udom)=@_;
                   8132:     #most student don\'t have any data set, check if there is some data
                   8133:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8134: 
                   8135:     my $hashid="$udom:$uname";
                   8136:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8137:     if (!defined($cached)) {
                   8138: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8139: 	$result=\%resourcedata;
                   8140: 	&do_cache_new('userres',$hashid,$result,600);
                   8141:     }
                   8142:     my ($tmp)=keys(%$result);
                   8143:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8144: 	return $result;
                   8145:     }
                   8146:     #error 2 occurs when the .db doesn't exist
                   8147:     if ($tmp!~/error: 2 /) {
1.672     albertel 8148: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8149: 		 " Trying to get resource data for ".
                   8150: 		 $uname." at ".$udom.": ".
                   8151: 		 $tmp."</font>");
                   8152:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8153: 	#&EXT_cache_set($udom,$uname);
                   8154: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8155: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8156:     }
                   8157:     return $tmp;
                   8158: }
1.879     foxr     8159: #----------------------------------------------- resdata - return resource data
                   8160: #  Purpose:
                   8161: #    Return resource data for either users or for a course.
                   8162: #  Parameters:
                   8163: #     $name      - Course/user name.
                   8164: #     $domain    - Name of the domain the user/course is registered on.
                   8165: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8166: #     @which     - Array of names of resources desired.
                   8167: #  Returns:
                   8168: #     The value of the first reasource in @which that is found in the
                   8169: #     resource hash.
                   8170: #  Exceptional Conditions:
                   8171: #     If the $type passed in is not valid (not the string 'course' or 
                   8172: #     'user', an undefined  reference is returned.
                   8173: #     If none of the resources are found, an undef is returned
1.624     albertel 8174: sub resdata {
                   8175:     my ($name,$domain,$type,@which)=@_;
                   8176:     my $result;
                   8177:     if ($type eq 'course') {
                   8178: 	$result=&get_courseresdata($name,$domain);
                   8179:     } elsif ($type eq 'user') {
                   8180: 	$result=&get_userresdata($name,$domain);
                   8181:     }
                   8182:     if (!ref($result)) { return $result; }    
1.251     albertel 8183:     foreach my $item (@which) {
1.927     albertel 8184: 	if (defined($result->{$item->[0]})) {
                   8185: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8186: 	}
1.250     albertel 8187:     }
1.291     albertel 8188:     return undef;
1.200     www      8189: }
                   8190: 
1.379     matthew  8191: #
                   8192: # EXT resource caching routines
                   8193: #
                   8194: 
                   8195: sub clear_EXT_cache_status {
1.383     albertel 8196:     &delenv('cache.EXT.');
1.379     matthew  8197: }
                   8198: 
                   8199: sub EXT_cache_status {
                   8200:     my ($target_domain,$target_user) = @_;
1.383     albertel 8201:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8202:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8203:         # We know already the user has no data
                   8204:         return 1;
                   8205:     } else {
                   8206:         return 0;
                   8207:     }
                   8208: }
                   8209: 
                   8210: sub EXT_cache_set {
                   8211:     my ($target_domain,$target_user) = @_;
1.383     albertel 8212:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8213:     #&appenv({$cachename => time});
1.379     matthew  8214: }
                   8215: 
1.28      www      8216: # --------------------------------------------------------- Value of a Variable
1.58      www      8217: sub EXT {
1.715     albertel 8218: 
1.395     albertel 8219:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8220:     unless ($varname) { return ''; }
1.218     albertel 8221:     #get real user name/domain, courseid and symb
                   8222:     my $courseid;
1.359     albertel 8223:     my $publicuser;
1.427     www      8224:     if ($symbparm) {
                   8225: 	$symbparm=&get_symb_from_alias($symbparm);
                   8226:     }
1.218     albertel 8227:     if (!($uname && $udom)) {
1.790     albertel 8228:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8229:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8230:     } else {
1.620     albertel 8231: 	$courseid=$env{'request.course.id'};
1.218     albertel 8232:     }
1.48      www      8233:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8234:     my $rest;
1.320     albertel 8235:     if (defined($therest[0])) {
1.48      www      8236:        $rest=join('.',@therest);
                   8237:     } else {
                   8238:        $rest='';
                   8239:     }
1.320     albertel 8240: 
1.57      www      8241:     my $qualifierrest=$qualifier;
                   8242:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8243:     my $spacequalifierrest=$space;
                   8244:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8245:     if ($realm eq 'user') {
1.48      www      8246: # --------------------------------------------------------------- user.resource
                   8247: 	if ($space eq 'resource') {
1.651     albertel 8248: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8249: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8250: 		 &&
1.744     albertel 8251: 		 ($symbparm eq &symbread()) ) {	
                   8252: 		# if we are in the middle of processing the resource the
                   8253: 		# get the value we are planning on committing
                   8254:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8255:                     return $Apache::lonhomework::results{$qualifierrest};
                   8256:                 } else {
                   8257:                     return $Apache::lonhomework::history{$qualifierrest};
                   8258:                 }
1.335     albertel 8259: 	    } else {
1.359     albertel 8260: 		my %restored;
1.620     albertel 8261: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8262: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8263: 		} else {
                   8264: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8265: 		}
1.335     albertel 8266: 		return $restored{$qualifierrest};
                   8267: 	    }
1.48      www      8268: # ----------------------------------------------------------------- user.access
                   8269:         } elsif ($space eq 'access') {
1.218     albertel 8270: 	    # FIXME - not supporting calls for a specific user
1.48      www      8271:             return &allowed($qualifier,$rest);
                   8272: # ------------------------------------------ user.preferences, user.environment
                   8273:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8274: 	    if (($uname eq $env{'user.name'}) &&
                   8275: 		($udom eq $env{'user.domain'})) {
                   8276: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8277: 	    } else {
1.359     albertel 8278: 		my %returnhash;
                   8279: 		if (!$publicuser) {
                   8280: 		    %returnhash=&userenvironment($udom,$uname,
                   8281: 						 $qualifierrest);
                   8282: 		}
1.218     albertel 8283: 		return $returnhash{$qualifierrest};
                   8284: 	    }
1.48      www      8285: # ----------------------------------------------------------------- user.course
                   8286:         } elsif ($space eq 'course') {
1.218     albertel 8287: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8288:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8289: # ------------------------------------------------------------------- user.role
                   8290:         } elsif ($space eq 'role') {
1.218     albertel 8291: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8292:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8293:             if ($qualifier eq 'value') {
                   8294: 		return $role;
                   8295:             } elsif ($qualifier eq 'extent') {
                   8296:                 return $where;
                   8297:             }
                   8298: # ----------------------------------------------------------------- user.domain
                   8299:         } elsif ($space eq 'domain') {
1.218     albertel 8300:             return $udom;
1.48      www      8301: # ------------------------------------------------------------------- user.name
                   8302:         } elsif ($space eq 'name') {
1.218     albertel 8303:             return $uname;
1.48      www      8304: # ---------------------------------------------------- Any other user namespace
1.29      www      8305:         } else {
1.359     albertel 8306: 	    my %reply;
                   8307: 	    if (!$publicuser) {
                   8308: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8309: 	    }
                   8310: 	    return $reply{$qualifierrest};
1.48      www      8311:         }
1.236     www      8312:     } elsif ($realm eq 'query') {
                   8313: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8314:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8315: 						[$spacequalifierrest]);
1.620     albertel 8316: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8317:    } elsif ($realm eq 'request') {
1.48      www      8318: # ------------------------------------------------------------- request.browser
                   8319:         if ($space eq 'browser') {
1.430     www      8320: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8321: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8322: 		    return 1;
                   8323: 		} else {
                   8324: 		    return 0;
                   8325: 		}
                   8326: 	    } else {
1.620     albertel 8327: 		return $env{'browser.'.$qualifier};
1.430     www      8328: 	    }
1.57      www      8329: # ------------------------------------------------------------ request.filename
                   8330:         } else {
1.620     albertel 8331:             return $env{'request.'.$spacequalifierrest};
1.29      www      8332:         }
1.28      www      8333:     } elsif ($realm eq 'course') {
1.48      www      8334: # ---------------------------------------------------------- course.description
1.620     albertel 8335:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8336:     } elsif ($realm eq 'resource') {
1.165     www      8337: 
1.620     albertel 8338: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8339: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8340: 	}
1.693     albertel 8341: 
                   8342: 	if ($space eq 'title') {
                   8343: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8344: 	    return &gettitle($symbparm);
                   8345: 	}
                   8346: 	
                   8347: 	if ($space eq 'map') {
                   8348: 	    my ($map) = &decode_symb($symbparm);
                   8349: 	    return &symbread($map);
                   8350: 	}
1.905     albertel 8351: 	if ($space eq 'filename') {
                   8352: 	    if ($symbparm) {
                   8353: 		return &clutter((&decode_symb($symbparm))[2]);
                   8354: 	    }
                   8355: 	    return &hreflocation('',$env{'request.filename'});
                   8356: 	}
1.693     albertel 8357: 
                   8358: 	my ($section, $group, @groups);
1.593     albertel 8359: 	my ($courselevelm,$courselevel);
1.539     albertel 8360: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8361: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8362: 
1.218     albertel 8363: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8364: 
1.60      www      8365: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8366: 	    my $symbp=$symbparm;
1.735     albertel 8367: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8368: 
                   8369: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8370: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8371: 
1.620     albertel 8372: 	    if (($env{'user.name'} eq $uname) &&
                   8373: 		($env{'user.domain'} eq $udom)) {
                   8374: 		$section=$env{'request.course.sec'};
1.733     raeburn  8375:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8376:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8377: 	    } else {
1.539     albertel 8378: 		if (! defined($usection)) {
1.551     albertel 8379: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8380: 		} else {
                   8381: 		    $section = $usection;
                   8382: 		}
1.733     raeburn  8383:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8384: 	    }
                   8385: 
                   8386: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8387: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8388: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8389: 
1.593     albertel 8390: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8391: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8392: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8393: 
1.60      www      8394: # ----------------------------------------------------------- first, check user
1.624     albertel 8395: 
                   8396: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8397: 				       ([$courselevelr,'resource'],
                   8398: 					[$courselevelm,'map'     ],
                   8399: 					[$courselevel, 'course'  ]));
1.931     albertel 8400: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8401: 
1.594     albertel 8402: # ------------------------------------------------ second, check some of course
1.684     raeburn  8403:             my $coursereply;
1.691     raeburn  8404:             if (@groups > 0) {
                   8405:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8406:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8407:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8408:             }
1.96      www      8409: 
1.684     raeburn  8410: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8411: 				  $env{'course.'.$courseid.'.domain'},
                   8412: 				  'course',
                   8413: 				  ([$seclevelr,   'resource'],
                   8414: 				   [$seclevelm,   'map'     ],
                   8415: 				   [$seclevel,    'course'  ],
                   8416: 				   [$courselevelr,'resource']));
                   8417: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8418: 
1.60      www      8419: # ------------------------------------------------------ third, check map parms
1.218     albertel 8420: 	    my %parmhash=();
                   8421: 	    my $thisparm='';
                   8422: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8423: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8424: 		    &GDBM_READER(),0640)) {
1.218     albertel 8425: 		$thisparm=$parmhash{$symbparm};
                   8426: 		untie(%parmhash);
                   8427: 	    }
1.927     albertel 8428: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8429: 	}
1.594     albertel 8430: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8431: 
1.218     albertel 8432: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8433: 	my $filename;
                   8434: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8435: 	if ($symbparm) {
1.409     www      8436: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8437: 	} else {
1.620     albertel 8438: 	    $filename=$env{'request.filename'};
1.282     albertel 8439: 	}
                   8440: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8441: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8442: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8443: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8444: 
1.927     albertel 8445: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8446: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8447: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8448: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8449: 				     $env{'course.'.$courseid.'.domain'},
                   8450: 				     'course',
1.927     albertel 8451: 				     ([$courselevelm,'map'   ],
                   8452: 				      [$courselevel, 'course']));
                   8453: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8454: 	}
1.145     www      8455: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8456: 	unless ($space eq '0') {
1.336     albertel 8457: 	    my @parts=split(/_/,$space);
                   8458: 	    my $id=pop(@parts);
                   8459: 	    my $part=join('_',@parts);
                   8460: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8461: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8462: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8463: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8464: 	}
1.395     albertel 8465: 	if ($recurse) { return undef; }
                   8466: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8467: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8468: # ---------------------------------------------------- Any other user namespace
                   8469:     } elsif ($realm eq 'environment') {
                   8470: # ----------------------------------------------------------------- environment
1.620     albertel 8471: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8472: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8473: 	} else {
1.770     albertel 8474: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8475: 		return '';
                   8476: 	    }
1.219     albertel 8477: 	    my %returnhash=&userenvironment($udom,$uname,
                   8478: 					    $spacequalifierrest);
                   8479: 	    return $returnhash{$spacequalifierrest};
                   8480: 	}
1.28      www      8481:     } elsif ($realm eq 'system') {
1.48      www      8482: # ----------------------------------------------------------------- system.time
                   8483: 	if ($space eq 'time') {
                   8484: 	    return time;
                   8485:         }
1.696     albertel 8486:     } elsif ($realm eq 'server') {
                   8487: # ----------------------------------------------------------------- system.time
                   8488: 	if ($space eq 'name') {
                   8489: 	    return $ENV{'SERVER_NAME'};
                   8490:         }
1.28      www      8491:     }
1.48      www      8492:     return '';
1.61      www      8493: }
                   8494: 
1.927     albertel 8495: sub get_reply {
                   8496:     my ($reply_value) = @_;
1.940     raeburn  8497:     if (ref($reply_value) eq 'ARRAY') {
                   8498:         if (wantarray) {
                   8499: 	    return @$reply_value;
                   8500:         }
                   8501:         return $reply_value->[0];
                   8502:     } else {
                   8503:         return $reply_value;
1.927     albertel 8504:     }
                   8505: }
                   8506: 
1.691     raeburn  8507: sub check_group_parms {
                   8508:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8509:     my @groupitems = ();
                   8510:     my $resultitem;
1.927     albertel 8511:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8512:     foreach my $group (@{$groups}) {
                   8513:         foreach my $level (@levels) {
1.927     albertel 8514:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8515:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8516:         }
                   8517:     }
                   8518:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8519:                             $env{'course.'.$courseid.'.domain'},
                   8520:                                      'course',@groupitems);
                   8521:     return $coursereply;
                   8522: }
                   8523: 
                   8524: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8525:     my ($courseid,@groups) = @_;
                   8526:     @groups = sort(@groups);
1.691     raeburn  8527:     return @groups;
                   8528: }
                   8529: 
1.395     albertel 8530: sub packages_tab_default {
                   8531:     my ($uri,$varname)=@_;
                   8532:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8533: 
                   8534:     my (@extension,@specifics,$do_default);
                   8535:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8536: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8537: 	if ($pack_type eq 'default') {
                   8538: 	    $do_default=1;
                   8539: 	} elsif ($pack_type eq 'extension') {
                   8540: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8541: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8542: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8543: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8544: 	}
                   8545:     }
                   8546:     # first look for a package that matches the requested part id
                   8547:     foreach my $package (@specifics) {
                   8548: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8549: 	next if ($pack_part ne $part);
                   8550: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8551: 	    return $packagetab{"$pack_type&$name&default"};
                   8552: 	}
                   8553:     }
                   8554:     # look for any possible matching non extension_ package
                   8555:     foreach my $package (@specifics) {
                   8556: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8557: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8558: 	    return $packagetab{"$pack_type&$name&default"};
                   8559: 	}
1.585     albertel 8560: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8561: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8562: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8563: 	}
                   8564:     }
1.738     albertel 8565:     # look for any posible extension_ match
                   8566:     foreach my $package (@extension) {
                   8567: 	my ($package,$pack_type)=@{$package};
                   8568: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8569: 	    return $packagetab{"$pack_type&$name&default"};
                   8570: 	}
                   8571: 	if (defined($packagetab{$package."&$name&default"})) {
                   8572: 	    return $packagetab{$package."&$name&default"};
                   8573: 	}
                   8574:     }
                   8575:     # look for a global default setting
                   8576:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8577: 	return $packagetab{"default&$name&default"};
                   8578:     }
1.395     albertel 8579:     return undef;
                   8580: }
                   8581: 
1.334     albertel 8582: sub add_prefix_and_part {
                   8583:     my ($prefix,$part)=@_;
                   8584:     my $keyroot;
                   8585:     if (defined($prefix) && $prefix !~ /^__/) {
                   8586: 	# prefix that has a part already
                   8587: 	$keyroot=$prefix;
                   8588:     } elsif (defined($prefix)) {
                   8589: 	# prefix that is missing a part
                   8590: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8591:     } else {
                   8592: 	# no prefix at all
                   8593: 	if (defined($part)) { $keyroot='_'.$part; }
                   8594:     }
                   8595:     return $keyroot;
                   8596: }
                   8597: 
1.71      www      8598: # ---------------------------------------------------------------- Get metadata
                   8599: 
1.599     albertel 8600: my %metaentry;
1.71      www      8601: sub metadata {
1.176     www      8602:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8603:     $uri=&declutter($uri);
1.288     albertel 8604:     # if it is a non metadata possible uri return quickly
1.529     albertel 8605:     if (($uri eq '') || 
                   8606: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8607: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.26  raeburn  8608:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8609: 	return undef;
                   8610:     }
                   8611:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8612: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8613: 	return undef;
1.288     albertel 8614:     }
1.73      www      8615:     my $filename=$uri;
                   8616:     $uri=~s/\.meta$//;
1.172     www      8617: #
                   8618: # Is the metadata already cached?
1.177     www      8619: # Look at timestamp of caching
1.172     www      8620: # Everything is cached by the main uri, libraries are never directly cached
                   8621: #
1.428     albertel 8622:     if (!defined($liburi)) {
1.599     albertel 8623: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8624: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8625:     }
                   8626:     {
1.172     www      8627: #
                   8628: # Is this a recursive call for a library?
                   8629: #
1.599     albertel 8630: #	if (! exists($metacache{$uri})) {
                   8631: #	    $metacache{$uri}={};
                   8632: #	}
1.924     albertel 8633: 	my $cachetime = 60*60;
1.171     www      8634:         if ($liburi) {
                   8635: 	    $liburi=&declutter($liburi);
                   8636:             $filename=$liburi;
1.401     bowersj2 8637:         } else {
1.599     albertel 8638: 	    &devalidate_cache_new('meta',$uri);
                   8639: 	    undef(%metaentry);
1.401     bowersj2 8640: 	}
1.140     www      8641:         my %metathesekeys=();
1.73      www      8642:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8643: 	my $metastring;
1.924     albertel 8644: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8645: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8646: 	    $metastring = 
1.929     albertel 8647: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8648: 					  ('grade_target' => 'meta'));
                   8649: 	    $cachetime = 1; # only want this cached in the child not long term
1.1056.4.26  raeburn  8650: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8651:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8652: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8653: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8654: 	    $metastring=&getfile($file);
1.489     albertel 8655: 	}
1.208     albertel 8656:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8657:         my $token;
1.140     www      8658:         undef %metathesekeys;
1.71      www      8659:         while ($token=$parser->get_token) {
1.339     albertel 8660: 	    if ($token->[0] eq 'S') {
                   8661: 		if (defined($token->[2]->{'package'})) {
1.172     www      8662: #
                   8663: # This is a package - get package info
                   8664: #
1.339     albertel 8665: 		    my $package=$token->[2]->{'package'};
                   8666: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8667: 		    if (defined($token->[2]->{'id'})) { 
                   8668: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8669: 		    }
1.599     albertel 8670: 		    if ($metaentry{':packages'}) {
                   8671: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8672: 		    } else {
1.599     albertel 8673: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8674: 		    }
1.736     albertel 8675: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8676: 			my $part=$keyroot;
                   8677: 			$part=~s/^\_//;
1.736     albertel 8678: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8679: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8680: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8681: 			    # ignore package.tab specified default values
                   8682:                             # here &package_tab_default() will fetch those
                   8683: 			    if ($subp eq 'default') { next; }
1.736     albertel 8684: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8685: 			    my $unikey;
                   8686: 			    if ($pack =~ /_0$/) {
                   8687: 				$unikey='parameter_0_'.$name;
                   8688: 				$part=0;
                   8689: 			    } else {
                   8690: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8691: 			    }
1.339     albertel 8692: 			    if ($subp eq 'display') {
                   8693: 				$value.=' [Part: '.$part.']';
                   8694: 			    }
1.599     albertel 8695: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8696: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8697: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8698: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8699: 			    }
1.599     albertel 8700: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8701: 				$metaentry{':'.$unikey}=
                   8702: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8703: 			    }
1.339     albertel 8704: 			}
                   8705: 		    }
                   8706: 		} else {
1.172     www      8707: #
                   8708: # This is not a package - some other kind of start tag
1.339     albertel 8709: #
                   8710: 		    my $entry=$token->[1];
                   8711: 		    my $unikey;
                   8712: 		    if ($entry eq 'import') {
                   8713: 			$unikey='';
                   8714: 		    } else {
                   8715: 			$unikey=$entry;
                   8716: 		    }
                   8717: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8718: 
                   8719: 		    if (defined($token->[2]->{'id'})) { 
                   8720: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8721: 		    }
1.175     www      8722: 
1.339     albertel 8723: 		    if ($entry eq 'import') {
1.175     www      8724: #
                   8725: # Importing a library here
1.339     albertel 8726: #
                   8727: 			if ($depthcount<20) {
                   8728: 			    my $location=$parser->get_text('/import');
                   8729: 			    my $dir=$filename;
                   8730: 			    $dir=~s|[^/]*$||;
                   8731: 			    $location=&filelocation($dir,$location);
1.736     albertel 8732: 			    my $metadata = 
                   8733: 				&metadata($uri,'keys', $location,$unikey,
                   8734: 					  $depthcount+1);
                   8735: 			    foreach my $meta (split(',',$metadata)) {
                   8736: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8737: 				$metathesekeys{$meta}=1;
1.339     albertel 8738: 			    }
                   8739: 			}
                   8740: 		    } else { 
                   8741: 			if (defined($token->[2]->{'name'})) { 
                   8742: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8743: 			}
                   8744: 			$metathesekeys{$unikey}=1;
1.736     albertel 8745: 			foreach my $param (@{$token->[3]}) {
                   8746: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8747: 				$token->[2]->{$param};
1.339     albertel 8748: 			}
                   8749: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8750: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8751: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8752: 		 # only ws inside the tag, and not in default, so use default
                   8753: 		 # as value
1.599     albertel 8754: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8755: 			} elsif ( $internaltext =~ /\S/ ) {
                   8756: 		  # something interesting inside the tag
                   8757: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8758: 			} else {
1.908     albertel 8759: 		  # no interesting values, don't set a default
1.339     albertel 8760: 			}
1.172     www      8761: # end of not-a-package not-a-library import
1.339     albertel 8762: 		    }
1.172     www      8763: # end of not-a-package start tag
1.339     albertel 8764: 		}
1.172     www      8765: # the next is the end of "start tag"
1.339     albertel 8766: 	    }
                   8767: 	}
1.483     albertel 8768: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8769: 	$extension = lc($extension);
                   8770: 	if ($extension eq 'htm') { $extension='html'; }
                   8771: 
1.737     albertel 8772: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8773: 	    #no specific packages #how's our extension
                   8774: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8775: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8776: 					 \%metathesekeys);
                   8777: 	}
1.883     albertel 8778: 
                   8779: 	if (!exists($metaentry{':packages'})
                   8780: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8781: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8782: 		#no specific packages well let's get default then
                   8783: 		if ($key!~/^default&/) { next; }
1.488     albertel 8784: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8785: 					     \%metathesekeys);
                   8786: 	    }
                   8787: 	}
1.338     www      8788: # are there custom rights to evaluate
1.599     albertel 8789: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8790: 
1.338     www      8791:     #
                   8792:     # Importing a rights file here
1.339     albertel 8793:     #
                   8794: 	    unless ($depthcount) {
1.599     albertel 8795: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8796: 		my $dir=$filename;
                   8797: 		$dir=~s|[^/]*$||;
                   8798: 		$location=&filelocation($dir,$location);
1.736     albertel 8799: 		my $rights_metadata =
                   8800: 		    &metadata($uri,'keys',$location,'_rights',
                   8801: 			      $depthcount+1);
                   8802: 		foreach my $rights (split(',',$rights_metadata)) {
                   8803: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8804: 		    $metathesekeys{$rights}=1;
1.339     albertel 8805: 		}
                   8806: 	    }
                   8807: 	}
1.737     albertel 8808: 	# uniqifiy package listing
                   8809: 	my %seen;
                   8810: 	my @uniq_packages =
                   8811: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8812: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8813: 
                   8814: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8815: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8816: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8817: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8818: # this is the end of "was not already recently cached
1.71      www      8819:     }
1.599     albertel 8820:     return $metaentry{':'.$what};
1.261     albertel 8821: }
                   8822: 
1.488     albertel 8823: sub metadata_create_package_def {
1.483     albertel 8824:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8825:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8826:     if ($subp eq 'default') { next; }
                   8827:     
1.599     albertel 8828:     if (defined($metaentry{':packages'})) {
                   8829: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8830:     } else {
1.599     albertel 8831: 	$metaentry{':packages'}=$package;
1.483     albertel 8832:     }
                   8833:     my $value=$packagetab{$key};
                   8834:     my $unikey;
                   8835:     $unikey='parameter_0_'.$name;
1.599     albertel 8836:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8837:     $$metathesekeys{$unikey}=1;
1.599     albertel 8838:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8839: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8840:     }
1.599     albertel 8841:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8842: 	$metaentry{':'.$unikey}=
                   8843: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8844:     }
                   8845: }
                   8846: 
1.261     albertel 8847: sub metadata_generate_part0 {
                   8848:     my ($metadata,$metacache,$uri) = @_;
                   8849:     my %allnames;
1.737     albertel 8850:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8851: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8852: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8853: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8854: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8855: 	    $allnames{$name}=$part;
                   8856: 	  }
                   8857: 	}
                   8858:     }
                   8859:     foreach my $name (keys(%allnames)) {
                   8860:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8861:       my $key=":parameter_0_$name";
1.261     albertel 8862:       $$metacache{"$key.part"}='0';
                   8863:       $$metacache{"$key.name"}=$name;
1.428     albertel 8864:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8865: 					   $allnames{$name}.'_'.$name.
                   8866: 					   '.type'};
1.428     albertel 8867:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8868: 			     '.display'};
1.644     www      8869:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8870:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8871:       $$metacache{"$key.display"}=$olddis;
                   8872:     }
1.71      www      8873: }
                   8874: 
1.764     albertel 8875: # ------------------------------------------------------ Devalidate title cache
                   8876: 
                   8877: sub devalidate_title_cache {
                   8878:     my ($url)=@_;
                   8879:     if (!$env{'request.course.id'}) { return; }
                   8880:     my $symb=&symbread($url);
                   8881:     if (!$symb) { return; }
                   8882:     my $key=$env{'request.course.id'}."\0".$symb;
                   8883:     &devalidate_cache_new('title',$key);
                   8884: }
                   8885: 
1.1014    droeschl 8886: # ------------------------------------------------- Get the title of a course
                   8887: 
                   8888: sub current_course_title {
                   8889:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8890: }
1.301     www      8891: # ------------------------------------------------- Get the title of a resource
                   8892: 
                   8893: sub gettitle {
                   8894:     my $urlsymb=shift;
                   8895:     my $symb=&symbread($urlsymb);
1.534     albertel 8896:     if ($symb) {
1.620     albertel 8897: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8898: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8899: 	if (defined($cached)) { 
                   8900: 	    return $result;
                   8901: 	}
1.534     albertel 8902: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8903: 	my $title='';
1.907     albertel 8904: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8905: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8906: 	} else {
                   8907: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8908: 		    &GDBM_READER(),0640)) {
                   8909: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8910: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8911: 		untie(%bighash);
                   8912: 	    }
1.534     albertel 8913: 	}
                   8914: 	$title=~s/\&colon\;/\:/gs;
                   8915: 	if ($title) {
1.599     albertel 8916: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8917: 	}
                   8918: 	$urlsymb=$url;
                   8919:     }
                   8920:     my $title=&metadata($urlsymb,'title');
                   8921:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8922:     return $title;
1.301     www      8923: }
1.613     albertel 8924: 
1.614     albertel 8925: sub get_slot {
                   8926:     my ($which,$cnum,$cdom)=@_;
                   8927:     if (!$cnum || !$cdom) {
1.790     albertel 8928: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8929: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8930: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8931:     }
1.703     albertel 8932:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8933:     my %slotinfo;
                   8934:     if (exists($remembered{$key})) {
                   8935: 	$slotinfo{$which} = $remembered{$key};
                   8936:     } else {
                   8937: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8938: 	&Apache::lonhomework::showhash(%slotinfo);
                   8939: 	my ($tmp)=keys(%slotinfo);
                   8940: 	if ($tmp=~/^error:/) { return (); }
                   8941: 	$remembered{$key} = $slotinfo{$which};
                   8942:     }
1.616     albertel 8943:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8944: 	return %{$slotinfo{$which}};
                   8945:     }
                   8946:     return $slotinfo{$which};
1.614     albertel 8947: }
1.31      www      8948: # ------------------------------------------------- Update symbolic store links
                   8949: 
                   8950: sub symblist {
                   8951:     my ($mapname,%newhash)=@_;
1.438     www      8952:     $mapname=&deversion(&declutter($mapname));
1.31      www      8953:     my %hash;
1.620     albertel 8954:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8955:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8956:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8957: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8958: 		next if ($url eq 'last_known'
                   8959: 			 && $env{'form.no_update_last_known'});
                   8960: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8961: 						    $newhash{$url}->[1],
                   8962: 						    $newhash{$url}->[0]);
1.191     harris41 8963:             }
1.31      www      8964:             if (untie(%hash)) {
                   8965: 		return 'ok';
                   8966:             }
                   8967:         }
                   8968:     }
                   8969:     return 'error';
1.212     www      8970: }
                   8971: 
                   8972: # --------------------------------------------------------------- Verify a symb
                   8973: 
                   8974: sub symbverify {
1.510     www      8975:     my ($symb,$thisurl)=@_;
                   8976:     my $thisfn=$thisurl;
1.439     www      8977:     $thisfn=&declutter($thisfn);
1.215     www      8978: # direct jump to resource in page or to a sequence - will construct own symbs
                   8979:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8980: # check URL part
1.409     www      8981:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8982: 
1.431     www      8983:     unless ($url eq $thisfn) { return 0; }
1.213     www      8984: 
1.216     www      8985:     $symb=&symbclean($symb);
1.510     www      8986:     $thisurl=&deversion($thisurl);
1.439     www      8987:     $thisfn=&deversion($thisfn);
1.213     www      8988: 
                   8989:     my %bighash;
                   8990:     my $okay=0;
1.431     www      8991: 
1.620     albertel 8992:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8993:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8994:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8995:             $thisurl =~ s/\?.+$//;
                   8996:         }
1.510     www      8997:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8998:         unless ($ids) { 
1.1056.4.21  raeburn  8999:            my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
                   9000:            $ids=$bighash{$idkey};
1.216     www      9001:         }
                   9002:         if ($ids) {
                   9003: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9004: 	    foreach my $id (split(/\,/,$ids)) {
                   9005: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9006:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9007:                    $symb =~ s/\?.+$//;
                   9008:                }
1.216     www      9009:                if (
                   9010:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9011:    eq $symb) { 
1.620     albertel 9012: 		   if (($env{'request.role.adv'}) ||
1.1056.4.20  raeburn  9013: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9014: 		       ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9015: 		       $okay=1; 
                   9016: 		   }
                   9017: 	       }
1.216     www      9018: 	   }
                   9019:         }
1.213     www      9020: 	untie(%bighash);
                   9021:     }
                   9022:     return $okay;
1.31      www      9023: }
                   9024: 
1.210     www      9025: # --------------------------------------------------------------- Clean-up symb
                   9026: 
                   9027: sub symbclean {
                   9028:     my $symb=shift;
1.568     albertel 9029:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9030: # remove version from map
                   9031:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9032: 
1.210     www      9033: # remove version from URL
                   9034:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9035: 
1.507     www      9036: # remove wrapper
                   9037: 
1.510     www      9038:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9039:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9040:     return $symb;
1.409     www      9041: }
                   9042: 
                   9043: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9044: 
                   9045: sub encode_symb {
                   9046:     my ($map,$resid,$url)=@_;
                   9047:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9048: }
1.409     www      9049: 
                   9050: sub decode_symb {
1.568     albertel 9051:     my $symb=shift;
                   9052:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9053:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9054:     return (&fixversion($map),$resid,&fixversion($url));
                   9055: }
                   9056: 
                   9057: sub fixversion {
                   9058:     my $fn=shift;
1.609     banghart 9059:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9060:     my %bighash;
                   9061:     my $uri=&clutter($fn);
1.620     albertel 9062:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9063: # is this cached?
1.599     albertel 9064:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9065:     if (defined($cached)) { return $result; }
                   9066: # unfortunately not cached, or expired
1.620     albertel 9067:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9068: 	    &GDBM_READER(),0640)) {
                   9069:  	if ($bighash{'version_'.$uri}) {
                   9070:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9071:  	    unless (($version eq 'mostrecent') || 
                   9072: 		    ($version==&getversion($uri))) {
1.440     www      9073:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9074:  	    }
                   9075:  	}
                   9076:  	untie %bighash;
1.413     www      9077:     }
1.599     albertel 9078:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9079: }
                   9080: 
                   9081: sub deversion {
                   9082:     my $url=shift;
                   9083:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9084:     return $url;
1.210     www      9085: }
                   9086: 
1.31      www      9087: # ------------------------------------------------------ Return symb list entry
                   9088: 
                   9089: sub symbread {
1.249     www      9090:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9091:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9092:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9093: # no filename provided? try from environment
1.44      www      9094:     unless ($thisfn) {
1.620     albertel 9095:         if ($env{'request.symb'}) {
                   9096: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9097: 	}
1.620     albertel 9098: 	$thisfn=$env{'request.filename'};
1.44      www      9099:     }
1.569     albertel 9100:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9101: # is that filename actually a symb? Verify, clean, and return
                   9102:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9103: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9104: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9105: 	}
1.242     www      9106:     }
1.44      www      9107:     $thisfn=declutter($thisfn);
1.31      www      9108:     my %hash;
1.37      www      9109:     my %bighash;
                   9110:     my $syval='';
1.620     albertel 9111:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9112:         my $targetfn = $thisfn;
1.609     banghart 9113:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9114:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9115:         }
1.687     albertel 9116: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9117: 	    $targetfn=$1;
                   9118: 	}
1.620     albertel 9119:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9120:                       &GDBM_READER(),0640)) {
1.481     raeburn  9121: 	    $syval=$hash{$targetfn};
1.37      www      9122:             untie(%hash);
                   9123:         }
                   9124: # ---------------------------------------------------------- There was an entry
                   9125:         if ($syval) {
1.601     albertel 9126: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9127: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9128: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9129: 		    #return $env{$cache_str}='';
1.601     albertel 9130: 		#}    
                   9131: 		#$syval.=$1;
                   9132: 	    #}
1.37      www      9133:         } else {
                   9134: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9135:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9136:                             &GDBM_READER(),0640)) {
1.37      www      9137: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9138:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9139:               unless ($ids) { 
                   9140:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9141:               }
                   9142:               unless ($ids) {
                   9143: # alias?
                   9144: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9145:               }
1.37      www      9146:               if ($ids) {
                   9147: # ------------------------------------------------------------------- Has ID(s)
                   9148:                  my @possibilities=split(/\,/,$ids);
1.39      www      9149:                  if ($#possibilities==0) {
                   9150: # ----------------------------------------------- There is only one possibility
1.37      www      9151: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9152: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9153: 						    $resid,$thisfn);
1.249     www      9154:                  } elsif (!$donotrecurse) {
1.39      www      9155: # ------------------------------------------ There is more than one possibility
                   9156:                      my $realpossible=0;
1.800     albertel 9157:                      foreach my $id (@possibilities) {
                   9158: 			 my $file=$bighash{'src_'.$id};
1.39      www      9159:                          if (&allowed('bre',$file)) {
1.800     albertel 9160:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9161:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9162: 				$realpossible++;
1.626     albertel 9163:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9164: 						    $resid,$thisfn);
1.39      www      9165:                             }
                   9166: 			 }
1.191     harris41 9167:                      }
1.39      www      9168: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9169:                  } else {
                   9170:                      $syval='';
1.37      www      9171:                  }
                   9172: 	      }
                   9173:               untie(%bighash)
1.481     raeburn  9174:            }
1.31      www      9175:         }
1.62      www      9176:         if ($syval) {
1.620     albertel 9177: 	    return $env{$cache_str}=$syval;
1.62      www      9178:         }
1.31      www      9179:     }
1.949     raeburn  9180:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9181:     return $env{$cache_str}='';
1.31      www      9182: }
                   9183: 
                   9184: # ---------------------------------------------------------- Return random seed
                   9185: 
1.32      www      9186: sub numval {
                   9187:     my $txt=shift;
                   9188:     $txt=~tr/A-J/0-9/;
                   9189:     $txt=~tr/a-j/0-9/;
                   9190:     $txt=~tr/K-T/0-9/;
                   9191:     $txt=~tr/k-t/0-9/;
                   9192:     $txt=~tr/U-Z/0-5/;
                   9193:     $txt=~tr/u-z/0-5/;
                   9194:     $txt=~s/\D//g;
1.564     albertel 9195:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9196:     return int($txt);
1.368     albertel 9197: }
                   9198: 
1.484     albertel 9199: sub numval2 {
                   9200:     my $txt=shift;
                   9201:     $txt=~tr/A-J/0-9/;
                   9202:     $txt=~tr/a-j/0-9/;
                   9203:     $txt=~tr/K-T/0-9/;
                   9204:     $txt=~tr/k-t/0-9/;
                   9205:     $txt=~tr/U-Z/0-5/;
                   9206:     $txt=~tr/u-z/0-5/;
                   9207:     $txt=~s/\D//g;
                   9208:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9209:     my $total;
                   9210:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9211:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9212:     return int($total);
                   9213: }
                   9214: 
1.575     albertel 9215: sub numval3 {
                   9216:     use integer;
                   9217:     my $txt=shift;
                   9218:     $txt=~tr/A-J/0-9/;
                   9219:     $txt=~tr/a-j/0-9/;
                   9220:     $txt=~tr/K-T/0-9/;
                   9221:     $txt=~tr/k-t/0-9/;
                   9222:     $txt=~tr/U-Z/0-5/;
                   9223:     $txt=~tr/u-z/0-5/;
                   9224:     $txt=~s/\D//g;
                   9225:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9226:     my $total;
                   9227:     foreach my $val (@txts) { $total+=$val; }
                   9228:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9229:     return $total;
                   9230: }
                   9231: 
1.675     albertel 9232: sub digest {
                   9233:     my ($data)=@_;
                   9234:     my $digest=&Digest::MD5::md5($data);
                   9235:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9236:     my ($e,$f);
                   9237:     {
                   9238:         use integer;
                   9239:         $e=($a+$b);
                   9240:         $f=($c+$d);
                   9241:         if ($_64bit) {
                   9242:             $e=(($e<<32)>>32);
                   9243:             $f=(($f<<32)>>32);
                   9244:         }
                   9245:     }
                   9246:     if (wantarray) {
                   9247: 	return ($e,$f);
                   9248:     } else {
                   9249: 	my $g;
                   9250: 	{
                   9251: 	    use integer;
                   9252: 	    $g=($e+$f);
                   9253: 	    if ($_64bit) {
                   9254: 		$g=(($g<<32)>>32);
                   9255: 	    }
                   9256: 	}
                   9257: 	return $g;
                   9258:     }
                   9259: }
                   9260: 
1.368     albertel 9261: sub latest_rnd_algorithm_id {
1.675     albertel 9262:     return '64bit5';
1.366     albertel 9263: }
1.32      www      9264: 
1.503     albertel 9265: sub get_rand_alg {
                   9266:     my ($courseid)=@_;
1.790     albertel 9267:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9268:     if ($courseid) {
1.620     albertel 9269: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9270:     }
                   9271:     return &latest_rnd_algorithm_id();
                   9272: }
                   9273: 
1.562     albertel 9274: sub validCODE {
                   9275:     my ($CODE)=@_;
                   9276:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9277:     return 0;
                   9278: }
                   9279: 
1.491     albertel 9280: sub getCODE {
1.620     albertel 9281:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9282:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9283: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9284: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9285: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9286:     }
                   9287:     return undef;
                   9288: }
                   9289: 
1.31      www      9290: sub rndseed {
1.155     albertel 9291:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9292:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9293:     if (!defined($symb)) {
1.366     albertel 9294: 	unless ($symb=$wsymb) { return time; }
                   9295:     }
                   9296:     if (!$courseid) { $courseid=$wcourseid; }
                   9297:     if (!$domain) { $domain=$wdomain; }
                   9298:     if (!$username) { $username=$wusername }
1.503     albertel 9299:     my $which=&get_rand_alg();
1.803     albertel 9300: 
1.491     albertel 9301:     if (defined(&getCODE())) {
1.675     albertel 9302: 	if ($which eq '64bit5') {
                   9303: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9304: 	} elsif ($which eq '64bit4') {
1.575     albertel 9305: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9306: 	} else {
                   9307: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9308: 	}
1.675     albertel 9309:     } elsif ($which eq '64bit5') {
                   9310: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9311:     } elsif ($which eq '64bit4') {
                   9312: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9313:     } elsif ($which eq '64bit3') {
                   9314: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9315:     } elsif ($which eq '64bit2') {
                   9316: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9317:     } elsif ($which eq '64bit') {
                   9318: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9319:     }
                   9320:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9321: }
                   9322: 
                   9323: sub rndseed_32bit {
                   9324:     my ($symb,$courseid,$domain,$username)=@_;
                   9325:     {
                   9326: 	use integer;
                   9327: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9328: 	my $symbseed=numval($symb) << 22;
                   9329: 	my $namechck=unpack("%32C*",$username) << 17;
                   9330: 	my $nameseed=numval($username) << 12;
                   9331: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9332: 	my $courseseed=unpack("%32C*",$courseid);
                   9333: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9334: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9335: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9336: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9337: 	return $num;
                   9338:     }
                   9339: }
                   9340: 
                   9341: sub rndseed_64bit {
                   9342:     my ($symb,$courseid,$domain,$username)=@_;
                   9343:     {
                   9344: 	use integer;
                   9345: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9346: 	my $symbseed=numval($symb) << 10;
                   9347: 	my $namechck=unpack("%32S*",$username);
                   9348: 	
                   9349: 	my $nameseed=numval($username) << 21;
                   9350: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9351: 	my $courseseed=unpack("%32S*",$courseid);
                   9352: 	
                   9353: 	my $num1=$symbchck+$symbseed+$namechck;
                   9354: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9355: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9356: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9357: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9358: 	return "$num1,$num2";
1.155     albertel 9359:     }
1.366     albertel 9360: }
                   9361: 
1.443     albertel 9362: sub rndseed_64bit2 {
                   9363:     my ($symb,$courseid,$domain,$username)=@_;
                   9364:     {
                   9365: 	use integer;
                   9366: 	# strings need to be an even # of cahracters long, it it is odd the
                   9367:         # last characters gets thrown away
                   9368: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9369: 	my $symbseed=numval($symb) << 10;
                   9370: 	my $namechck=unpack("%32S*",$username.' ');
                   9371: 	
                   9372: 	my $nameseed=numval($username) << 21;
1.501     albertel 9373: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9374: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9375: 	
                   9376: 	my $num1=$symbchck+$symbseed+$namechck;
                   9377: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9378: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9379: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9380: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9381: 	return "$num1,$num2";
                   9382:     }
                   9383: }
                   9384: 
                   9385: sub rndseed_64bit3 {
                   9386:     my ($symb,$courseid,$domain,$username)=@_;
                   9387:     {
                   9388: 	use integer;
                   9389: 	# strings need to be an even # of cahracters long, it it is odd the
                   9390:         # last characters gets thrown away
                   9391: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9392: 	my $symbseed=numval2($symb) << 10;
                   9393: 	my $namechck=unpack("%32S*",$username.' ');
                   9394: 	
                   9395: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9396: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9397: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9398: 	
                   9399: 	my $num1=$symbchck+$symbseed+$namechck;
                   9400: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9401: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9402: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9403: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9404: 	
1.503     albertel 9405: 	return "$num1:$num2";
1.443     albertel 9406:     }
                   9407: }
                   9408: 
1.575     albertel 9409: sub rndseed_64bit4 {
                   9410:     my ($symb,$courseid,$domain,$username)=@_;
                   9411:     {
                   9412: 	use integer;
                   9413: 	# strings need to be an even # of cahracters long, it it is odd the
                   9414:         # last characters gets thrown away
                   9415: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9416: 	my $symbseed=numval3($symb) << 10;
                   9417: 	my $namechck=unpack("%32S*",$username.' ');
                   9418: 	
                   9419: 	my $nameseed=numval3($username) << 21;
                   9420: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9421: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9422: 	
                   9423: 	my $num1=$symbchck+$symbseed+$namechck;
                   9424: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9425: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9426: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9427: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9428: 	
                   9429: 	return "$num1:$num2";
                   9430:     }
                   9431: }
                   9432: 
1.675     albertel 9433: sub rndseed_64bit5 {
                   9434:     my ($symb,$courseid,$domain,$username)=@_;
                   9435:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9436:     return "$num1:$num2";
                   9437: }
                   9438: 
1.366     albertel 9439: sub rndseed_CODE_64bit {
                   9440:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9441:     {
1.366     albertel 9442: 	use integer;
1.443     albertel 9443: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9444: 	my $symbseed=numval2($symb);
1.491     albertel 9445: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9446: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9447: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9448: 	my $num1=$symbseed+$CODEchck;
                   9449: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9450: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9451: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9452: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9453: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9454: 	return "$num1:$num2";
1.366     albertel 9455:     }
                   9456: }
                   9457: 
1.575     albertel 9458: sub rndseed_CODE_64bit4 {
                   9459:     my ($symb,$courseid,$domain,$username)=@_;
                   9460:     {
                   9461: 	use integer;
                   9462: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9463: 	my $symbseed=numval3($symb);
                   9464: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9465: 	my $CODEseed=numval3(&getCODE());
                   9466: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9467: 	my $num1=$symbseed+$CODEchck;
                   9468: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9469: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9470: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9471: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9472: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9473: 	return "$num1:$num2";
                   9474:     }
                   9475: }
                   9476: 
1.675     albertel 9477: sub rndseed_CODE_64bit5 {
                   9478:     my ($symb,$courseid,$domain,$username)=@_;
                   9479:     my $code = &getCODE();
                   9480:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9481:     return "$num1:$num2";
                   9482: }
                   9483: 
1.366     albertel 9484: sub setup_random_from_rndseed {
                   9485:     my ($rndseed)=@_;
1.503     albertel 9486:     if ($rndseed =~/([,:])/) {
                   9487: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9488: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9489:     } else {
                   9490: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9491:     }
1.36      albertel 9492: }
                   9493: 
1.474     albertel 9494: sub latest_receipt_algorithm_id {
1.835     albertel 9495:     return 'receipt3';
1.474     albertel 9496: }
                   9497: 
1.480     www      9498: sub recunique {
                   9499:     my $fucourseid=shift;
                   9500:     my $unique;
1.835     albertel 9501:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9502: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9503: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9504:     } else {
                   9505: 	$unique=$perlvar{'lonReceipt'};
                   9506:     }
                   9507:     return unpack("%32C*",$unique);
                   9508: }
                   9509: 
                   9510: sub recprefix {
                   9511:     my $fucourseid=shift;
                   9512:     my $prefix;
1.835     albertel 9513:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9514: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9515: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9516:     } else {
                   9517: 	$prefix=$perlvar{'lonHostID'};
                   9518:     }
                   9519:     return unpack("%32C*",$prefix);
                   9520: }
                   9521: 
1.76      www      9522: sub ireceipt {
1.474     albertel 9523:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9524: 
                   9525:     my $return =&recprefix($fucourseid).'-';
                   9526: 
                   9527:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9528: 	$env{'request.state'} eq 'construct') {
                   9529: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9530: 	return $return;
                   9531:     }
                   9532: 
1.76      www      9533:     my $cuname=unpack("%32C*",$funame);
                   9534:     my $cudom=unpack("%32C*",$fudom);
                   9535:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9536:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9537:     my $cunique=&recunique($fucourseid);
1.474     albertel 9538:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9539:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9540: 
1.790     albertel 9541: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9542: 			       
                   9543: 	$return.= ($cunique%$cuname+
                   9544: 		   $cunique%$cudom+
                   9545: 		   $cusymb%$cuname+
                   9546: 		   $cusymb%$cudom+
                   9547: 		   $cucourseid%$cuname+
                   9548: 		   $cucourseid%$cudom+
                   9549: 		   $cpart%$cuname+
                   9550: 		   $cpart%$cudom);
                   9551:     } else {
                   9552: 	$return.= ($cunique%$cuname+
                   9553: 		   $cunique%$cudom+
                   9554: 		   $cusymb%$cuname+
                   9555: 		   $cusymb%$cudom+
                   9556: 		   $cucourseid%$cuname+
                   9557: 		   $cucourseid%$cudom);
                   9558:     }
                   9559:     return $return;
1.76      www      9560: }
                   9561: 
                   9562: sub receipt {
1.474     albertel 9563:     my ($part)=@_;
1.790     albertel 9564:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9565:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9566: }
1.260     ng       9567: 
1.790     albertel 9568: sub whichuser {
                   9569:     my ($passedsymb)=@_;
                   9570:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9571:     if (defined($env{'form.grade_symb'})) {
                   9572: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9573: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9574: 	if (!$allowed &&
                   9575: 	    exists($env{'request.course.sec'}) &&
                   9576: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9577: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9578: 			      '/'.$env{'request.course.sec'});
                   9579: 	}
                   9580: 	if ($allowed) {
                   9581: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9582: 	    $courseid=$tmp_courseid;
                   9583: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9584: 	    ($name)=&get_env_multiple('form.grade_username');
                   9585: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9586: 	}
                   9587:     }
                   9588:     if (!$passedsymb) {
                   9589: 	$symb=&symbread();
                   9590:     } else {
                   9591: 	$symb=$passedsymb;
                   9592:     }
                   9593:     $courseid=$env{'request.course.id'};
                   9594:     $domain=$env{'user.domain'};
                   9595:     $name=$env{'user.name'};
                   9596:     if ($name eq 'public' && $domain eq 'public') {
                   9597: 	if (!defined($env{'form.username'})) {
                   9598: 	    $env{'form.username'}.=time.rand(10000000);
                   9599: 	}
                   9600: 	$name.=$env{'form.username'};
                   9601:     }
                   9602:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9603: 
                   9604: }
                   9605: 
1.36      albertel 9606: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9607: # returns either the contents of the file or 
                   9608: # -1 if the file doesn't exist
1.481     raeburn  9609: #
                   9610: # if the target is a file that was uploaded via DOCS, 
                   9611: # a check will be made to see if a current copy exists on the local server,
                   9612: # if it does this will be served, otherwise a copy will be retrieved from
                   9613: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9614: # the local server.   
1.472     albertel 9615: 
1.36      albertel 9616: sub getfile {
1.538     albertel 9617:     my ($file) = @_;
1.609     banghart 9618:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9619:     &repcopy($file);
                   9620:     return &readfile($file);
                   9621: }
                   9622: 
                   9623: sub repcopy_userfile {
                   9624:     my ($file)=@_;
1.609     banghart 9625:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9626:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9627:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9628: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9629:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9630:     if (-e "$file") {
1.828     www      9631: # we already have a local copy, check it out
1.538     albertel 9632: 	my @fileinfo = stat($file);
1.828     www      9633: 	my $rtncode;
                   9634: 	my $info;
1.538     albertel 9635: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9636: 	if ($lwpresp ne 'ok') {
1.828     www      9637: # there is no such file anymore, even though we had a local copy
1.482     albertel 9638: 	    if ($rtncode eq '404') {
1.538     albertel 9639: 		unlink($file);
1.482     albertel 9640: 	    }
                   9641: 	    return -1;
                   9642: 	}
                   9643: 	if ($info < $fileinfo[9]) {
1.828     www      9644: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9645: 	    return 'ok';
1.828     www      9646: 	} else {
                   9647: # the file is outdated, get rid of it
                   9648: 	    unlink($file);
1.482     albertel 9649: 	}
1.828     www      9650:     }
                   9651: # one way or the other, at this point, we don't have the file
                   9652: # construct the correct path for the file
                   9653:     my @parts = ($cdom,$cnum); 
                   9654:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9655: 	push @parts, split(/\//,$1);
                   9656:     }
                   9657:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9658:     foreach my $part (@parts) {
                   9659: 	$path .= '/'.$part;
                   9660: 	if (!-e $path) {
                   9661: 	    mkdir($path,0770);
1.482     albertel 9662: 	}
                   9663:     }
1.828     www      9664: # now the path exists for sure
                   9665: # get a user agent
                   9666:     my $ua=new LWP::UserAgent;
                   9667:     my $transferfile=$file.'.in.transfer';
                   9668: # FIXME: this should flock
                   9669:     if (-e $transferfile) { return 'ok'; }
                   9670:     my $request;
                   9671:     $uri=~s/^\///;
1.980     raeburn  9672:     my $homeserver = &homeserver($cnum,$cdom);
                   9673:     my $protocol = $protocol{$homeserver};
                   9674:     $protocol = 'http' if ($protocol ne 'https');
                   9675:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9676:     my $response=$ua->request($request,$transferfile);
                   9677: # did it work?
                   9678:     if ($response->is_error()) {
                   9679: 	unlink($transferfile);
                   9680: 	&logthis("Userfile repcopy failed for $uri");
                   9681: 	return -1;
                   9682:     }
                   9683: # worked, rename the transfer file
                   9684:     rename($transferfile,$file);
1.607     raeburn  9685:     return 'ok';
1.481     raeburn  9686: }
                   9687: 
1.517     albertel 9688: sub tokenwrapper {
                   9689:     my $uri=shift;
1.980     raeburn  9690:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9691:     $uri=~s|^/||;
1.620     albertel 9692:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9693:     my $token=$1;
1.552     albertel 9694:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9695:     if ($udom && $uname && $file) {
                   9696: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9697:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9698:         my $homeserver = &homeserver($uname,$udom);
                   9699:         my $protocol = $protocol{$homeserver};
                   9700:         $protocol = 'http' if ($protocol ne 'https');
                   9701:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9702:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9703:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9704:     } else {
                   9705:         return '/adm/notfound.html';
                   9706:     }
                   9707: }
                   9708: 
1.828     www      9709: # call with reqtype HEAD: get last modification time
                   9710: # call with reqtype GET: get the file contents
                   9711: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9712: #
1.481     raeburn  9713: sub getuploaded {
                   9714:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9715:     $uri=~s/^\///;
1.980     raeburn  9716:     my $homeserver = &homeserver($cnum,$cdom);
                   9717:     my $protocol = $protocol{$homeserver};
                   9718:     $protocol = 'http' if ($protocol ne 'https');
                   9719:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9720:     my $ua=new LWP::UserAgent;
                   9721:     my $request=new HTTP::Request($reqtype,$uri);
                   9722:     my $response=$ua->request($request);
                   9723:     $$rtncode = $response->code;
1.482     albertel 9724:     if (! $response->is_success()) {
                   9725: 	return 'failed';
                   9726:     }      
                   9727:     if ($reqtype eq 'HEAD') {
1.486     www      9728: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9729:     } elsif ($reqtype eq 'GET') {
                   9730: 	$$info = $response->content;
1.472     albertel 9731:     }
1.482     albertel 9732:     return 'ok';
1.36      albertel 9733: }
                   9734: 
1.481     raeburn  9735: sub readfile {
                   9736:     my $file = shift;
                   9737:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9738:     my $fh;
                   9739:     open($fh,"<$file");
                   9740:     my $a='';
1.800     albertel 9741:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9742:     return $a;
                   9743: }
                   9744: 
1.36      albertel 9745: sub filelocation {
1.590     banghart 9746:     my ($dir,$file) = @_;
                   9747:     my $location;
                   9748:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9749: 
                   9750:     if ($file =~ m-^/adm/-) {
                   9751: 	$file=~s-^/adm/wrapper/-/-;
                   9752: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9753:     }
1.882     albertel 9754: 
1.590     banghart 9755:     if ($file=~m:^/~:) { # is a contruction space reference
                   9756:         $location = $file;
                   9757:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9758:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9759: 	# is a correct contruction space reference
                   9760:         $location = $file;
1.956     raeburn  9761:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9762:         $location = $file;
1.609     banghart 9763:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9764:         my ($udom,$uname,$filename)=
1.811     albertel 9765:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9766:         my $home=&homeserver($uname,$udom);
                   9767:         my $is_me=0;
                   9768:         my @ids=&current_machine_ids();
                   9769:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9770:         if ($is_me) {
1.955     raeburn  9771:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9772:         } else {
                   9773:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9774:   	      $udom.'/'.$uname.'/'.$filename;
                   9775:         }
1.882     albertel 9776:     } elsif ($file =~ m-^/adm/-) {
                   9777: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9778:     } else {
                   9779:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9780:         $file=~s:^/res/:/:;
                   9781:         if ( !( $file =~ m:^/:) ) {
                   9782:             $location = $dir. '/'.$file;
                   9783:         } else {
                   9784:             $location = '/home/httpd/html/res'.$file;
                   9785:         }
1.59      albertel 9786:     }
1.590     banghart 9787:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9788:     while ($location=~m{/\.\./}) {
                   9789: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9790: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9791: 	} else {
                   9792: 	    $location=~ s{/\.\./}{/}g;
                   9793: 	}
                   9794:     } #remove dir/..
1.590     banghart 9795:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9796:     return $location;
1.46      www      9797: }
1.36      albertel 9798: 
1.46      www      9799: sub hreflocation {
                   9800:     my ($dir,$file)=@_;
1.980     raeburn  9801:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9802: 	$file=filelocation($dir,$file);
1.700     albertel 9803:     } elsif ($file=~m-^/adm/-) {
                   9804: 	$file=~s-^/adm/wrapper/-/-;
                   9805: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9806:     }
                   9807:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9808: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9809:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9810: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9811:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9812: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9813: 	    -/uploaded/$1/$2/-x;
1.46      www      9814:     }
1.913     albertel 9815:     if ($file=~ m{^/userfiles/}) {
                   9816: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9817:     }
1.462     albertel 9818:     return $file;
1.465     albertel 9819: }
                   9820: 
                   9821: sub current_machine_domains {
1.853     albertel 9822:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9823: }
                   9824: 
                   9825: sub machine_domains {
                   9826:     my ($hostname) = @_;
1.465     albertel 9827:     my @domains;
1.838     albertel 9828:     my %hostname = &all_hostnames();
1.465     albertel 9829:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9830: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9831: 	if ($hostname eq $name) {
1.844     albertel 9832: 	    push(@domains,&host_domain($id));
1.465     albertel 9833: 	}
                   9834:     }
                   9835:     return @domains;
                   9836: }
                   9837: 
                   9838: sub current_machine_ids {
1.853     albertel 9839:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9840: }
                   9841: 
                   9842: sub machine_ids {
                   9843:     my ($hostname) = @_;
                   9844:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9845:     my @ids;
1.888     albertel 9846:     my %name_to_host = &all_names();
1.889     albertel 9847:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9848: 	return @{ $name_to_host{$hostname} };
                   9849:     }
                   9850:     return;
1.31      www      9851: }
                   9852: 
1.824     raeburn  9853: sub additional_machine_domains {
                   9854:     my @domains;
                   9855:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9856:     while( my $line = <$fh>) {
                   9857:         $line =~ s/\s//g;
                   9858:         push(@domains,$line);
                   9859:     }
                   9860:     return @domains;
                   9861: }
                   9862: 
                   9863: sub default_login_domain {
                   9864:     my $domain = $perlvar{'lonDefDomain'};
                   9865:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9866:     foreach my $posdom (&current_machine_domains(),
                   9867:                         &additional_machine_domains()) {
                   9868:         if (lc($posdom) eq lc($testdomain)) {
                   9869:             $domain=$posdom;
                   9870:             last;
                   9871:         }
                   9872:     }
                   9873:     return $domain;
                   9874: }
                   9875: 
1.31      www      9876: # ------------------------------------------------------------- Declutters URLs
                   9877: 
                   9878: sub declutter {
                   9879:     my $thisfn=shift;
1.569     albertel 9880:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9881:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9882:     $thisfn=~s/^\///;
1.697     albertel 9883:     $thisfn=~s|^adm/wrapper/||;
                   9884:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9885:     $thisfn=~s/^res\///;
1.1032    raeburn  9886:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9887:         $thisfn=~s/\?.+$//;
                   9888:     }
1.268     www      9889:     return $thisfn;
                   9890: }
                   9891: 
                   9892: # ------------------------------------------------------------- Clutter up URLs
                   9893: 
                   9894: sub clutter {
                   9895:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9896:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9897: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9898:        $thisfn='/res'.$thisfn; 
                   9899:     }
1.1031    raeburn  9900:     if ($thisfn !~m|^/adm|) {
                   9901: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9902: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9903: 	} else {
                   9904: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9905: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9906: 	    if ($embstyle eq 'ssi'
                   9907: 		|| ($embstyle eq 'hdn')
                   9908: 		|| ($embstyle eq 'rat')
                   9909: 		|| ($embstyle eq 'prv')
                   9910: 		|| ($embstyle eq 'ign')) {
                   9911: 		#do nothing with these
                   9912: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9913: 		|| ($embstyle eq 'emb')
                   9914: 		|| ($embstyle eq 'wrp')) {
                   9915: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9916: 	    } elsif ($embstyle eq 'unk'
                   9917: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9918: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9919: 	    } else {
1.718     www      9920: #		&logthis("Got a blank emb style");
1.695     albertel 9921: 	    }
1.694     albertel 9922: 	}
                   9923:     }
1.31      www      9924:     return $thisfn;
1.12      www      9925: }
                   9926: 
1.787     albertel 9927: sub clutter_with_no_wrapper {
                   9928:     my $uri = &clutter(shift);
                   9929:     if ($uri =~ m-^/adm/-) {
                   9930: 	$uri =~ s-^/adm/wrapper/-/-;
                   9931: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9932:     }
                   9933:     return $uri;
                   9934: }
                   9935: 
1.557     albertel 9936: sub freeze_escape {
                   9937:     my ($value)=@_;
                   9938:     if (ref($value)) {
                   9939: 	$value=&nfreeze($value);
                   9940: 	return '__FROZEN__'.&escape($value);
                   9941:     }
                   9942:     return &escape($value);
                   9943: }
                   9944: 
1.11      www      9945: 
1.557     albertel 9946: sub thaw_unescape {
                   9947:     my ($value)=@_;
                   9948:     if ($value =~ /^__FROZEN__/) {
                   9949: 	substr($value,0,10,undef);
                   9950: 	$value=&unescape($value);
                   9951: 	return &thaw($value);
                   9952:     }
                   9953:     return &unescape($value);
                   9954: }
                   9955: 
1.436     albertel 9956: sub correct_line_ends {
                   9957:     my ($result)=@_;
                   9958:     $$result =~s/\r\n/\n/mg;
                   9959:     $$result =~s/\r/\n/mg;
1.415     albertel 9960: }
1.1       albertel 9961: # ================================================================ Main Program
                   9962: 
1.184     www      9963: sub goodbye {
1.204     albertel 9964:    &logthis("Starting Shut down");
1.443     albertel 9965: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9966:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9967: #converted
1.599     albertel 9968: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9969:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9970: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9971: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9972: #1.1 only
1.870     albertel 9973: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9974: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9975: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9976: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9977:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9978:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9979:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9980:    &flushcourselogs();
                   9981:    &logthis("Shutting down");
                   9982: }
                   9983: 
1.852     albertel 9984: sub get_dns {
1.869     albertel 9985:     my ($url,$func,$ignore_cache) = @_;
                   9986:     if (!$ignore_cache) {
                   9987: 	my ($content,$cached)=
                   9988: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9989: 	if ($cached) {
                   9990: 	    &$func($content);
                   9991: 	    return;
                   9992: 	}
                   9993:     }
                   9994: 
                   9995:     my %alldns;
1.852     albertel 9996:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9997:     foreach my $dns (<$config>) {
                   9998: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9999:         my $line = $1;
                   10000:         my ($host,$protocol) = split(/:/,$line);
                   10001:         if ($protocol ne 'https') {
                   10002:             $protocol = 'http';
                   10003:         }
                   10004: 	$alldns{$host} = $protocol;
1.869     albertel 10005:     }
                   10006:     while (%alldns) {
                   10007: 	my ($dns) = keys(%alldns);
1.852     albertel 10008: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10009: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10010: 	my $response=$ua->request($request);
1.979     raeburn  10011:         delete($alldns{$dns});
1.852     albertel 10012: 	next if ($response->is_error());
                   10013: 	my @content = split("\n",$response->content);
1.869     albertel 10014: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10015: 	&$func(\@content);
1.869     albertel 10016: 	return;
1.852     albertel 10017:     }
                   10018:     close($config);
1.871     albertel 10019:     my $which = (split('/',$url))[3];
                   10020:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10021:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10022:     my @content = <$config>;
                   10023:     &$func(\@content);
                   10024:     return;
1.852     albertel 10025: }
1.327     albertel 10026: # ------------------------------------------------------------ Read domain file
                   10027: {
1.852     albertel 10028:     my $loaded;
1.846     albertel 10029:     my %domain;
                   10030: 
1.852     albertel 10031:     sub parse_domain_tab {
                   10032: 	my ($lines) = @_;
                   10033: 	foreach my $line (@$lines) {
                   10034: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10035: 
1.846     albertel 10036: 	    chomp($line);
1.852     albertel 10037: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10038: 	    my %this_domain;
                   10039: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10040: 			       'lang_def', 'city', 'longi', 'lati',
                   10041: 			       'primary') {
                   10042: 		$this_domain{$field} = shift(@elements);
                   10043: 	    }
                   10044: 	    $domain{$name} = \%this_domain;
1.852     albertel 10045: 	}
                   10046:     }
1.864     albertel 10047: 
                   10048:     sub reset_domain_info {
                   10049: 	undef($loaded);
                   10050: 	undef(%domain);
                   10051:     }
                   10052: 
1.852     albertel 10053:     sub load_domain_tab {
1.869     albertel 10054: 	my ($ignore_cache) = @_;
                   10055: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10056: 	my $fh;
                   10057: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10058: 	    my @lines = <$fh>;
                   10059: 	    &parse_domain_tab(\@lines);
1.448     albertel 10060: 	}
1.852     albertel 10061: 	close($fh);
                   10062: 	$loaded = 1;
1.327     albertel 10063:     }
1.846     albertel 10064: 
                   10065:     sub domain {
1.852     albertel 10066: 	&load_domain_tab() if (!$loaded);
                   10067: 
1.846     albertel 10068: 	my ($name,$what) = @_;
                   10069: 	return if ( !exists($domain{$name}) );
                   10070: 
                   10071: 	if (!$what) {
                   10072: 	    return $domain{$name}{'description'};
                   10073: 	}
                   10074: 	return $domain{$name}{$what};
                   10075:     }
1.974     raeburn  10076: 
                   10077:     sub domain_info {
                   10078:         &load_domain_tab() if (!$loaded);
                   10079:         return %domain;
                   10080:     }
                   10081: 
1.327     albertel 10082: }
                   10083: 
                   10084: 
1.1       albertel 10085: # ------------------------------------------------------------- Read hosts file
                   10086: {
1.838     albertel 10087:     my %hostname;
1.844     albertel 10088:     my %hostdom;
1.845     albertel 10089:     my %libserv;
1.852     albertel 10090:     my $loaded;
1.888     albertel 10091:     my %name_to_host;
1.1056.4.6  raeburn  10092:     my %internetdom;
1.1056.4.25  raeburn  10093:     my %LC_dns_serv;
1.852     albertel 10094: 
                   10095:     sub parse_hosts_tab {
                   10096: 	my ($file) = @_;
                   10097: 	foreach my $configline (@$file) {
                   10098: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1056.4.25  raeburn  10099:             chomp($configline);
                   10100:             if ($configline =~ /^\^/) {
                   10101:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10102:                     $LC_dns_serv{$1} = 1;
                   10103:                 }
                   10104:                 next;
                   10105:             }
1.1056.4.6  raeburn  10106: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10107: 	    $name=~s/\s//g;
                   10108: 	    if ($id && $domain && $role && $name) {
                   10109: 		$hostname{$id}=$name;
1.888     albertel 10110: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10111: 		$hostdom{$id}=$domain;
                   10112: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10113:                 if (defined($protocol)) {
                   10114:                     if ($protocol eq 'https') {
                   10115:                         $protocol{$id} = $protocol;
                   10116:                     } else {
                   10117:                         $protocol{$id} = 'http'; 
                   10118:                     }
1.968     raeburn  10119:                 } else {
1.969     raeburn  10120:                     $protocol{$id} = 'http';
1.968     raeburn  10121:                 }
1.1056.4.6  raeburn  10122:                 if (defined($intdom)) {
                   10123:                     $internetdom{$id} = $intdom;
                   10124:                 }
1.852     albertel 10125: 	    }
                   10126: 	}
                   10127:     }
1.864     albertel 10128:     
                   10129:     sub reset_hosts_info {
1.897     albertel 10130: 	&purge_remembered();
1.864     albertel 10131: 	&reset_domain_info();
                   10132: 	&reset_hosts_ip_info();
1.892     albertel 10133: 	undef(%name_to_host);
1.864     albertel 10134: 	undef(%hostname);
                   10135: 	undef(%hostdom);
                   10136: 	undef(%libserv);
                   10137: 	undef($loaded);
                   10138:     }
1.1       albertel 10139: 
1.852     albertel 10140:     sub load_hosts_tab {
1.869     albertel 10141: 	my ($ignore_cache) = @_;
                   10142: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10143: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10144: 	my @config = <$config>;
                   10145: 	&parse_hosts_tab(\@config);
                   10146: 	close($config);
                   10147: 	$loaded=1;
1.1       albertel 10148:     }
1.852     albertel 10149: 
1.838     albertel 10150:     sub hostname {
1.852     albertel 10151: 	&load_hosts_tab() if (!$loaded);
                   10152: 
1.838     albertel 10153: 	my ($lonid) = @_;
                   10154: 	return $hostname{$lonid};
                   10155:     }
1.845     albertel 10156: 
1.838     albertel 10157:     sub all_hostnames {
1.852     albertel 10158: 	&load_hosts_tab() if (!$loaded);
                   10159: 
1.838     albertel 10160: 	return %hostname;
                   10161:     }
1.845     albertel 10162: 
1.888     albertel 10163:     sub all_names {
                   10164: 	&load_hosts_tab() if (!$loaded);
                   10165: 
                   10166: 	return %name_to_host;
                   10167:     }
                   10168: 
1.974     raeburn  10169:     sub all_host_domain {
                   10170:         &load_hosts_tab() if (!$loaded);
                   10171:         return %hostdom;
                   10172:     }
                   10173: 
1.845     albertel 10174:     sub is_library {
1.852     albertel 10175: 	&load_hosts_tab() if (!$loaded);
                   10176: 
1.845     albertel 10177: 	return exists($libserv{$_[0]});
                   10178:     }
                   10179: 
                   10180:     sub all_library {
1.852     albertel 10181: 	&load_hosts_tab() if (!$loaded);
                   10182: 
1.845     albertel 10183: 	return %libserv;
                   10184:     }
                   10185: 
1.1056.4.2  raeburn  10186:     sub unique_library {
                   10187:         #2x reverse removes all hostnames that appear more than once
                   10188:         my %unique = reverse &all_library();
                   10189:         return reverse %unique;
                   10190:     }
                   10191: 
1.841     albertel 10192:     sub get_servers {
1.852     albertel 10193: 	&load_hosts_tab() if (!$loaded);
                   10194: 
1.841     albertel 10195: 	my ($domain,$type) = @_;
                   10196: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10197: 	                                          : %hostname;
                   10198: 	my %result;
1.842     albertel 10199: 	if (ref($domain) eq 'ARRAY') {
                   10200: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10201: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10202: 		    $result{$host} = $hostname;
                   10203: 		}
                   10204: 	    }
                   10205: 	} else {
                   10206: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10207: 		if ($hostdom{$host} eq $domain) {
                   10208: 		    $result{$host} = $hostname;
                   10209: 		}
1.841     albertel 10210: 	    }
                   10211: 	}
                   10212: 	return %result;
                   10213:     }
1.845     albertel 10214: 
1.1056.4.2  raeburn  10215:     sub get_unique_servers {
                   10216:         my %unique = reverse &get_servers(@_);
                   10217:         return reverse %unique;
                   10218:     }
                   10219: 
1.844     albertel 10220:     sub host_domain {
1.852     albertel 10221: 	&load_hosts_tab() if (!$loaded);
                   10222: 
1.844     albertel 10223: 	my ($lonid) = @_;
                   10224: 	return $hostdom{$lonid};
                   10225:     }
                   10226: 
1.841     albertel 10227:     sub all_domains {
1.852     albertel 10228: 	&load_hosts_tab() if (!$loaded);
                   10229: 
1.841     albertel 10230: 	my %seen;
                   10231: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10232: 	return @uniq;
                   10233:     }
1.1056.4.3  raeburn  10234: 
                   10235:     sub internet_dom {
                   10236:         &load_hosts_tab() if (!$loaded);
                   10237: 
                   10238:         my ($lonid) = @_;
                   10239:         return $internetdom{$lonid};
                   10240:     }
1.1056.4.27  raeburn  10241: 
                   10242:     sub is_LC_dns {
                   10243:         &load_hosts_tab() if (!$loaded);
                   10244: 
                   10245:         my ($hostname) = @_;
                   10246:         return exists($LC_dns_serv{$hostname});
                   10247:     }
                   10248: 
1.1       albertel 10249: }
                   10250: 
1.847     albertel 10251: { 
                   10252:     my %iphost;
1.856     albertel 10253:     my %name_to_ip;
                   10254:     my %lonid_to_ip;
1.869     albertel 10255: 
1.847     albertel 10256:     sub get_hosts_from_ip {
                   10257: 	my ($ip) = @_;
                   10258: 	my %iphosts = &get_iphost();
                   10259: 	if (ref($iphosts{$ip})) {
                   10260: 	    return @{$iphosts{$ip}};
                   10261: 	}
                   10262: 	return;
1.839     albertel 10263:     }
1.864     albertel 10264:     
                   10265:     sub reset_hosts_ip_info {
                   10266: 	undef(%iphost);
                   10267: 	undef(%name_to_ip);
                   10268: 	undef(%lonid_to_ip);
                   10269:     }
1.856     albertel 10270: 
                   10271:     sub get_host_ip {
                   10272: 	my ($lonid) = @_;
                   10273: 	if (exists($lonid_to_ip{$lonid})) {
                   10274: 	    return $lonid_to_ip{$lonid};
                   10275: 	}
                   10276: 	my $name=&hostname($lonid);
                   10277:    	my $ip = gethostbyname($name);
                   10278: 	return if (!$ip || length($ip) ne 4);
                   10279: 	$ip=inet_ntoa($ip);
                   10280: 	$name_to_ip{$name}   = $ip;
                   10281: 	$lonid_to_ip{$lonid} = $ip;
                   10282: 	return $ip;
                   10283:     }
1.847     albertel 10284:     
                   10285:     sub get_iphost {
1.869     albertel 10286: 	my ($ignore_cache) = @_;
1.894     albertel 10287: 
1.869     albertel 10288: 	if (!$ignore_cache) {
                   10289: 	    if (%iphost) {
                   10290: 		return %iphost;
                   10291: 	    }
                   10292: 	    my ($ip_info,$cached)=
                   10293: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10294: 	    if ($cached) {
                   10295: 		%iphost      = %{$ip_info->[0]};
                   10296: 		%name_to_ip  = %{$ip_info->[1]};
                   10297: 		%lonid_to_ip = %{$ip_info->[2]};
                   10298: 		return %iphost;
                   10299: 	    }
                   10300: 	}
1.894     albertel 10301: 
                   10302: 	# get yesterday's info for fallback
                   10303: 	my %old_name_to_ip;
                   10304: 	my ($ip_info,$cached)=
                   10305: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10306: 	if ($cached) {
                   10307: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10308: 	}
                   10309: 
1.888     albertel 10310: 	my %name_to_host = &all_names();
                   10311: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10312: 	    my $ip;
                   10313: 	    if (!exists($name_to_ip{$name})) {
                   10314: 		$ip = gethostbyname($name);
                   10315: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10316: 		    if (defined($old_name_to_ip{$name})) {
                   10317: 			$ip = $old_name_to_ip{$name};
                   10318: 			&logthis("Can't find $name defaulting to old $ip");
                   10319: 		    } else {
                   10320: 			&logthis("Name $name no IP found");
                   10321: 			next;
                   10322: 		    }
                   10323: 		} else {
                   10324: 		    $ip=inet_ntoa($ip);
1.847     albertel 10325: 		}
                   10326: 		$name_to_ip{$name} = $ip;
                   10327: 	    } else {
                   10328: 		$ip = $name_to_ip{$name};
1.653     albertel 10329: 	    }
1.888     albertel 10330: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10331: 		$lonid_to_ip{$id} = $ip;
                   10332: 	    }
                   10333: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10334: 	}
1.869     albertel 10335: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10336: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10337: 				      48*60*60);
1.869     albertel 10338: 
1.847     albertel 10339: 	return %iphost;
1.598     albertel 10340:     }
                   10341: 
1.992     raeburn  10342:     #
                   10343:     #  Given a DNS returns the loncapa host name for that DNS 
                   10344:     # 
                   10345:     sub host_from_dns {
                   10346:         my ($dns) = @_;
                   10347:         my @hosts;
                   10348:         my $ip;
                   10349: 
1.993     raeburn  10350:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10351:             $ip = $name_to_ip{$dns};
                   10352:         }
                   10353:         if (!$ip) {
                   10354:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10355:             if (length($ip) == 4) { 
                   10356: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10357:             }
                   10358:         }
                   10359:         if ($ip) {
                   10360: 	    @hosts = get_hosts_from_ip($ip);
                   10361: 	    return $hosts[0];
                   10362:         }
                   10363:         return undef;
1.986     foxr     10364:     }
1.992     raeburn  10365: 
1.1056.4.3  raeburn  10366:     sub get_internet_names {
                   10367:         my ($lonid) = @_;
                   10368:         return if ($lonid eq '');
                   10369:         my ($idnref,$cached)=
                   10370:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10371:         if ($cached) {
                   10372:             return $idnref;
                   10373:         }
                   10374:         my $ip = &get_host_ip($lonid);
                   10375:         my @hosts = &get_hosts_from_ip($ip);
                   10376:         my %iphost = &get_iphost();
                   10377:         my (@idns,%seen);
                   10378:         foreach my $id (@hosts) {
                   10379:             my $dom = &host_domain($id);
                   10380:             my $prim_id = &domain($dom,'primary');
                   10381:             my $prim_ip = &get_host_ip($prim_id);
                   10382:             next if ($seen{$prim_ip});
                   10383:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10384:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10385:                     my $intdom = &internet_dom($id);
                   10386:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10387:                         push(@idns,$intdom);
                   10388:                     }
                   10389:                 }
                   10390:             }
                   10391:             $seen{$prim_ip} = 1;
                   10392:         }
                   10393:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10394:     }
                   10395: 
                   10396: }
                   10397: 
                   10398: sub all_loncaparevs {
                   10399:     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     10400: }
                   10401: 
1.862     albertel 10402: BEGIN {
                   10403: 
                   10404: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10405:     unless ($readit) {
                   10406: {
                   10407:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10408:     %perlvar = (%perlvar,%{$configvars});
                   10409: }
                   10410: 
                   10411: 
1.1       albertel 10412: # ------------------------------------------------------ Read spare server file
                   10413: {
1.448     albertel 10414:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10415: 
                   10416:     while (my $configline=<$config>) {
                   10417:        chomp($configline);
1.284     matthew  10418:        if ($configline) {
1.784     albertel 10419: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10420: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10421: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10422:        }
                   10423:     }
1.448     albertel 10424:     close($config);
1.1       albertel 10425: }
1.11      www      10426: # ------------------------------------------------------------ Read permissions
                   10427: {
1.448     albertel 10428:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10429: 
                   10430:     while (my $configline=<$config>) {
1.448     albertel 10431: 	chomp($configline);
                   10432: 	if ($configline) {
                   10433: 	    my ($role,$perm)=split(/ /,$configline);
                   10434: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10435: 	}
1.11      www      10436:     }
1.448     albertel 10437:     close($config);
1.11      www      10438: }
                   10439: 
                   10440: # -------------------------------------------- Read plain texts for permissions
                   10441: {
1.448     albertel 10442:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10443: 
                   10444:     while (my $configline=<$config>) {
1.448     albertel 10445: 	chomp($configline);
                   10446: 	if ($configline) {
1.742     raeburn  10447: 	    my ($short,@plain)=split(/:/,$configline);
                   10448:             %{$prp{$short}} = ();
                   10449: 	    if (@plain > 0) {
                   10450:                 $prp{$short}{'std'} = $plain[0];
                   10451:                 for (my $i=1; $i<@plain; $i++) {
                   10452:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10453:                 }
                   10454:             }
1.448     albertel 10455: 	}
1.135     www      10456:     }
1.448     albertel 10457:     close($config);
1.135     www      10458: }
                   10459: 
                   10460: # ---------------------------------------------------------- Read package table
                   10461: {
1.448     albertel 10462:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10463: 
                   10464:     while (my $configline=<$config>) {
1.483     albertel 10465: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10466: 	chomp($configline);
                   10467: 	my ($short,$plain)=split(/:/,$configline);
                   10468: 	my ($pack,$name)=split(/\&/,$short);
                   10469: 	if ($plain ne '') {
                   10470: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10471: 	    $packagetab{$short}=$plain; 
                   10472: 	}
1.11      www      10473:     }
1.448     albertel 10474:     close($config);
1.329     matthew  10475: }
                   10476: 
1.1056.4.3  raeburn  10477: # ---------------------------------------------------------- Read loncaparev table
                   10478: {
                   10479:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10480:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10481:             while (my $configline=<$config>) {
                   10482:                 chomp($configline);
                   10483:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10484:                 $loncaparevs{$hostid}=$loncaparev;
                   10485:             }
                   10486:             close($config);
                   10487:         }
                   10488:     }
                   10489: }
                   10490: 
                   10491: # ---------------------------------------------------------- Read serverhostID table
                   10492: {
                   10493:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10494:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10495:             while (my $configline=<$config>) {
                   10496:                 chomp($configline);
                   10497:                 my ($name,$id)=split(/:/,$configline);
                   10498:                 $serverhomeIDs{$name}=$id;
                   10499:             }
                   10500:             close($config);
                   10501:         }
                   10502:     }
                   10503: }
                   10504: 
1.1056.4.5  raeburn  10505: {
                   10506:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10507:     if (-e $file) {
                   10508:         my $parser = HTML::LCParser->new($file);
                   10509:         while (my $token = $parser->get_token()) {
                   10510:             if ($token->[0] eq 'S') {
                   10511:                 my $item = $token->[1];
                   10512:                 my $name = $token->[2]{'name'};
                   10513:                 my $value = $token->[2]{'value'};
                   10514:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10515:                     my $release = $parser->get_text();
                   10516:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10517:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10518:                 }
                   10519:             }
                   10520:         }
                   10521:     }
                   10522: }
                   10523: 
1.329     matthew  10524: # ------------- set up temporary directory
                   10525: {
                   10526:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10527: 
1.11      www      10528: }
                   10529: 
1.794     albertel 10530: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10531: 				'compress_threshold'=> 20_000,
                   10532:  			        });
1.185     www      10533: 
1.281     www      10534: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10535: $dumpcount=0;
1.958     www      10536: $locknum=0;
1.22      www      10537: 
1.163     harris41 10538: &logtouch();
1.672     albertel 10539: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10540: $readit=1;
1.564     albertel 10541:     {
                   10542: 	use integer;
                   10543: 	my $test=(2**32)+1;
1.568     albertel 10544: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10545: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10546:     }
1.195     www      10547: }
1.1       albertel 10548: }
1.179     www      10549: 
1.1       albertel 10550: 1;
1.191     harris41 10551: __END__
                   10552: 
1.243     albertel 10553: =pod
                   10554: 
1.191     harris41 10555: =head1 NAME
                   10556: 
1.243     albertel 10557: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10558: 
                   10559: =head1 SYNOPSIS
                   10560: 
1.243     albertel 10561: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10562: 
                   10563:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10564: 
1.243     albertel 10565: Common parameters:
                   10566: 
                   10567: =over 4
                   10568: 
                   10569: =item *
                   10570: 
                   10571: $uname : an internal username (if $cname expecting a course Id specifically)
                   10572: 
                   10573: =item *
                   10574: 
                   10575: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10576: 
                   10577: =item *
                   10578: 
                   10579: $symb : a resource instance identifier
                   10580: 
                   10581: =item *
                   10582: 
                   10583: $namespace : the name of a .db file that contains the data needed or
                   10584: being set.
                   10585: 
                   10586: =back
                   10587: 
1.394     bowersj2 10588: =head1 OVERVIEW
1.191     harris41 10589: 
1.394     bowersj2 10590: lonnet provides subroutines which interact with the
                   10591: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10592: about classes, users, and resources.
1.243     albertel 10593: 
                   10594: For many of these objects you can also use this to store data about
                   10595: them or modify them in various ways.
1.191     harris41 10596: 
1.394     bowersj2 10597: =head2 Symbs
1.191     harris41 10598: 
1.394     bowersj2 10599: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10600: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10601: map, the resource number of the resource in the map, and the URL of
                   10602: the resource itself. The latter is somewhat redundant, but might help
                   10603: if maps change.
                   10604: 
                   10605: An example is
                   10606: 
                   10607:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10608: 
                   10609: The respective map entry is
                   10610: 
                   10611:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10612:   title="Problem 2">
                   10613:  </resource>
                   10614: 
                   10615: Symbs are used by the random number generator, as well as to store and
                   10616: restore data specific to a certain instance of for example a problem.
                   10617: 
                   10618: =head2 Storing And Retrieving Data
                   10619: 
                   10620: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10621: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10622: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10623: is is the non-critical message twin of cstore. These functions are for
                   10624: handlers to store a perl hash to a user's permanent data space in an
                   10625: easy manner, and to retrieve it again on another call. It is expected
                   10626: that a handler would use this once at the beginning to retrieve data,
                   10627: and then again once at the end to send only the new data back.
                   10628: 
                   10629: The data is stored in the user's data directory on the user's
                   10630: homeserver under the ID of the course.
                   10631: 
                   10632: The hash that is returned by restore will have all of the previous
                   10633: value for all of the elements of the hash.
                   10634: 
                   10635: Example:
                   10636: 
                   10637:  #creating a hash
                   10638:  my %hash;
                   10639:  $hash{'foo'}='bar';
                   10640: 
                   10641:  #storing it
                   10642:  &Apache::lonnet::cstore(\%hash);
                   10643: 
                   10644:  #changing a value
                   10645:  $hash{'foo'}='notbar';
                   10646: 
                   10647:  #adding a new value
                   10648:  $hash{'bar'}='foo';
                   10649:  &Apache::lonnet::cstore(\%hash);
                   10650: 
                   10651:  #retrieving the hash
                   10652:  my %history=&Apache::lonnet::restore();
                   10653: 
                   10654:  #print the hash
                   10655:  foreach my $key (sort(keys(%history))) {
                   10656:    print("\%history{$key} = $history{$key}");
                   10657:  }
                   10658: 
                   10659: Will print out:
1.191     harris41 10660: 
1.394     bowersj2 10661:  %history{1:foo} = bar
                   10662:  %history{1:keys} = foo:timestamp
                   10663:  %history{1:timestamp} = 990455579
                   10664:  %history{2:bar} = foo
                   10665:  %history{2:foo} = notbar
                   10666:  %history{2:keys} = foo:bar:timestamp
                   10667:  %history{2:timestamp} = 990455580
                   10668:  %history{bar} = foo
                   10669:  %history{foo} = notbar
                   10670:  %history{timestamp} = 990455580
                   10671:  %history{version} = 2
                   10672: 
                   10673: Note that the special hash entries C<keys>, C<version> and
                   10674: C<timestamp> were added to the hash. C<version> will be equal to the
                   10675: total number of versions of the data that have been stored. The
                   10676: C<timestamp> attribute will be the UNIX time the hash was
                   10677: stored. C<keys> is available in every historical section to list which
                   10678: keys were added or changed at a specific historical revision of a
                   10679: hash.
                   10680: 
                   10681: B<Warning>: do not store the hash that restore returns directly. This
                   10682: will cause a mess since it will restore the historical keys as if the
                   10683: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10684: 
1.394     bowersj2 10685: Calling convention:
1.191     harris41 10686: 
1.394     bowersj2 10687:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10688:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10689: 
1.394     bowersj2 10690: For more detailed information, see lonnet specific documentation.
1.191     harris41 10691: 
1.394     bowersj2 10692: =head1 RETURN MESSAGES
1.191     harris41 10693: 
1.394     bowersj2 10694: =over 4
1.191     harris41 10695: 
1.394     bowersj2 10696: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10697: 
1.394     bowersj2 10698: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10699: when the connection is brought back up
1.191     harris41 10700: 
1.394     bowersj2 10701: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10702: for later delivery
1.191     harris41 10703: 
1.967     bisitz   10704: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10705: 
1.394     bowersj2 10706: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10707: that was requested
1.191     harris41 10708: 
1.243     albertel 10709: =back
1.191     harris41 10710: 
1.243     albertel 10711: =head1 PUBLIC SUBROUTINES
1.191     harris41 10712: 
1.243     albertel 10713: =head2 Session Environment Functions
1.191     harris41 10714: 
1.243     albertel 10715: =over 4
1.191     harris41 10716: 
1.394     bowersj2 10717: =item * 
                   10718: X<appenv()>
1.949     raeburn  10719: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10720: the user envirnoment file, and will be restored for each access this
1.620     albertel 10721: user makes during this session, also modifies the %env for the current
1.949     raeburn  10722: process. Optional rolesarrayref - if defined contains a reference to an array
                   10723: of roles which are exempt from the restriction on modifying user.role entries 
                   10724: in the user's environment.db and in %env.    
1.191     harris41 10725: 
                   10726: =item *
1.394     bowersj2 10727: X<delenv()>
1.987     raeburn  10728: B<delenv($delthis,$regexp)>: removes all items from the session
                   10729: environment file that begin with $delthis. If the 
                   10730: optional second arg - $regexp - is true, $delthis is treated as a 
                   10731: regular expression, otherwise \Q$delthis\E is used. 
                   10732: The values are also deleted from the current processes %env.
1.191     harris41 10733: 
1.795     albertel 10734: =item * get_env_multiple($name) 
                   10735: 
                   10736: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10737: values may be defined and end up as an array ref.
                   10738: 
                   10739: returns an array of values
                   10740: 
1.243     albertel 10741: =back
                   10742: 
                   10743: =head2 User Information
1.191     harris41 10744: 
1.243     albertel 10745: =over 4
1.191     harris41 10746: 
                   10747: =item *
1.394     bowersj2 10748: X<queryauthenticate()>
                   10749: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10750: authentication scheme
                   10751: 
                   10752: =item *
1.394     bowersj2 10753: X<authenticate()>
1.1056.4.3  raeburn  10754: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10755: authenticate user from domain's lib servers (first use the current
                   10756: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10757: $checkdefauth is optional (value is 1 if a check should be made to
                   10758:    authenticate user using default authentication method, and allow
                   10759:    account creation if username does not have account in the domain).
                   10760: $clientcancheckhost is optional (value is 1 if checking whether the
                   10761:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10762: 
                   10763: =item *
1.394     bowersj2 10764: X<homeserver()>
                   10765: B<homeserver($uname,$udom)>: find the server which has
                   10766: the user's directory and files (there must be only one), this caches
                   10767: the answer, and also caches if there is a borken connection.
1.191     harris41 10768: 
                   10769: =item *
1.394     bowersj2 10770: X<idget()>
                   10771: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10772: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10773: username, and only 1 username per ID in a specific domain) (returns
                   10774: hash: id=>name,id=>name)
1.191     harris41 10775: 
                   10776: =item *
1.394     bowersj2 10777: X<idrget()>
                   10778: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10779: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10780: 
                   10781: =item *
1.394     bowersj2 10782: X<idput()>
                   10783: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10784: 
                   10785: =item *
1.394     bowersj2 10786: X<rolesinit()>
                   10787: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10788: 
                   10789: =item *
1.551     albertel 10790: X<getsection()>
                   10791: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10792: course $cname, return section name/number or '' for "not in course"
                   10793: and '-1' for "no section"
                   10794: 
                   10795: =item *
1.394     bowersj2 10796: X<userenvironment()>
                   10797: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10798: passed in @what from the requested user's environment, returns a hash
                   10799: 
1.858     raeburn  10800: =item * 
                   10801: X<userlog_query()>
1.859     albertel 10802: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10803: activity.log file. %filters defines filters applied when parsing the
                   10804: log file. These can be start or end timestamps, or the type of action
                   10805: - log to look for Login or Logout events, check for Checkin or
                   10806: Checkout, role for role selection. The response is in the form
                   10807: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10808: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10809: 
1.243     albertel 10810: =back
                   10811: 
                   10812: =head2 User Roles
                   10813: 
                   10814: =over 4
                   10815: 
                   10816: =item *
                   10817: 
1.810     raeburn  10818: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10819:  F: full access
                   10820:  U,I,K: authentication modes (cxx only)
                   10821:  '': forbidden
                   10822:  1: user needs to choose course
                   10823:  2: browse allowed
1.766     albertel 10824:  A: passphrase authentication needed
1.243     albertel 10825: 
                   10826: =item *
                   10827: 
                   10828: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10829: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10830: and course level
                   10831: 
                   10832: =item *
                   10833: 
1.988     raeburn  10834: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10835: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10836: $type is Course (default) or Community.
1.988     raeburn  10837: If $forcedefault evaluates to true, text returned will be default 
                   10838: text for $type. Otherwise, if this is a course, the text returned 
                   10839: will be a custom name for the role (if defined in the course's 
                   10840: environment).  If no custom name is defined the default is returned.
                   10841:    
1.832     raeburn  10842: =item *
                   10843: 
1.935     raeburn  10844: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10845: All arguments are optional. Returns a hash of a roles, either for
                   10846: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10847: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10848: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10849: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10850: For each key, value is set to colon-separated start and end times for
                   10851: the role.  If no username and domain are specified, will default to
1.934     raeburn  10852: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10853: of role statuses (active, future or previous), roles 
                   10854: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10855: to restrict the list of roles reported. If no array ref is 
                   10856: provided for types, will default to return only active roles.
1.834     albertel 10857: 
1.243     albertel 10858: =back
                   10859: 
                   10860: =head2 User Modification
                   10861: 
                   10862: =over 4
                   10863: 
                   10864: =item *
                   10865: 
1.957     raeburn  10866: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10867: user for the level given by URL.  Optional start and end dates (leave empty
                   10868: string or zero for "no date")
1.191     harris41 10869: 
                   10870: =item *
                   10871: 
1.243     albertel 10872: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10873: change a users, password, possible return values are: ok,
                   10874: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10875: refused
1.191     harris41 10876: 
                   10877: =item *
                   10878: 
1.243     albertel 10879: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10880: 
                   10881: =item *
                   10882: 
1.1056.4.1  raeburn  10883: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10884:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10885: 
                   10886: will update user information (firstname,middlename,lastname,generation,
                   10887: permanentemail), and if forceid is true, student/employee ID also.
                   10888: A user's institutional affiliation(s) can also be updated.
                   10889: User information fields will not be overwritten with empty entries 
                   10890: unless the field is included in the $candelete array reference.
                   10891: This array is included when a single user is modified via "Manage Users",
                   10892: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10893: 
                   10894: =item *
                   10895: 
1.286     matthew  10896: modifystudent
                   10897: 
1.957     raeburn  10898: modify a student's enrollment and identification information.
1.286     matthew  10899: The course id is resolved based on the current users environment.  
                   10900: This means the envoking user must be a course coordinator or otherwise
                   10901: associated with a course.
                   10902: 
1.297     matthew  10903: This call is essentially a wrapper for lonnet::modifyuser and
                   10904: lonnet::modify_student_enrollment
1.286     matthew  10905: 
                   10906: Inputs: 
                   10907: 
                   10908: =over 4
                   10909: 
1.957     raeburn  10910: =item B<$udom> Student's loncapa domain
1.286     matthew  10911: 
1.957     raeburn  10912: =item B<$uname> Student's loncapa login name
1.286     matthew  10913: 
1.964     bisitz   10914: =item B<$uid> Student/Employee ID
1.286     matthew  10915: 
1.957     raeburn  10916: =item B<$umode> Student's authentication mode
1.286     matthew  10917: 
1.957     raeburn  10918: =item B<$upass> Student's password
1.286     matthew  10919: 
1.957     raeburn  10920: =item B<$first> Student's first name
1.286     matthew  10921: 
1.957     raeburn  10922: =item B<$middle> Student's middle name
1.286     matthew  10923: 
1.957     raeburn  10924: =item B<$last> Student's last name
1.286     matthew  10925: 
1.957     raeburn  10926: =item B<$gene> Student's generation
1.286     matthew  10927: 
1.957     raeburn  10928: =item B<$usec> Student's section in course
1.286     matthew  10929: 
                   10930: =item B<$end> Unix time of the roles expiration
                   10931: 
                   10932: =item B<$start> Unix time of the roles start date
                   10933: 
                   10934: =item B<$forceid> If defined, allow $uid to be changed
                   10935: 
                   10936: =item B<$desiredhome> server to use as home server for student
                   10937: 
1.957     raeburn  10938: =item B<$email> Student's permanent e-mail address
                   10939: 
                   10940: =item B<$type> Type of enrollment (auto or manual)
                   10941: 
1.963     raeburn  10942: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10943: 
                   10944: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10945: 
1.963     raeburn  10946: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10947: 
1.963     raeburn  10948: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10949: 
1.963     raeburn  10950: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10951: 
1.286     matthew  10952: =back
1.297     matthew  10953: 
                   10954: =item *
                   10955: 
                   10956: modify_student_enrollment
                   10957: 
                   10958: Change a students enrollment status in a class.  The environment variable
                   10959: 'role.request.course' must be defined for this function to proceed.
                   10960: 
                   10961: Inputs:
                   10962: 
                   10963: =over 4
                   10964: 
                   10965: =item $udom, students domain
                   10966: 
                   10967: =item $uname, students name
                   10968: 
                   10969: =item $uid, students user id
                   10970: 
                   10971: =item $first, students first name
                   10972: 
                   10973: =item $middle
                   10974: 
                   10975: =item $last
                   10976: 
                   10977: =item $gene
                   10978: 
                   10979: =item $usec
                   10980: 
                   10981: =item $end
                   10982: 
                   10983: =item $start
                   10984: 
1.957     raeburn  10985: =item $type
                   10986: 
                   10987: =item $locktype
                   10988: 
                   10989: =item $cid
                   10990: 
                   10991: =item $selfenroll
                   10992: 
                   10993: =item $context
                   10994: 
1.297     matthew  10995: =back
                   10996: 
1.191     harris41 10997: 
                   10998: =item *
                   10999: 
1.243     albertel 11000: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11001: custom role; give a custom role to a user for the level given by URL.  Specify
                   11002: name and domain of role author, and role name
1.191     harris41 11003: 
                   11004: =item *
                   11005: 
1.243     albertel 11006: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11007: 
                   11008: =item *
                   11009: 
1.243     albertel 11010: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11011: 
                   11012: =back
                   11013: 
                   11014: =head2 Course Infomation
                   11015: 
                   11016: =over 4
1.191     harris41 11017: 
                   11018: =item *
                   11019: 
1.631     albertel 11020: coursedescription($courseid) : returns a hash of information about the
                   11021: specified course id, including all environment settings for the
                   11022: course, the description of the course will be in the hash under the
                   11023: key 'description'
1.191     harris41 11024: 
                   11025: =item *
                   11026: 
1.624     albertel 11027: resdata($name,$domain,$type,@which) : request for current parameter
                   11028: setting for a specific $type, where $type is either 'course' or 'user',
                   11029: @what should be a list of parameters to ask about. This routine caches
                   11030: answers for 5 minutes.
1.243     albertel 11031: 
1.877     foxr     11032: =item *
                   11033: 
                   11034: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11035: data base, returning a hash that is keyed by the resource name and has
                   11036: values that are the resource value.  I believe that the timestamps and
                   11037: versions are also returned.
                   11038: 
                   11039: 
1.243     albertel 11040: =back
                   11041: 
                   11042: =head2 Course Modification
                   11043: 
                   11044: =over 4
1.191     harris41 11045: 
                   11046: =item *
                   11047: 
1.243     albertel 11048: writecoursepref($courseid,%prefs) : write preferences (environment
                   11049: database) for a course
1.191     harris41 11050: 
                   11051: =item *
                   11052: 
1.1011    raeburn  11053: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11054: 
                   11055: =item *
                   11056: 
1.1038    raeburn  11057: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11058: 
                   11059: =back
                   11060: 
                   11061: =head2 Resource Subroutines
                   11062: 
                   11063: =over 4
1.191     harris41 11064: 
                   11065: =item *
                   11066: 
1.243     albertel 11067: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11068: 
                   11069: =item *
                   11070: 
1.243     albertel 11071: repcopy($filename) : subscribes to the requested file, and attempts to
                   11072: replicate from the owning library server, Might return
1.607     raeburn  11073: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11074: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11075: resource. Expects the local filesystem pathname
                   11076: (/home/httpd/html/res/....)
                   11077: 
                   11078: =back
                   11079: 
                   11080: =head2 Resource Information
                   11081: 
                   11082: =over 4
1.191     harris41 11083: 
                   11084: =item *
                   11085: 
1.243     albertel 11086: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11087: a vairety of different possible values, $varname should be a request
                   11088: string, and the other parameters can be used to specify who and what
                   11089: one is asking about.
                   11090: 
                   11091: Possible values for $varname are environment.lastname (or other item
                   11092: from the envirnment hash), user.name (or someother aspect about the
                   11093: user), resource.0.maxtries (or some other part and parameter of a
                   11094: resource)
1.204     albertel 11095: 
                   11096: =item *
                   11097: 
1.243     albertel 11098: directcondval($number) : get current value of a condition; reads from a state
                   11099: string
1.204     albertel 11100: 
                   11101: =item *
                   11102: 
1.243     albertel 11103: condval($condidx) : value of condition index based on state
1.204     albertel 11104: 
                   11105: =item *
                   11106: 
1.243     albertel 11107: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11108: resource's metadata, $what should be either a specific key, or either
                   11109: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11110: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11111: 
                   11112: this function automatically caches all requests
1.191     harris41 11113: 
                   11114: =item *
                   11115: 
1.243     albertel 11116: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11117: network of library servers; returns file handle of where SQL and regex results
                   11118: will be stored for query
1.191     harris41 11119: 
                   11120: =item *
                   11121: 
1.243     albertel 11122: symbread($filename) : return symbolic list entry (filename argument optional);
                   11123: returns the data handle
1.191     harris41 11124: 
                   11125: =item *
                   11126: 
1.243     albertel 11127: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11128: a possible symb for the URL in $thisfn, and if is an encryypted
                   11129: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11130: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11131: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11132: 
1.191     harris41 11133: 
                   11134: =item *
                   11135: 
1.243     albertel 11136: symbclean($symb) : removes versions numbers from a symb, returns the
                   11137: cleaned symb
1.191     harris41 11138: 
                   11139: =item *
                   11140: 
1.243     albertel 11141: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11142: course map, user must be in a course for it to work.
1.191     harris41 11143: 
                   11144: =item *
                   11145: 
1.243     albertel 11146: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11147: 
                   11148: =item *
                   11149: 
1.243     albertel 11150: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11151: a random seed, all arguments are optional, if they aren't sent it uses the
                   11152: environment to derive them. Note: if symb isn't sent and it can't get one
                   11153: from &symbread it will use the current time as its return value
1.191     harris41 11154: 
                   11155: =item *
                   11156: 
1.243     albertel 11157: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11158: unfakeable, receipt
1.191     harris41 11159: 
                   11160: =item *
                   11161: 
1.620     albertel 11162: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11163: 
                   11164: =item *
                   11165: 
1.243     albertel 11166: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11167: 
                   11168: =item *
                   11169: 
1.243     albertel 11170: 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 11171: 
                   11172: =item *
                   11173: 
1.243     albertel 11174: 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 11175: 
                   11176: =item *
                   11177: 
1.243     albertel 11178: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11179: 
                   11180: =item *
                   11181: 
1.243     albertel 11182: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11183: forcing spreadsheet to reevaluate the resource scores next time.
                   11184: 
                   11185: =back
                   11186: 
                   11187: =head2 Storing/Retreiving Data
                   11188: 
                   11189: =over 4
1.191     harris41 11190: 
                   11191: =item *
                   11192: 
1.243     albertel 11193: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11194: for this url; hashref needs to be given and should be a \%hashname; the
                   11195: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11196: be derived from the env
1.191     harris41 11197: 
                   11198: =item *
                   11199: 
1.243     albertel 11200: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11201: uses critical subroutine
1.191     harris41 11202: 
                   11203: =item *
                   11204: 
1.243     albertel 11205: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11206: all args are optional
1.191     harris41 11207: 
                   11208: =item *
                   11209: 
1.717     albertel 11210: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11211: dumps the complete (or key matching regexp) namespace into a hash
                   11212: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11213: normally &store()ed into
                   11214: 
                   11215: $range should be either an integer '100' (give me the first 100
                   11216:                                            matching records)
                   11217:               or be  two integers sperated by a - with no spaces
                   11218:                  '30-50' (give me the 30th through the 50th matching
                   11219:                           records)
                   11220: 
                   11221: 
                   11222: =item *
                   11223: 
                   11224: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11225: replaces a &store() version of data with a replacement set of data
                   11226: for a particular resource in a namespace passed in the $storehash hash 
                   11227: reference
                   11228: 
                   11229: =item *
                   11230: 
1.243     albertel 11231: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11232: works very similar to store/cstore, but all data is stored in a
                   11233: temporary location and can be reset using tmpreset, $storehash should
                   11234: be a hash reference, returns nothing on success
1.191     harris41 11235: 
                   11236: =item *
                   11237: 
1.243     albertel 11238: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11239: similar to restore, but all data is stored in a temporary location and
                   11240: can be reset using tmpreset. Returns a hash of values on success,
                   11241: error string otherwise.
1.191     harris41 11242: 
                   11243: =item *
                   11244: 
1.243     albertel 11245: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11246: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11247: 
                   11248: =item *
                   11249: 
1.243     albertel 11250: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11251: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11252: 
                   11253: =item *
                   11254: 
1.243     albertel 11255: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11256: namesp ($udom and $uname are optional)
1.191     harris41 11257: 
                   11258: =item *
                   11259: 
1.702     albertel 11260: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11261: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11262: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11263: 
1.702     albertel 11264: $range should be either an integer '100' (give me the first 100
                   11265:                                            matching records)
                   11266:               or be  two integers sperated by a - with no spaces
                   11267:                  '30-50' (give me the 30th through the 50th matching
                   11268:                           records)
1.449     matthew  11269: =item *
                   11270: 
                   11271: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11272: $store can be a scalar, an array reference, or if the amount to be 
                   11273: incremented is > 1, a hash reference.
                   11274: 
                   11275: ($udom and $uname are optional)
1.191     harris41 11276: 
                   11277: =item *
                   11278: 
1.243     albertel 11279: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11280: ($udom and $uname are optional)
1.191     harris41 11281: 
                   11282: =item *
                   11283: 
1.243     albertel 11284: cput($namespace,$storehash,$udom,$uname) : critical put
                   11285: ($udom and $uname are optional)
1.191     harris41 11286: 
                   11287: =item *
                   11288: 
1.748     albertel 11289: newput($namespace,$storehash,$udom,$uname) :
                   11290: 
                   11291: Attempts to store the items in the $storehash, but only if they don't
                   11292: currently exist, if this succeeds you can be certain that you have 
                   11293: successfully created a new key value pair in the $namespace db.
                   11294: 
                   11295: 
                   11296: Args:
                   11297:  $namespace: name of database to store values to
                   11298:  $storehash: hashref to store to the db
                   11299:  $udom: (optional) domain of user containing the db
                   11300:  $uname: (optional) name of user caontaining the db
                   11301: 
                   11302: Returns:
                   11303:  'ok' -> succeeded in storing all keys of $storehash
                   11304:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11305:                         least <key> already existed in the db (other
                   11306:                         requested keys may also already exist)
1.967     bisitz   11307:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11308:  'con_lost' -> unable to contact request server
                   11309:  'refused' -> action was not allowed by remote machine
                   11310: 
                   11311: 
                   11312: =item *
                   11313: 
1.243     albertel 11314: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11315: reference filled in from namesp (encrypts the return communication)
                   11316: ($udom and $uname are optional)
1.191     harris41 11317: 
                   11318: =item *
                   11319: 
1.243     albertel 11320: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11321: critical subroutine
                   11322: 
1.806     raeburn  11323: =item *
                   11324: 
1.860     raeburn  11325: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11326: array reference filled in from namespace found in domain level on either
                   11327: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11328: 
                   11329: =item *
                   11330: 
1.860     raeburn  11331: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11332: domain level either on specified domain server ($uhome) or primary domain 
                   11333: server ($udom and $uhome are optional)
1.806     raeburn  11334: 
1.943     raeburn  11335: =item * 
                   11336: 
                   11337: get_domain_defaults($target_domain) : returns hash with defaults for
                   11338: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11339: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11340: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11341: Values are retrieved from cache (if current), or from domain's configuration.db
                   11342: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11343: or lonTabs/domain.tab. 
                   11344: 
                   11345: %domdefaults = &get_auth_defaults($target_domain);
                   11346: 
1.243     albertel 11347: =back
                   11348: 
                   11349: =head2 Network Status Functions
                   11350: 
                   11351: =over 4
1.191     harris41 11352: 
                   11353: =item *
                   11354: 
                   11355: dirlist($uri) : return directory list based on URI
                   11356: 
                   11357: =item *
                   11358: 
1.243     albertel 11359: spareserver() : find server with least workload from spare.tab
                   11360: 
1.986     foxr     11361: 
                   11362: =item *
                   11363: 
                   11364: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11365: if there is no corresponding loncapa host.
                   11366: 
1.243     albertel 11367: =back
                   11368: 
1.986     foxr     11369: 
1.243     albertel 11370: =head2 Apache Request
                   11371: 
                   11372: =over 4
1.191     harris41 11373: 
                   11374: =item *
                   11375: 
1.243     albertel 11376: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11377: localhost, posts hash
                   11378: 
                   11379: =back
                   11380: 
                   11381: =head2 Data to String to Data
                   11382: 
                   11383: =over 4
1.191     harris41 11384: 
                   11385: =item *
                   11386: 
1.243     albertel 11387: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11388: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11389: 
                   11390: =item *
                   11391: 
1.243     albertel 11392: hashref2str($hashref) : convert a hashref into a string complete with
                   11393: escaping and '=' and '&' separators, supports elements that are
                   11394: arrayrefs and hashrefs
1.191     harris41 11395: 
                   11396: =item *
                   11397: 
1.243     albertel 11398: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11399: with escaping and '&' separators, supports elements that are arrayrefs
                   11400: and hashrefs
1.191     harris41 11401: 
                   11402: =item *
                   11403: 
1.243     albertel 11404: str2hash($string) : convert string to hash using unescaping and
                   11405: splitting on '=' and '&', supports elements that are arrayrefs and
                   11406: hashrefs
1.191     harris41 11407: 
                   11408: =item *
                   11409: 
1.243     albertel 11410: str2array($string) : convert string to hash using unescaping and
                   11411: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11412: 
                   11413: =back
                   11414: 
                   11415: =head2 Logging Routines
                   11416: 
                   11417: =over 4
                   11418: 
                   11419: These routines allow one to make log messages in the lonnet.log and
                   11420: lonnet.perm logfiles.
1.191     harris41 11421: 
                   11422: =item *
                   11423: 
1.243     albertel 11424: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11425: 
                   11426: =item *
                   11427: 
1.243     albertel 11428: logthis() : append message to the normal lonnet.log file, it gets
                   11429: preiodically rolled over and deleted.
1.191     harris41 11430: 
                   11431: =item *
                   11432: 
1.243     albertel 11433: logperm() : append a permanent message to lonnet.perm.log, this log
                   11434: file never gets deleted by any automated portion of the system, only
                   11435: messages of critical importance should go in here.
                   11436: 
                   11437: =back
                   11438: 
                   11439: =head2 General File Helper Routines
                   11440: 
                   11441: =over 4
1.191     harris41 11442: 
                   11443: =item *
                   11444: 
1.481     raeburn  11445: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11446: (a) files in /uploaded
                   11447:   (i) If a local copy of the file exists - 
                   11448:       compares modification date of local copy with last-modified date for 
                   11449:       definitive version stored on home server for course. If local copy is 
                   11450:       stale, requests a new version from the home server and stores it. 
                   11451:       If the original has been removed from the home server, then local copy 
                   11452:       is unlinked.
                   11453:   (ii) If local copy does not exist -
                   11454:       requests the file from the home server and stores it. 
                   11455:   
                   11456:   If $caller is 'uploadrep':  
                   11457:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11458:     for request for files originally uploaded via DOCS. 
                   11459:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11460:   
                   11461:   Otherwise:
                   11462:      This indicates a call from the content generation phase of the request.
                   11463:      -  returns the entire contents of the file or -1.
                   11464:      
                   11465: (b) files in /res
                   11466:    - returns the entire contents of a file or -1; 
                   11467:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11468: 
1.712     albertel 11469: 
                   11470: =item *
                   11471: 
                   11472: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11473:                   reference
                   11474: 
                   11475: returns either a stat() list of data about the file or an empty list
                   11476: if the file doesn't exist or couldn't find out about it (connection
                   11477: problems or user unknown)
                   11478: 
1.191     harris41 11479: =item *
                   11480: 
1.243     albertel 11481: filelocation($dir,$file) : returns file system location of a file
                   11482: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11483: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11484: and a file of ../bob will become /a/bob)
1.191     harris41 11485: 
                   11486: =item *
                   11487: 
                   11488: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11489: filelocation except for hrefs
                   11490: 
                   11491: =item *
                   11492: 
                   11493: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11494: 
1.243     albertel 11495: =back
                   11496: 
1.608     albertel 11497: =head2 Usererfile file routines (/uploaded*)
                   11498: 
                   11499: =over 4
                   11500: 
                   11501: =item *
                   11502: 
                   11503: userfileupload(): main rotine for putting a file in a user or course's
                   11504:                   filespace, arguments are,
                   11505: 
1.620     albertel 11506:  formname - required - this is the name of the element in $env where the
1.608     albertel 11507:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11508:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11509:            contents of the file is located in $env{'form.'.$formname}
1.1056.4.13  raeburn  11510:  context - if coursedoc, store the file in the course of the active role
                   11511:              of the current user;
                   11512:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11513:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11514:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11515:          if undefined, it will be placed in "unknown"
                   11516: 
                   11517:  (This routine calls clean_filename() to remove any dangerous
                   11518:  characters from the filename, and then calls finuserfileupload() to
                   11519:  complete the transaction)
                   11520: 
                   11521:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11522:  and /adm/notfound.html if unsuccessful
                   11523: 
                   11524: =item *
                   11525: 
                   11526: clean_filename(): routine for cleaing a filename up for storage in
                   11527:                  userfile space, argument is:
                   11528: 
                   11529:  filename - proposed filename
                   11530: 
                   11531: returns: the new clean filename
                   11532: 
                   11533: =item *
                   11534: 
1.1056.4.13  raeburn  11535: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11536: userspace, probably shouldn't be called directly
                   11537: 
                   11538:   docuname: username or courseid of destination for the file
                   11539:   docudom: domain of user/course of destination for the file
                   11540:   formname: same as for userfileupload()
1.1056.4.13  raeburn  11541:   fname: filename (including subdirectories) for the file
                   11542:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11543:   allfiles: reference to hash used to store objects found by parser
                   11544:   codebase: reference to hash used for codebases of java objects found by parser
                   11545:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11546:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11547:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11548:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11549:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11550:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1056.4.16  raeburn  11551:   mimetype: reference to scalar to accommodate mime type determined
                   11552:             from File::MMagic if $parser = parse.
1.608     albertel 11553: 
                   11554:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13  raeburn  11555:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11556:  was 'overwrite').
                   11557: 
1.608     albertel 11558: 
                   11559: =item *
                   11560: 
                   11561: renameuserfile(): renames an existing userfile to a new name
                   11562: 
                   11563:   Args:
                   11564:    docuname: username or courseid of destination for the file
                   11565:    docudom: domain of user/course of destination for the file
                   11566:    old: current file name (including any subdirs under userfiles)
                   11567:    new: desired file name (including any subdirs under userfiles)
                   11568: 
                   11569: =item *
                   11570: 
                   11571: mkdiruserfile(): creates a directory is a userfiles dir
                   11572: 
                   11573:   Args:
                   11574:    docuname: username or courseid of destination for the file
                   11575:    docudom: domain of user/course of destination for the file
                   11576:    dir: dir to create (including any subdirs under userfiles)
                   11577: 
                   11578: =item *
                   11579: 
                   11580: removeuserfile(): removes a file that exists in userfiles
                   11581: 
                   11582:   Args:
                   11583:    docuname: username or courseid of destination for the file
                   11584:    docudom: domain of user/course of destination for the file
                   11585:    fname: filname to delete (including any subdirs under userfiles)
                   11586: 
                   11587: =item *
                   11588: 
                   11589: removeuploadedurl(): convience function for removeuserfile()
                   11590: 
                   11591:   Args:
                   11592:    url:  a full /uploaded/... url to delete
                   11593: 
1.747     albertel 11594: =item * 
                   11595: 
                   11596: get_portfile_permissions():
                   11597:   Args:
                   11598:     domain: domain of user or course contain the portfolio files
                   11599:     user: name of user or num of course contain the portfolio files
                   11600:   Returns:
                   11601:     hashref of a dump of the proper file_permissions.db
                   11602:    
                   11603: 
                   11604: =item * 
                   11605: 
                   11606: get_access_controls():
                   11607: 
                   11608: Args:
                   11609:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11610:   group: (optional) the group you want the files associated with
                   11611:   file: (optional) the file you want access info on
                   11612: 
                   11613: Returns:
1.749     raeburn  11614:     a hash (keys are file names) of hashes containing
                   11615:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11616:         values are XML containing access control settings (see below) 
1.747     albertel 11617: 
                   11618: Internal notes:
                   11619: 
1.749     raeburn  11620:  access controls are stored in file_permissions.db as key=value pairs.
                   11621:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11622:         where scope -> public,guest,course,group,domains or users.
                   11623:               end -> UNIX time for end of access (0 -> no end date)
                   11624:               start -> UNIX time for start of access
                   11625: 
                   11626:     value -> XML description of access control
                   11627:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11628:             <start></start>
                   11629:             <end></end>
                   11630: 
                   11631:             <password></password>  for scope type = guest
                   11632: 
                   11633:             <domain></domain>     for scope type = course or group
                   11634:             <number></number>
                   11635:             <roles id="">
                   11636:              <role></role>
                   11637:              <access></access>
                   11638:              <section></section>
                   11639:              <group></group>
                   11640:             </roles>
                   11641: 
                   11642:             <dom></dom>         for scope type = domains
                   11643: 
                   11644:             <users>             for scope type = users
                   11645:              <user>
                   11646:               <uname></uname>
                   11647:               <udom></udom>
                   11648:              </user>
                   11649:             </users>
                   11650:            </scope> 
                   11651:               
                   11652:  Access data is also aggregated for each file in an additional key=value pair:
                   11653:  key -> path to file/file_name\0accesscontrol 
                   11654:  value -> reference to hash
                   11655:           hash contains key = value pairs
                   11656:           where key = uniqueID:scope_end_start
                   11657:                 value = UNIX time record was last updated
                   11658: 
                   11659:           Used to improve speed of look-ups of access controls for each file.  
                   11660:  
                   11661:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11662: 
                   11663: modify_access_controls():
                   11664: 
                   11665: Modifies access controls for a portfolio file
                   11666: Args
                   11667: 1. file name
                   11668: 2. reference to hash of required changes,
                   11669: 3. domain
                   11670: 4. username
                   11671:   where domain,username are the domain of the portfolio owner 
                   11672:   (either a user or a course) 
                   11673: 
                   11674: Returns:
                   11675: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11676: 2. result of deletions ('ok' or 'error', with error message).
                   11677: 3. reference to hash of any new or updated access controls.
                   11678: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11679:    key = integer (inbound ID)
                   11680:    value = uniqueID  
1.747     albertel 11681: 
1.608     albertel 11682: =back
                   11683: 
1.243     albertel 11684: =head2 HTTP Helper Routines
                   11685: 
                   11686: =over 4
                   11687: 
1.191     harris41 11688: =item *
                   11689: 
                   11690: escape() : unpack non-word characters into CGI-compatible hex codes
                   11691: 
                   11692: =item *
                   11693: 
                   11694: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11695: 
1.243     albertel 11696: =back
                   11697: 
                   11698: =head1 PRIVATE SUBROUTINES
                   11699: 
                   11700: =head2 Underlying communication routines (Shouldn't call)
                   11701: 
                   11702: =over 4
                   11703: 
                   11704: =item *
                   11705: 
                   11706: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11707: 
                   11708: =item *
                   11709: 
                   11710: reply() : uses subreply to send a message to remote machine, logs all failures
                   11711: 
                   11712: =item *
                   11713: 
                   11714: critical() : passes a critical message to another server; if cannot
                   11715: get through then place message in connection buffer directory and
                   11716: returns con_delayed, if incapable of saving message, returns
                   11717: con_failed
                   11718: 
                   11719: =item *
                   11720: 
                   11721: reconlonc() : tries to reconnect lonc client processes.
                   11722: 
                   11723: =back
                   11724: 
                   11725: =head2 Resource Access Logging
                   11726: 
                   11727: =over 4
                   11728: 
                   11729: =item *
                   11730: 
                   11731: flushcourselogs() : flush (save) buffer logs and access logs
                   11732: 
                   11733: =item *
                   11734: 
                   11735: courselog($what) : save message for course in hash
                   11736: 
                   11737: =item *
                   11738: 
                   11739: courseacclog($what) : save message for course using &courselog().  Perform
                   11740: special processing for specific resource types (problems, exams, quizzes, etc).
                   11741: 
1.191     harris41 11742: =item *
                   11743: 
                   11744: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11745: as a PerlChildExitHandler
1.243     albertel 11746: 
                   11747: =back
                   11748: 
                   11749: =head2 Other
                   11750: 
                   11751: =over 4
                   11752: 
                   11753: =item *
                   11754: 
                   11755: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11756: 
                   11757: =back
                   11758: 
                   11759: =cut
1.877     foxr     11760: 

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