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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1113  ! raeburn     4: # $Id: lonnet.pm,v 1.1112 2011/06/07 17:42:29 www Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.1090    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.1106    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.1073    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.1073    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.1081    raeburn   249:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    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.1082    raeburn   257:                     $ua->timeout(4);
1.1073    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.1081    raeburn   265:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   266:                             $loncaparev = $1;
                    267:                         }
                    268:                     }
                    269:                 } else {
                    270:                     $loncaparev = $loncaparevs{$lonhost};
                    271:                 }
1.1081    raeburn   272:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   273:                 $loncaparev = $1;
                    274:             }
1.993     raeburn   275:         }
1.1073    raeburn   276:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   277:     }
                    278: }
                    279: 
1.1074    raeburn   280: sub get_server_homeID {
                    281:     my ($hostname,$ignore_cache,$caller) = @_;
                    282:     unless ($ignore_cache) {
                    283:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    284:         if (defined($cached)) {
                    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:             }
                    298:         }
                    299:         if ($serverhomeID eq '') {
                    300:             $serverhomeID = $machine_ids[-1];
                    301:         }
                    302:     } else {
                    303:         $serverhomeID = $serverhomeIDs{$hostname};
                    304:     }
                    305:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    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.1104    raeburn   638:     my ($delthis,$regexp,$roles) = @_;
                    639:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    640:         my $refused = 1;
                    641:         if (ref($roles) eq 'ARRAY') {
                    642:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    643:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    644:                 $refused = 0;
                    645:             }
                    646:         }
                    647:         if ($refused) {
                    648:             &logthis("<font color=\"blue\">WARNING: ".
                    649:                      "Attempt to delete from environment ".$delthis);
                    650:             return 'error';
                    651:         }
1.56      www       652:     }
1.917     albertel  653:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    654:     if ($opened
1.915     albertel  655: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  656: 	&&
                    657: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    658: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  659: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   660: 	    if ($regexp) {
                    661:                 if ($key=~/^$delthis/) {
                    662:                     delete($env{$key});
                    663:                     delete($disk_env{$key});
                    664:                 } 
                    665:             } else {
                    666:                 if ($key=~/^\Q$delthis\E/) {
                    667: 		    delete($env{$key});
                    668: 		    delete($disk_env{$key});
                    669: 	        }
                    670:             }
1.448     albertel  671: 	}
1.783     albertel  672: 	untie(%disk_env);
1.5       www       673:     }
                    674:     return 'ok';
1.369     albertel  675: }
                    676: 
1.790     albertel  677: sub get_env_multiple {
                    678:     my ($name) = @_;
                    679:     my @values;
                    680:     if (defined($env{$name})) {
                    681:         # exists is it an array
                    682:         if (ref($env{$name})) {
                    683:             @values=@{ $env{$name} };
                    684:         } else {
                    685:             $values[0]=$env{$name};
                    686:         }
                    687:     }
                    688:     return(@values);
                    689: }
                    690: 
1.958     www       691: # ------------------------------------------------------------------- Locking
                    692: 
                    693: sub set_lock {
                    694:     my ($text)=@_;
                    695:     $locknum++;
                    696:     my $id=$$.'-'.$locknum;
                    697:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    698:              'session.lock.'.$id => $text});
                    699:     return $id;
                    700: }
                    701: 
                    702: sub get_locks {
                    703:     my $num=0;
                    704:     my %texts=();
                    705:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    706:        if ($lock=~/\w/) {
                    707:           $num++;
                    708:           $texts{$lock}=$env{'session.lock.'.$lock};
                    709:        }
                    710:    }
                    711:    return ($num,%texts);
                    712: }
                    713: 
                    714: sub remove_lock {
                    715:     my ($id)=@_;
                    716:     my $newlocks='';
                    717:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    718:        if (($lock=~/\w/) && ($lock ne $id)) {
                    719:           $newlocks.=','.$lock;
                    720:        }
                    721:     }
                    722:     &appenv({'session.locks' => $newlocks});
                    723:     &delenv('session.lock.'.$id);
                    724: }
                    725: 
                    726: sub remove_all_locks {
                    727:     my $activelocks=$env{'session.locks'};
                    728:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    729:        if ($lock=~/\w/) {
                    730:           &remove_lock($lock);
                    731:        }
                    732:     }
                    733: }
                    734: 
                    735: 
1.369     albertel  736: # ------------------------------------------ Find out current server userload
                    737: sub userload {
                    738:     my $numusers=0;
                    739:     {
                    740: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    741: 	my $filename;
                    742: 	my $curtime=time;
                    743: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  744: 	    next if ($filename eq '.' || $filename eq '..');
                    745: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  746: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  747: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  748: 	}
                    749: 	closedir(LONIDS);
                    750:     }
                    751:     my $userloadpercent=0;
                    752:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    753:     if ($maxuserload) {
1.371     albertel  754: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  755:     }
1.372     albertel  756:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  757:     return $userloadpercent;
1.283     www       758: }
                    759: 
1.1       albertel  760: # ------------------------------ Find server with least workload from spare.tab
1.11      www       761: 
1.1       albertel  762: sub spareserver {
1.1083    raeburn   763:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  764:     my $spare_server;
1.370     albertel  765:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  766:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    767:                                                      :  $userloadpercent;
1.1083    raeburn   768:     my ($uint_dom,$remotesessions);
                    769:     if (($udom ne '') && (&domain($udom) ne '')) {
                    770:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    771:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    772:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    773:         $remotesessions = $udomdefaults{'remotesessions'};
                    774:     }
1.784     albertel  775:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083    raeburn   776:         if ($uint_dom) {
                    777:              next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    778:                                           $try_server));
                    779:         }
1.784     albertel  780: 	($spare_server, $lowest_load) =
                    781: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    782:     }
                    783: 
                    784:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    785: 
                    786:     if (!$found_server) {
                    787: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1083    raeburn   788:             if ($uint_dom) {
                    789:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    790:                                              $try_server));
                    791:             }
1.784     albertel  792: 	    ($spare_server, $lowest_load) =
                    793: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    794: 	}
                    795:     }
                    796: 
                    797:     if (!$want_server_name) {
1.968     raeburn   798:         my $protocol = 'http';
                    799:         if ($protocol{$spare_server} eq 'https') {
                    800:             $protocol = $protocol{$spare_server};
                    801:         }
1.1001    raeburn   802:         if (defined($spare_server)) {
                    803:             my $hostname = &hostname($spare_server);
1.1083    raeburn   804:             if (defined($hostname)) {
1.1001    raeburn   805: 	        $spare_server = $protocol.'://'.$hostname;
                    806:             }
                    807:         }
1.784     albertel  808:     }
                    809:     return $spare_server;
                    810: }
                    811: 
                    812: sub compare_server_load {
                    813:     my ($try_server, $spare_server, $lowest_load) = @_;
                    814: 
                    815:     my $loadans     = &reply('load',    $try_server);
                    816:     my $userloadans = &reply('userload',$try_server);
                    817: 
                    818:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072    www       819: 	return; #didn't get a number from the server
1.784     albertel  820:     }
                    821: 
                    822:     my $load;
                    823:     if ($loadans =~ /\d/) {
                    824: 	if ($userloadans =~ /\d/) {
                    825: 	    #both are numbers, pick the bigger one
                    826: 	    $load = ($loadans > $userloadans) ? $loadans 
                    827: 		                              : $userloadans;
1.411     albertel  828: 	} else {
1.784     albertel  829: 	    $load = $loadans;
1.411     albertel  830: 	}
1.784     albertel  831:     } else {
                    832: 	$load = $userloadans;
                    833:     }
                    834: 
                    835:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    836: 	$spare_server = $try_server;
                    837: 	$lowest_load  = $load;
1.370     albertel  838:     }
1.784     albertel  839:     return ($spare_server,$lowest_load);
1.202     matthew   840: }
1.914     albertel  841: 
                    842: # --------------------------- ask offload servers if user already has a session
                    843: sub find_existing_session {
                    844:     my ($udom,$uname) = @_;
                    845:     foreach my $try_server (@{ $spareid{'primary'} },
                    846: 			    @{ $spareid{'default'} }) {
                    847: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    848:     }
                    849:     return;
                    850: }
                    851: 
                    852: # -------------------------------- ask if server already has a session for user
                    853: sub has_user_session {
                    854:     my ($lonid,$udom,$uname) = @_;
                    855:     my $result = &reply(join(':','userhassession',
                    856: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    857:     return 1 if ($result eq 'ok');
                    858: 
                    859:     return 0;
                    860: }
                    861: 
1.1076    raeburn   862: # --------- determine least loaded server in a user's domain which allows login
                    863: 
                    864: sub choose_server {
                    865:     my ($udom) = @_;
                    866:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   867:     my %servers = &get_servers($udom);
1.1076    raeburn   868:     my $lowest_load = 30000;
                    869:     my ($login_host,$hostname);
                    870:     foreach my $lonhost (keys(%servers)) {
                    871:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    872:         if ($loginvia eq '') {
                    873:             ($login_host, $lowest_load) =
                    874:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    875:         }
                    876:     }
                    877:     if ($login_host ne '') {
                    878:         $hostname = $servers{$login_host};
                    879:     }
                    880:     return ($login_host,$hostname);
                    881: }
                    882: 
1.202     matthew   883: # --------------------------------------------- Try to change a user's password
                    884: 
                    885: sub changepass {
1.799     raeburn   886:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   887:     $currentpass = &escape($currentpass);
                    888:     $newpass     = &escape($newpass);
1.1030    raeburn   889:     my $lonhost = $perlvar{'lonHostID'};
                    890:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   891: 		       $server);
                    892:     if (! $answer) {
                    893: 	&logthis("No reply on password change request to $server ".
                    894: 		 "by $uname in domain $udom.");
                    895:     } elsif ($answer =~ "^ok") {
                    896:         &logthis("$uname in $udom successfully changed their password ".
                    897: 		 "on $server.");
                    898:     } elsif ($answer =~ "^pwchange_failure") {
                    899: 	&logthis("$uname in $udom was unable to change their password ".
                    900: 		 "on $server.  The action was blocked by either lcpasswd ".
                    901: 		 "or pwchange");
                    902:     } elsif ($answer =~ "^non_authorized") {
                    903:         &logthis("$uname in $udom did not get their password correct when ".
                    904: 		 "attempting to change it on $server.");
                    905:     } elsif ($answer =~ "^auth_mode_error") {
                    906:         &logthis("$uname in $udom attempted to change their password despite ".
                    907: 		 "not being locally or internally authenticated on $server.");
                    908:     } elsif ($answer =~ "^unknown_user") {
                    909:         &logthis("$uname in $udom attempted to change their password ".
                    910: 		 "on $server but were unable to because $server is not ".
                    911: 		 "their home server.");
                    912:     } elsif ($answer =~ "^refused") {
                    913: 	&logthis("$server refused to change $uname in $udom password because ".
                    914: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   915:     } elsif ($answer =~ "invalid_client") {
                    916:         &logthis("$server refused to change $uname in $udom password because ".
                    917:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   918:     }
                    919:     return $answer;
1.1       albertel  920: }
                    921: 
1.169     harris41  922: # ----------------------- Try to determine user's current authentication scheme
                    923: 
                    924: sub queryauthenticate {
                    925:     my ($uname,$udom)=@_;
1.456     albertel  926:     my $uhome=&homeserver($uname,$udom);
                    927:     if (!$uhome) {
                    928: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    929: 	return 'no_host';
                    930:     }
                    931:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    932:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    933: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  934:     }
1.456     albertel  935:     return $answer;
1.169     harris41  936: }
                    937: 
1.1       albertel  938: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       939: 
1.1       albertel  940: sub authenticate {
1.1073    raeburn   941:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  942:     $upass=&escape($upass);
                    943:     $uname= &LONCAPA::clean_username($uname);
1.836     www       944:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   945:     my $newhome;
1.836     www       946:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    947: # Maybe the machine was offline and only re-appeared again recently?
                    948:         &reconlonc();
                    949: # One more
1.952     raeburn   950: 	$uhome=&homeserver($uname,$udom,1);
                    951:         if (($uhome eq 'no_host') && $checkdefauth) {
                    952:             if (defined(&domain($udom,'primary'))) {
                    953:                 $newhome=&domain($udom,'primary');
                    954:             }
                    955:             if ($newhome ne '') {
                    956:                 $uhome = $newhome;
                    957:             }
                    958:         }
1.836     www       959: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    960: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   961: 	    return 'no_host';
                    962:         }
1.1       albertel  963:     }
1.1073    raeburn   964:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  965:     if ($answer eq 'authorized') {
1.952     raeburn   966:         if ($newhome) {
                    967:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    968:             return 'no_account_on_host'; 
                    969:         } else {
                    970:             &logthis("User $uname at $udom authorized by $uhome");
                    971:             return $uhome;
                    972:         }
1.471     albertel  973:     }
                    974:     if ($answer eq 'non_authorized') {
                    975: 	&logthis("User $uname at $udom rejected by $uhome");
                    976: 	return 'no_host'; 
1.9       www       977:     }
1.471     albertel  978:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  979:     return 'no_host';
                    980: }
                    981: 
1.1073    raeburn   982: sub can_host_session {
1.1074    raeburn   983:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn   984:     my $canhost = 1;
1.1074    raeburn   985:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn   986:     if (ref($remotesessions) eq 'HASH') {
                    987:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn   988:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn   989:                 $canhost = 0;
                    990:             } else {
                    991:                 $canhost = 1;
                    992:             }
                    993:         }
                    994:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn   995:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn   996:                 $canhost = 1;
                    997:             } else {
                    998:                 $canhost = 0;
                    999:             }
                   1000:         }
                   1001:         if ($canhost) {
                   1002:             if ($remotesessions->{'version'} ne '') {
                   1003:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1004:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1005:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1006:                         my $major = $1;
                   1007:                         my $minor = $2;
                   1008:                         if (($major < $reqmajor ) ||
                   1009:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1010:                             $canhost = 0;
                   1011:                         }
                   1012:                     } else {
                   1013:                         $canhost = 0;
                   1014:                     }
                   1015:                 }
                   1016:             }
                   1017:         }
                   1018:     }
                   1019:     if ($canhost) {
                   1020:         if (ref($hostedsessions) eq 'HASH') {
                   1021:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                   1022:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                   1023:                     $canhost = 0;
                   1024:                 } else {
                   1025:                     $canhost = 1;
                   1026:                 }
                   1027:             }
                   1028:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                   1029:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                   1030:                     $canhost = 1;
                   1031:                 } else {
                   1032:                     $canhost = 0;
                   1033:                 }
                   1034:             }
                   1035:         }
                   1036:     }
                   1037:     return $canhost;
                   1038: }
                   1039: 
1.1083    raeburn  1040: sub spare_can_host {
                   1041:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1042:     my $canhost=1;
                   1043:     my @intdoms;
                   1044:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1045:     if (ref($internet_names) eq 'ARRAY') {
                   1046:         @intdoms = @{$internet_names};
                   1047:     }
                   1048:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1049:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1050:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1051:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1052:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1053:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1054:                                      $remotesessions,
                   1055:                                      $defdomdefaults{'hostedsessions'});
                   1056:     }
                   1057:     return $canhost;
                   1058: }
                   1059: 
1.1       albertel 1060: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1061: 
1.599     albertel 1062: my %homecache;
1.1       albertel 1063: sub homeserver {
1.230     stredwic 1064:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1065:     my $index="$uname:$udom";
1.426     albertel 1066: 
1.599     albertel 1067:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1068: 
                   1069:     my %servers = &get_servers($udom,'library');
                   1070:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1071:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1072: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1073: 
                   1074: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1075: 	if ($answer eq 'found') {
                   1076: 	    delete($badServerCache{$tryserver}); 
                   1077: 	    return $homecache{$index}=$tryserver;
                   1078: 	} elsif ($answer eq 'no_host') {
                   1079: 	    $badServerCache{$tryserver}=1;
                   1080: 	}
1.1       albertel 1081:     }    
                   1082:     return 'no_host';
1.70      www      1083: }
                   1084: 
                   1085: # ------------------------------------- Find the usernames behind a list of IDs
                   1086: 
                   1087: sub idget {
                   1088:     my ($udom,@ids)=@_;
                   1089:     my %returnhash=();
                   1090:     
1.841     albertel 1091:     my %servers = &get_servers($udom,'library');
                   1092:     foreach my $tryserver (keys(%servers)) {
                   1093: 	my $idlist=join('&',@ids);
                   1094: 	$idlist=~tr/A-Z/a-z/; 
                   1095: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1096: 	my @answer=();
                   1097: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1098: 	    @answer=split(/\&/,$reply);
                   1099: 	}                    ;
                   1100: 	my $i;
                   1101: 	for ($i=0;$i<=$#ids;$i++) {
                   1102: 	    if ($answer[$i]) {
                   1103: 		$returnhash{$ids[$i]}=$answer[$i];
                   1104: 	    } 
                   1105: 	}
                   1106:     } 
1.70      www      1107:     return %returnhash;
                   1108: }
                   1109: 
                   1110: # ------------------------------------- Find the IDs behind a list of usernames
                   1111: 
                   1112: sub idrget {
                   1113:     my ($udom,@unames)=@_;
                   1114:     my %returnhash=();
1.800     albertel 1115:     foreach my $uname (@unames) {
                   1116:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1117:     }
1.70      www      1118:     return %returnhash;
                   1119: }
                   1120: 
                   1121: # ------------------------------- Store away a list of names and associated IDs
                   1122: 
                   1123: sub idput {
                   1124:     my ($udom,%ids)=@_;
                   1125:     my %servers=();
1.800     albertel 1126:     foreach my $uname (keys(%ids)) {
                   1127: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1128:         my $uhom=&homeserver($uname,$udom);
1.70      www      1129:         if ($uhom ne 'no_host') {
1.800     albertel 1130:             my $id=&escape($ids{$uname});
1.70      www      1131:             $id=~tr/A-Z/a-z/;
1.800     albertel 1132:             my $esc_unam=&escape($uname);
1.70      www      1133: 	    if ($servers{$uhom}) {
1.800     albertel 1134: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1135:             } else {
1.800     albertel 1136:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1137:             }
                   1138:         }
1.191     harris41 1139:     }
1.800     albertel 1140:     foreach my $server (keys(%servers)) {
                   1141:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1142:     }
1.344     www      1143: }
                   1144: 
1.1023    raeburn  1145: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1146: sub dump_dom {
1.1023    raeburn  1147:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1148:     if (!$udom) {
                   1149:         $udom=$env{'user.domain'};
                   1150:     }
                   1151:     my %returnhash;
1.1023    raeburn  1152:     if ($udom) {
                   1153:         my $uname = &get_domainconfiguser($udom);
                   1154:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1155:     }
                   1156:     return %returnhash;
                   1157: }
                   1158: 
1.1023    raeburn  1159: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1160: 
                   1161: sub get_dom {
1.860     raeburn  1162:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1163:     my $items='';
                   1164:     foreach my $item (@$storearr) {
                   1165:         $items.=&escape($item).'&';
                   1166:     }
                   1167:     $items=~s/\&$//;
1.860     raeburn  1168:     if (!$udom) {
                   1169:         $udom=$env{'user.domain'};
                   1170:         if (defined(&domain($udom,'primary'))) {
                   1171:             $uhome=&domain($udom,'primary');
                   1172:         } else {
1.874     albertel 1173:             undef($uhome);
1.860     raeburn  1174:         }
                   1175:     } else {
                   1176:         if (!$uhome) {
                   1177:             if (defined(&domain($udom,'primary'))) {
                   1178:                 $uhome=&domain($udom,'primary');
                   1179:             }
                   1180:         }
                   1181:     }
                   1182:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1183:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1184:         my %returnhash;
1.875     albertel 1185:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1186:             return %returnhash;
                   1187:         }
1.806     raeburn  1188:         my @pairs=split(/\&/,$rep);
                   1189:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1190:             return @pairs;
                   1191:         }
                   1192:         my $i=0;
                   1193:         foreach my $item (@$storearr) {
                   1194:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1195:             $i++;
                   1196:         }
                   1197:         return %returnhash;
                   1198:     } else {
1.880     banghart 1199:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1200:     }
                   1201: }
                   1202: 
                   1203: # -------------------------------------------- put items in domain db files 
                   1204: 
                   1205: sub put_dom {
1.860     raeburn  1206:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1207:     if (!$udom) {
                   1208:         $udom=$env{'user.domain'};
                   1209:         if (defined(&domain($udom,'primary'))) {
                   1210:             $uhome=&domain($udom,'primary');
                   1211:         } else {
1.874     albertel 1212:             undef($uhome);
1.860     raeburn  1213:         }
                   1214:     } else {
                   1215:         if (!$uhome) {
                   1216:             if (defined(&domain($udom,'primary'))) {
                   1217:                 $uhome=&domain($udom,'primary');
                   1218:             }
                   1219:         }
                   1220:     } 
                   1221:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1222:         my $items='';
                   1223:         foreach my $item (keys(%$storehash)) {
                   1224:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1225:         }
                   1226:         $items=~s/\&$//;
                   1227:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1228:     } else {
1.860     raeburn  1229:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1230:     }
                   1231: }
                   1232: 
1.1023    raeburn  1233: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1234: sub newput_dom {
1.1023    raeburn  1235:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1236:     my $result;
                   1237:     if (!$udom) {
                   1238:         $udom=$env{'user.domain'};
                   1239:     }
1.1023    raeburn  1240:     if ($udom) {
                   1241:         my $uname = &get_domainconfiguser($udom);
                   1242:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1243:     }
                   1244:     return $result;
                   1245: }
                   1246: 
1.1023    raeburn  1247: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1248: sub del_dom {
1.1023    raeburn  1249:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1250:     if (ref($storearr) eq 'ARRAY') {
                   1251:         if (!$udom) {
                   1252:             $udom=$env{'user.domain'};
                   1253:         }
1.1023    raeburn  1254:         if ($udom) {
                   1255:             my $uname = &get_domainconfiguser($udom); 
                   1256:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1257:         }
                   1258:     }
                   1259: }
                   1260: 
1.1023    raeburn  1261: # ----------------------------------construct domainconfig user for a domain 
                   1262: sub get_domainconfiguser {
                   1263:     my ($udom) = @_;
                   1264:     return $udom.'-domainconfig';
                   1265: }
                   1266: 
1.837     raeburn  1267: sub retrieve_inst_usertypes {
                   1268:     my ($udom) = @_;
                   1269:     my (%returnhash,@order);
1.989     raeburn  1270:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1271:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1272:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1273:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1274:         @order = @{$domdefs{'inststatusorder'}};
                   1275:     } else {
                   1276:         if (defined(&domain($udom,'primary'))) {
                   1277:             my $uhome=&domain($udom,'primary');
                   1278:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1279:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1280:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1281:                 return (\%returnhash,\@order);
                   1282:             }
                   1283:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1284:             my @pairs=split(/\&/,$hashitems);
                   1285:             foreach my $item (@pairs) {
                   1286:                 my ($key,$value)=split(/=/,$item,2);
                   1287:                 $key = &unescape($key);
                   1288:                 next if ($key =~ /^error: 2 /);
                   1289:                 $returnhash{$key}=&thaw_unescape($value);
                   1290:             }
                   1291:             my @esc_order = split(/\&/,$orderitems);
                   1292:             foreach my $item (@esc_order) {
                   1293:                 push(@order,&unescape($item));
                   1294:             }
                   1295:         } else {
                   1296:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1297:         }
                   1298:     }
                   1299:     return (\%returnhash,\@order);
                   1300: }
                   1301: 
1.868     raeburn  1302: sub is_domainimage {
                   1303:     my ($url) = @_;
                   1304:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1305:         if (&domain($1) ne '') {
                   1306:             return '1';
                   1307:         }
                   1308:     }
                   1309:     return;
                   1310: }
                   1311: 
1.899     raeburn  1312: sub inst_directory_query {
                   1313:     my ($srch) = @_;
                   1314:     my $udom = $srch->{'srchdomain'};
                   1315:     my %results;
                   1316:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1317:     my $outcome;
1.899     raeburn  1318:     if ($homeserver ne '') {
1.904     albertel 1319: 	my $queryid=&reply("querysend:instdirsearch:".
                   1320: 			   &escape($srch->{'srchby'}).':'.
                   1321: 			   &escape($srch->{'srchterm'}).':'.
                   1322: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1323: 	my $host=&hostname($homeserver);
                   1324: 	if ($queryid !~/^\Q$host\E\_/) {
                   1325: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1326: 	    return;
                   1327: 	}
                   1328: 	my $response = &get_query_reply($queryid);
                   1329: 	my $maxtries = 5;
                   1330: 	my $tries = 1;
                   1331: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1332: 	    $response = &get_query_reply($queryid);
                   1333: 	    $tries ++;
                   1334: 	}
                   1335: 
                   1336:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1337:             if ($response eq 'unavailable') {
                   1338:                 $outcome = $response;
                   1339:             } else {
                   1340:                 $outcome = 'ok';
                   1341:                 my @matches = split(/\n/,$response);
                   1342:                 foreach my $match (@matches) {
                   1343:                     my ($key,$value) = split(/=/,$match);
                   1344:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1345:                 }
1.899     raeburn  1346:             }
                   1347:         }
                   1348:     }
1.909     raeburn  1349:     return ($outcome,%results);
1.899     raeburn  1350: }
                   1351: 
                   1352: sub usersearch {
                   1353:     my ($srch) = @_;
                   1354:     my $dom = $srch->{'srchdomain'};
                   1355:     my %results;
                   1356:     my %libserv = &all_library();
                   1357:     my $query = 'usersearch';
                   1358:     foreach my $tryserver (keys(%libserv)) {
                   1359:         if (&host_domain($tryserver) eq $dom) {
                   1360:             my $host=&hostname($tryserver);
                   1361:             my $queryid=
1.911     raeburn  1362:                 &reply("querysend:".&escape($query).':'.
                   1363:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1364:                        &escape($srch->{'srchtype'}).':'.
                   1365:                        &escape($srch->{'srchterm'}),$tryserver);
                   1366:             if ($queryid !~/^\Q$host\E\_/) {
                   1367:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1368:                 next;
1.899     raeburn  1369:             }
                   1370:             my $reply = &get_query_reply($queryid);
                   1371:             my $maxtries = 1;
                   1372:             my $tries = 1;
                   1373:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1374:                 $reply = &get_query_reply($queryid);
                   1375:                 $tries ++;
                   1376:             }
                   1377:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1378:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1379:             } else {
1.911     raeburn  1380:                 my @matches;
                   1381:                 if ($reply =~ /\n/) {
                   1382:                     @matches = split(/\n/,$reply);
                   1383:                 } else {
                   1384:                     @matches = split(/\&/,$reply);
                   1385:                 }
1.899     raeburn  1386:                 foreach my $match (@matches) {
                   1387:                     my ($uname,$udom,%userhash);
1.911     raeburn  1388:                     foreach my $entry (split(/:/,$match)) {
                   1389:                         my ($key,$value) =
                   1390:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1391:                         $userhash{$key} = $value;
                   1392:                         if ($key eq 'username') {
                   1393:                             $uname = $value;
                   1394:                         } elsif ($key eq 'domain') {
                   1395:                             $udom = $value;
1.911     raeburn  1396:                         }
1.899     raeburn  1397:                     }
                   1398:                     $results{$uname.':'.$udom} = \%userhash;
                   1399:                 }
                   1400:             }
                   1401:         }
                   1402:     }
                   1403:     return %results;
                   1404: }
                   1405: 
1.912     raeburn  1406: sub get_instuser {
                   1407:     my ($udom,$uname,$id) = @_;
                   1408:     my $homeserver = &domain($udom,'primary');
                   1409:     my ($outcome,%results);
                   1410:     if ($homeserver ne '') {
                   1411:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1412:                            &escape($id).':'.&escape($udom),$homeserver);
                   1413:         my $host=&hostname($homeserver);
                   1414:         if ($queryid !~/^\Q$host\E\_/) {
                   1415:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1416:             return;
                   1417:         }
                   1418:         my $response = &get_query_reply($queryid);
                   1419:         my $maxtries = 5;
                   1420:         my $tries = 1;
                   1421:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1422:             $response = &get_query_reply($queryid);
                   1423:             $tries ++;
                   1424:         }
                   1425:         if (!&error($response) && $response ne 'refused') {
                   1426:             if ($response eq 'unavailable') {
                   1427:                 $outcome = $response;
                   1428:             } else {
                   1429:                 $outcome = 'ok';
                   1430:                 my @matches = split(/\n/,$response);
                   1431:                 foreach my $match (@matches) {
                   1432:                     my ($key,$value) = split(/=/,$match);
                   1433:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1434:                 }
                   1435:             }
                   1436:         }
                   1437:     }
                   1438:     my %userinfo;
                   1439:     if (ref($results{$uname}) eq 'HASH') {
                   1440:         %userinfo = %{$results{$uname}};
                   1441:     } 
                   1442:     return ($outcome,%userinfo);
                   1443: }
                   1444: 
                   1445: sub inst_rulecheck {
1.923     raeburn  1446:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1447:     my %returnhash;
                   1448:     if ($udom ne '') {
                   1449:         if (ref($rules) eq 'ARRAY') {
                   1450:             @{$rules} = map {&escape($_);} (@{$rules});
                   1451:             my $rulestr = join(':',@{$rules});
                   1452:             my $homeserver=&domain($udom,'primary');
                   1453:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1454:                 my $response;
                   1455:                 if ($item eq 'username') {                
                   1456:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1457:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1458:                                               $homeserver));
1.923     raeburn  1459:                 } elsif ($item eq 'id') {
                   1460:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1461:                                               ':'.&escape($id).':'.$rulestr,
                   1462:                                               $homeserver));
1.945     raeburn  1463:                 } elsif ($item eq 'selfcreate') {
                   1464:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1465:                                                &escape($udom).':'.&escape($uname).
                   1466:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1467:                 }
1.912     raeburn  1468:                 if ($response ne 'refused') {
                   1469:                     my @pairs=split(/\&/,$response);
                   1470:                     foreach my $item (@pairs) {
                   1471:                         my ($key,$value)=split(/=/,$item,2);
                   1472:                         $key = &unescape($key);
                   1473:                         next if ($key =~ /^error: 2 /);
                   1474:                         $returnhash{$key}=&thaw_unescape($value);
                   1475:                     }
                   1476:                 }
                   1477:             }
                   1478:         }
                   1479:     }
                   1480:     return %returnhash;
                   1481: }
                   1482: 
                   1483: sub inst_userrules {
1.923     raeburn  1484:     my ($udom,$check) = @_;
1.912     raeburn  1485:     my (%ruleshash,@ruleorder);
                   1486:     if ($udom ne '') {
                   1487:         my $homeserver=&domain($udom,'primary');
                   1488:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1489:             my $response;
                   1490:             if ($check eq 'id') {
                   1491:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1492:                                  $homeserver);
1.943     raeburn  1493:             } elsif ($check eq 'email') {
                   1494:                 $response=&reply('instemailrules:'.&escape($udom),
                   1495:                                  $homeserver);
1.923     raeburn  1496:             } else {
                   1497:                 $response=&reply('instuserrules:'.&escape($udom),
                   1498:                                  $homeserver);
                   1499:             }
1.912     raeburn  1500:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1501:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1502:                 ($response ne 'no_such_host')) {
                   1503:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1504:                 my @pairs=split(/\&/,$hashitems);
                   1505:                 foreach my $item (@pairs) {
                   1506:                     my ($key,$value)=split(/=/,$item,2);
                   1507:                     $key = &unescape($key);
                   1508:                     next if ($key =~ /^error: 2 /);
                   1509:                     $ruleshash{$key}=&thaw_unescape($value);
                   1510:                 }
                   1511:                 my @esc_order = split(/\&/,$orderitems);
                   1512:                 foreach my $item (@esc_order) {
                   1513:                     push(@ruleorder,&unescape($item));
                   1514:                 }
                   1515:             }
                   1516:         }
                   1517:     }
                   1518:     return (\%ruleshash,\@ruleorder);
                   1519: }
                   1520: 
1.976     raeburn  1521: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1522: 
                   1523: sub get_domain_defaults {
                   1524:     my ($domain) = @_;
                   1525:     my $cachetime = 60*60*24;
                   1526:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1527:     if (defined($cached)) {
                   1528:         if (ref($result) eq 'HASH') {
                   1529:             return %{$result};
                   1530:         }
                   1531:     }
                   1532:     my %domdefaults;
                   1533:     my %domconfig =
1.989     raeburn  1534:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1535:                                   'requestcourses','inststatus',
1.1073    raeburn  1536:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1537:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1538:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1539:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1540:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1541:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1542:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1543:     } else {
                   1544:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1545:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1546:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1547:     }
1.976     raeburn  1548:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1549:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1550:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1551:         } else {
                   1552:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1553:         } 
                   1554:         my @usertools = ('aboutme','blog','portfolio');
                   1555:         foreach my $item (@usertools) {
                   1556:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1557:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1558:             }
                   1559:         }
                   1560:     }
1.985     raeburn  1561:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1562:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1563:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1564:         }
                   1565:     }
1.989     raeburn  1566:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1567:         foreach my $item ('inststatustypes','inststatusorder') {
                   1568:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1569:         }
                   1570:     }
1.1047    raeburn  1571:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1572:         foreach my $item ('canuse_pdfforms') {
                   1573:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1574:         }
                   1575:     }
1.1073    raeburn  1576:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1577:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1578:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1579:         }
                   1580:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1581:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1582:         }
                   1583:     }
1.943     raeburn  1584:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1585:                                   $cachetime);
                   1586:     return %domdefaults;
                   1587: }
                   1588: 
1.344     www      1589: # --------------------------------------------------- Assign a key to a student
                   1590: 
                   1591: sub assign_access_key {
1.364     www      1592: #
                   1593: # a valid key looks like uname:udom#comments
                   1594: # comments are being appended
                   1595: #
1.498     www      1596:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1597:     $kdom=
1.620     albertel 1598:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1599:     $knum=
1.620     albertel 1600:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1601:     $cdom=
1.620     albertel 1602:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1603:     $cnum=
1.620     albertel 1604:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1605:     $udom=$env{'user.name'} unless (defined($udom));
                   1606:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1607:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1608:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1609:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1610:                                                   # assigned to this person
                   1611:                                                   # - this should not happen,
1.345     www      1612:                                                   # unless something went wrong
                   1613:                                                   # the first time around
                   1614: # ready to assign
1.364     www      1615:         $logentry=$1.'; '.$logentry;
1.496     www      1616:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1617:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1618: # key now belongs to user
1.346     www      1619: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1620:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1621:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1622:                 return 'ok';
                   1623:             } else {
                   1624:                 return 
                   1625:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1626: 	    }
                   1627:         } else {
                   1628:             return 'error: Could not assign key, try again later.';
                   1629:         }
1.364     www      1630:     } elsif (!$existing{$ckey}) {
1.345     www      1631: # the key does not exist
                   1632: 	return 'error: The key does not exist';
                   1633:     } else {
                   1634: # the key is somebody else's
                   1635: 	return 'error: The key is already in use';
                   1636:     }
1.344     www      1637: }
                   1638: 
1.364     www      1639: # ------------------------------------------ put an additional comment on a key
                   1640: 
                   1641: sub comment_access_key {
                   1642: #
                   1643: # a valid key looks like uname:udom#comments
                   1644: # comments are being appended
                   1645: #
                   1646:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1647:     $cdom=
1.620     albertel 1648:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1649:     $cnum=
1.620     albertel 1650:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1651:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1652:     if ($existing{$ckey}) {
                   1653:         $existing{$ckey}.='; '.$logentry;
                   1654: # ready to assign
1.367     www      1655:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1656:                                                  $cdom,$cnum) eq 'ok') {
                   1657: 	    return 'ok';
                   1658:         } else {
                   1659: 	    return 'error: Count not store comment.';
                   1660:         }
                   1661:     } else {
                   1662: # the key does not exist
                   1663: 	return 'error: The key does not exist';
                   1664:     }
                   1665: }
                   1666: 
1.344     www      1667: # ------------------------------------------------------ Generate a set of keys
                   1668: 
                   1669: sub generate_access_keys {
1.364     www      1670:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1671:     $cdom=
1.620     albertel 1672:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1673:     $cnum=
1.620     albertel 1674:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1675:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1676:     unless (($cdom) && ($cnum)) { return 0; }
                   1677:     if ($number>10000) { return 0; }
                   1678:     sleep(2); # make sure don't get same seed twice
                   1679:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1680:     my $total=0;
                   1681:     for (my $i=1;$i<=$number;$i++) {
                   1682:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1683:                   sprintf("%lx",int(100000*rand)).'-'.
                   1684:                   sprintf("%lx",int(100000*rand));
                   1685:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1686:        $newkey=~s/0/h/g; # and also 0 and O
                   1687:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1688:        if ($existing{$newkey}) {
                   1689:            $i--;
                   1690:        } else {
1.364     www      1691: 	  if (&put('accesskeys',
                   1692:               { $newkey => '# generated '.localtime().
1.620     albertel 1693:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1694:                            '; '.$logentry },
                   1695: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1696:               $total++;
                   1697: 	  }
                   1698:        }
                   1699:     }
1.620     albertel 1700:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1701:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1702:     return $total;
                   1703: }
                   1704: 
                   1705: # ------------------------------------------------------- Validate an accesskey
                   1706: 
                   1707: sub validate_access_key {
                   1708:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1709:     $cdom=
1.620     albertel 1710:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1711:     $cnum=
1.620     albertel 1712:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1713:     $udom=$env{'user.domain'} unless (defined($udom));
                   1714:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1715:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1716:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1717: }
                   1718: 
                   1719: # ------------------------------------- Find the section of student in a course
1.652     albertel 1720: sub devalidate_getsection_cache {
                   1721:     my ($udom,$unam,$courseid)=@_;
                   1722:     my $hashid="$udom:$unam:$courseid";
                   1723:     &devalidate_cache_new('getsection',$hashid);
                   1724: }
1.298     matthew  1725: 
1.815     albertel 1726: sub courseid_to_courseurl {
                   1727:     my ($courseid) = @_;
                   1728:     #already url style courseid
                   1729:     return $courseid if ($courseid =~ m{^/});
                   1730: 
                   1731:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1732: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1733: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1734: 	return "/$cdom/$cnum";
                   1735:     }
                   1736: 
                   1737:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1738:     if (exists($courseinfo{'num'})) {
                   1739: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1740:     }
                   1741: 
                   1742:     return undef;
                   1743: }
                   1744: 
1.298     matthew  1745: sub getsection {
                   1746:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1747:     my $cachetime=1800;
1.551     albertel 1748: 
                   1749:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1750:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1751:     if (defined($cached)) { return $result; }
                   1752: 
1.298     matthew  1753:     my %Pending; 
                   1754:     my %Expired;
                   1755:     #
                   1756:     # Each role can either have not started yet (pending), be active, 
                   1757:     #    or have expired.
                   1758:     #
                   1759:     # If there is an active role, we are done.
                   1760:     #
                   1761:     # If there is more than one role which has not started yet, 
                   1762:     #     choose the one which will start sooner
                   1763:     # If there is one role which has not started yet, return it.
                   1764:     #
                   1765:     # If there is more than one expired role, choose the one which ended last.
                   1766:     # If there is a role which has expired, return it.
                   1767:     #
1.815     albertel 1768:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1769:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1770:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1771:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1772:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1773:         my $section=$1;
                   1774:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1775:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1776:         my $now=time;
1.548     albertel 1777:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1778:             $Expired{$end}=$section;
                   1779:             next;
                   1780:         }
1.548     albertel 1781:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1782:             $Pending{$start}=$section;
                   1783:             next;
                   1784:         }
1.599     albertel 1785:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1786:     }
                   1787:     #
                   1788:     # Presumedly there will be few matching roles from the above
                   1789:     # loop and the sorting time will be negligible.
                   1790:     if (scalar(keys(%Pending))) {
                   1791:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1792:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1793:     } 
                   1794:     if (scalar(keys(%Expired))) {
                   1795:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1796:         my $time = pop(@sorted);
1.599     albertel 1797:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1798:     }
1.599     albertel 1799:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1800: }
1.70      www      1801: 
1.599     albertel 1802: sub save_cache {
                   1803:     &purge_remembered();
1.722     albertel 1804:     #&Apache::loncommon::validate_page();
1.620     albertel 1805:     undef(%env);
1.780     albertel 1806:     undef($env_loaded);
1.599     albertel 1807: }
1.452     albertel 1808: 
1.599     albertel 1809: my $to_remember=-1;
                   1810: my %remembered;
                   1811: my %accessed;
                   1812: my $kicks=0;
                   1813: my $hits=0;
1.849     albertel 1814: sub make_key {
                   1815:     my ($name,$id) = @_;
1.872     albertel 1816:     if (length($id) > 65 
                   1817: 	&& length(&escape($id)) > 200) {
                   1818: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1819:     }
1.849     albertel 1820:     return &escape($name.':'.$id);
                   1821: }
                   1822: 
1.599     albertel 1823: sub devalidate_cache_new {
                   1824:     my ($name,$id,$debug) = @_;
                   1825:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1826:     $id=&make_key($name,$id);
1.599     albertel 1827:     $memcache->delete($id);
                   1828:     delete($remembered{$id});
                   1829:     delete($accessed{$id});
                   1830: }
                   1831: 
                   1832: sub is_cached_new {
                   1833:     my ($name,$id,$debug) = @_;
1.849     albertel 1834:     $id=&make_key($name,$id);
1.599     albertel 1835:     if (exists($remembered{$id})) {
                   1836: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1837: 	$accessed{$id}=[&gettimeofday()];
                   1838: 	$hits++;
                   1839: 	return ($remembered{$id},1);
                   1840:     }
                   1841:     my $value = $memcache->get($id);
                   1842:     if (!(defined($value))) {
                   1843: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1844: 	return (undef,undef);
1.416     albertel 1845:     }
1.599     albertel 1846:     if ($value eq '__undef__') {
                   1847: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1848: 	$value=undef;
                   1849:     }
                   1850:     &make_room($id,$value,$debug);
                   1851:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1852:     return ($value,1);
                   1853: }
                   1854: 
                   1855: sub do_cache_new {
                   1856:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1857:     $id=&make_key($name,$id);
1.599     albertel 1858:     my $setvalue=$value;
                   1859:     if (!defined($setvalue)) {
                   1860: 	$setvalue='__undef__';
                   1861:     }
1.623     albertel 1862:     if (!defined($time) ) {
                   1863: 	$time=600;
                   1864:     }
1.599     albertel 1865:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1866:     my $result = $memcache->set($id,$setvalue,$time);
                   1867:     if (! $result) {
1.872     albertel 1868: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1869: 	$memcache->disconnect_all();
1.872     albertel 1870:     }
1.600     albertel 1871:     # need to make a copy of $value
1.919     albertel 1872:     &make_room($id,$value,$debug);
1.599     albertel 1873:     return $value;
                   1874: }
                   1875: 
                   1876: sub make_room {
                   1877:     my ($id,$value,$debug)=@_;
1.919     albertel 1878: 
                   1879:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1880:                                     : $value;
1.599     albertel 1881:     if ($to_remember<0) { return; }
                   1882:     $accessed{$id}=[&gettimeofday()];
                   1883:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1884:     my $to_kick;
                   1885:     my $max_time=0;
                   1886:     foreach my $other (keys(%accessed)) {
                   1887: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1888: 	    $to_kick=$other;
                   1889: 	    $max_time=&tv_interval($accessed{$other});
                   1890: 	}
                   1891:     }
                   1892:     delete($remembered{$to_kick});
                   1893:     delete($accessed{$to_kick});
                   1894:     $kicks++;
                   1895:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1896:     return;
                   1897: }
                   1898: 
1.599     albertel 1899: sub purge_remembered {
1.604     albertel 1900:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1901:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1902:     undef(%remembered);
                   1903:     undef(%accessed);
1.428     albertel 1904: }
1.70      www      1905: # ------------------------------------- Read an entry from a user's environment
                   1906: 
                   1907: sub userenvironment {
                   1908:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1909:     my $items;
                   1910:     foreach my $item (@what) {
                   1911:         $items.=&escape($item).'&';
                   1912:     }
                   1913:     $items=~s/\&$//;
1.70      www      1914:     my %returnhash=();
1.1009    raeburn  1915:     my $uhome = &homeserver($unam,$udom);
                   1916:     unless ($uhome eq 'no_host') {
                   1917:         my @answer=split(/\&/, 
                   1918:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1919:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1920:             return %returnhash;
                   1921:         }
1.1009    raeburn  1922:         my $i;
                   1923:         for ($i=0;$i<=$#what;$i++) {
                   1924: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1925:         }
1.70      www      1926:     }
                   1927:     return %returnhash;
1.1       albertel 1928: }
                   1929: 
1.617     albertel 1930: # ---------------------------------------------------------- Get a studentphoto
                   1931: sub studentphoto {
                   1932:     my ($udom,$unam,$ext) = @_;
                   1933:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1934:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1935:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1936:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1937:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1938:             } else {
                   1939:                 my ($result,$perm_reqd)=
1.707     albertel 1940: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1941:                 if ($result eq 'ok') {
                   1942:                     if (!($perm_reqd eq 'yes')) {
                   1943:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1944:                     }
                   1945:                 }
                   1946:             }
                   1947:         }
                   1948:     } else {
                   1949:         my ($result,$perm_reqd) = 
1.707     albertel 1950: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1951:         if ($result eq 'ok') {
                   1952:             if (!($perm_reqd eq 'yes')) {
                   1953:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1954:             }
                   1955:         }
                   1956:     }
                   1957:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1958: }
                   1959: 
                   1960: sub retrievestudentphoto {
                   1961:     my ($udom,$unam,$ext,$type) = @_;
                   1962:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1963:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1964:     if ($ret eq 'ok') {
                   1965:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1966:         if ($type eq 'thumbnail') {
                   1967:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1968:         }
                   1969:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1970:         return $tokenurl;
                   1971:     } else {
                   1972:         if ($type eq 'thumbnail') {
                   1973:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1974:         } else { 
                   1975:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1976:         }
1.617     albertel 1977:     }
                   1978: }
                   1979: 
1.263     www      1980: # -------------------------------------------------------------------- New chat
                   1981: 
                   1982: sub chatsend {
1.724     raeburn  1983:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1984:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1985:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1986:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1987:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1988: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1989: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1990: }
                   1991: 
                   1992: # ------------------------------------------ Find current version of a resource
                   1993: 
                   1994: sub getversion {
                   1995:     my $fname=&clutter(shift);
                   1996:     unless ($fname=~/^\/res\//) { return -1; }
                   1997:     return &currentversion(&filelocation('',$fname));
                   1998: }
                   1999: 
                   2000: sub currentversion {
                   2001:     my $fname=shift;
                   2002:     my $author=$fname;
                   2003:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2004:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2005:     my $home=&homeserver($uname,$udom);
1.292     www      2006:     if ($home eq 'no_host') { 
                   2007:         return -1; 
                   2008:     }
1.1112    www      2009:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2010:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2011: 	return -1;
                   2012:     }
1.1112    www      2013:     return $answer;
1.263     www      2014: }
                   2015: 
1.1111    www      2016: #
                   2017: # Return special version number of resource if set by override, empty otherwise
                   2018: #
                   2019: sub usedversion {
                   2020:     my $fname=shift;
                   2021:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2022:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2023:     if ($urlversion) { return $urlversion; }
                   2024:     return '';
                   2025: }
                   2026: 
1.1       albertel 2027: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2028: 
1.1       albertel 2029: sub subscribe {
                   2030:     my $fname=shift;
1.761     raeburn  2031:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2032:     $fname=~s/[\n\r]//g;
1.1       albertel 2033:     my $author=$fname;
                   2034:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2035:     my ($udom,$uname)=split(/\//,$author);
                   2036:     my $home=homeserver($uname,$udom);
1.335     albertel 2037:     if ($home eq 'no_host') {
                   2038:         return 'not_found';
1.1       albertel 2039:     }
                   2040:     my $answer=reply("sub:$fname",$home);
1.64      www      2041:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2042: 	$answer.=' by '.$home;
                   2043:     }
1.1       albertel 2044:     return $answer;
                   2045: }
                   2046:     
1.8       www      2047: # -------------------------------------------------------------- Replicate file
                   2048: 
                   2049: sub repcopy {
                   2050:     my $filename=shift;
1.23      www      2051:     $filename=~s/\/+/\//g;
1.607     raeburn  2052:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2053:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2054:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2055: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2056: 	return &repcopy_userfile($filename);
                   2057:     }
1.532     albertel 2058:     $filename=~s/[\n\r]//g;
1.8       www      2059:     my $transname="$filename.in.transfer";
1.828     www      2060: # FIXME: this should flock
1.607     raeburn  2061:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2062:     my $remoteurl=subscribe($filename);
1.64      www      2063:     if ($remoteurl =~ /^con_lost by/) {
                   2064: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2065:            return 'unavailable';
1.8       www      2066:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2067: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2068: 	   return 'not_found';
1.64      www      2069:     } elsif ($remoteurl =~ /^rejected by/) {
                   2070: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2071:            return 'forbidden';
1.20      www      2072:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2073:            return 'ok';
1.8       www      2074:     } else {
1.290     www      2075:         my $author=$filename;
                   2076:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2077:         my ($udom,$uname)=split(/\//,$author);
                   2078:         my $home=homeserver($uname,$udom);
                   2079:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2080:            my @parts=split(/\//,$filename);
                   2081:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2082:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2083:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2084: 	       return 'bad_request';
1.8       www      2085:            }
                   2086:            my $count;
                   2087:            for ($count=5;$count<$#parts;$count++) {
                   2088:                $path.="/$parts[$count]";
                   2089:                if ((-e $path)!=1) {
                   2090: 		   mkdir($path,0777);
                   2091:                }
                   2092:            }
                   2093:            my $ua=new LWP::UserAgent;
                   2094:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2095:            my $response=$ua->request($request,$transname);
                   2096:            if ($response->is_error()) {
                   2097: 	       unlink($transname);
                   2098:                my $message=$response->status_line;
1.672     albertel 2099:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2100:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2101:                return 'unavailable';
1.8       www      2102:            } else {
1.16      www      2103: 	       if ($remoteurl!~/\.meta$/) {
                   2104:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2105:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2106:                   if ($mresponse->is_error()) {
                   2107: 		      unlink($filename.'.meta');
                   2108:                       &logthis(
1.672     albertel 2109:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2110:                   }
                   2111: 	       }
1.8       www      2112:                rename($transname,$filename);
1.607     raeburn  2113:                return 'ok';
1.8       www      2114:            }
1.290     www      2115:        }
1.8       www      2116:     }
1.330     www      2117: }
                   2118: 
                   2119: # ------------------------------------------------ Get server side include body
                   2120: sub ssi_body {
1.381     albertel 2121:     my ($filelink,%form)=@_;
1.606     matthew  2122:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2123:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2124:     }
1.953     www      2125:     my $output='';
                   2126:     my $response;
1.980     raeburn  2127:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2128:        ($output,$response)=&externalssi($filelink);
1.953     www      2129:     } else {
1.1004    droeschl 2130:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2131:        $filelink .= 'inhibitmenu=yes';
1.953     www      2132:        ($output,$response)=&ssi($filelink,%form);
                   2133:     }
1.778     albertel 2134:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2135:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2136:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2137:     if (wantarray) {
                   2138:         return ($output, $response);
                   2139:     } else {
                   2140:         return $output;
                   2141:     }
1.8       www      2142: }
                   2143: 
1.15      www      2144: # --------------------------------------------------------- Server Side Include
                   2145: 
1.782     albertel 2146: sub absolute_url {
                   2147:     my ($host_name) = @_;
                   2148:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2149:     if ($host_name eq '') {
                   2150: 	$host_name = $ENV{'SERVER_NAME'};
                   2151:     }
                   2152:     return $protocol.$host_name;
                   2153: }
                   2154: 
1.942     foxr     2155: #
                   2156: #   Server side include.
                   2157: # Parameters:
                   2158: #  fn     Possibly encrypted resource name/id.
                   2159: #  form   Hash that describes how the rendering should be done
                   2160: #         and other things.
1.944     foxr     2161: # Returns:
1.950     raeburn  2162: #   Scalar context: The content of the response.
                   2163: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2164: #     
1.15      www      2165: sub ssi {
                   2166: 
1.944     foxr     2167:     my ($fn,%form)=@_;
1.15      www      2168:     my $ua=new LWP::UserAgent;
1.23      www      2169:     my $request;
1.711     albertel 2170: 
                   2171:     $form{'no_update_last_known'}=1;
1.895     albertel 2172:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2173:     if (%form) {
1.782     albertel 2174:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2175:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2176:     } else {
1.782     albertel 2177:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2178:     }
                   2179: 
1.15      www      2180:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2181:     my $response=$ua->request($request);
                   2182: 
1.944     foxr     2183:     if (wantarray) {
                   2184: 	return ($response->content, $response);
                   2185:     } else {
                   2186: 	return $response->content;
1.942     foxr     2187:     }
1.324     www      2188: }
                   2189: 
                   2190: sub externalssi {
                   2191:     my ($url)=@_;
                   2192:     my $ua=new LWP::UserAgent;
                   2193:     my $request=new HTTP::Request('GET',$url);
                   2194:     my $response=$ua->request($request);
1.954     raeburn  2195:     if (wantarray) {
                   2196:         return ($response->content, $response);
                   2197:     } else {
                   2198:         return $response->content;
                   2199:     }
1.15      www      2200: }
1.254     www      2201: 
1.492     albertel 2202: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2203: 
                   2204: sub allowuploaded {
                   2205:     my ($srcurl,$url)=@_;
                   2206:     $url=&clutter(&declutter($url));
                   2207:     my $dir=$url;
                   2208:     $dir=~s/\/[^\/]+$//;
                   2209:     my %httpref=();
                   2210:     my $httpurl=&hreflocation('',$url);
                   2211:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2212:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2213: }
1.477     raeburn  2214: 
1.478     albertel 2215: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2216: # input: action, courseID, current domain, intended
1.637     raeburn  2217: #        path to file, source of file, instruction to parse file for objects,
                   2218: #        ref to hash for embedded objects,
                   2219: #        ref to hash for codebase of java objects.
1.1095    raeburn  2220: #        reference to scalar to accommodate mime type determined
                   2221: #          from File::MMagic if $parser = parse.
1.637     raeburn  2222: #
1.485     raeburn  2223: # output: url to file (if action was uploaddoc), 
                   2224: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2225: #
1.478     albertel 2226: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2227: # course.
1.477     raeburn  2228: #
1.478     albertel 2229: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2230: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2231: #          course's home server.
1.477     raeburn  2232: #
1.478     albertel 2233: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2234: #          be copied from $source (current location) to 
                   2235: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2236: #         and will then be copied to
                   2237: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2238: #         course's home server.
1.485     raeburn  2239: #
1.481     raeburn  2240: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2241: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2242: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2243: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2244: #         in course's home server.
1.637     raeburn  2245: #
1.477     raeburn  2246: 
                   2247: sub process_coursefile {
1.1095    raeburn  2248:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2249:         $mimetype)=@_;
1.477     raeburn  2250:     my $fetchresult;
1.638     albertel 2251:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2252:     if ($action eq 'propagate') {
1.638     albertel 2253:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2254: 			     $home);
1.481     raeburn  2255:     } else {
1.477     raeburn  2256:         my $fpath = '';
                   2257:         my $fname = $file;
1.478     albertel 2258:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2259:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2260:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2261:         if ($action eq 'copy') {
                   2262:             if ($source eq '') {
                   2263:                 $fetchresult = 'no source file';
                   2264:                 return $fetchresult;
                   2265:             } else {
                   2266:                 my $destination = $filepath.'/'.$fname;
                   2267:                 rename($source,$destination);
                   2268:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2269:                                  $home);
1.481     raeburn  2270:             }
                   2271:         } elsif ($action eq 'uploaddoc') {
                   2272:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2273:             print $fh $env{'form.'.$source};
1.481     raeburn  2274:             close($fh);
1.637     raeburn  2275:             if ($parser eq 'parse') {
1.1024    raeburn  2276:                 my $mm = new File::MMagic;
1.1095    raeburn  2277:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2278:                 if ($type eq 'text/html') {
1.1024    raeburn  2279:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2280:                     unless ($parse_result eq 'ok') {
                   2281:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2282:                     }
1.637     raeburn  2283:                 }
1.1095    raeburn  2284:                 if (ref($mimetype)) {
                   2285:                     $$mimetype = $type;
                   2286:                 } 
1.637     raeburn  2287:             }
1.477     raeburn  2288:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2289:                                  $home);
1.481     raeburn  2290:             if ($fetchresult eq 'ok') {
                   2291:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2292:             } else {
                   2293:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2294:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2295:                 return '/adm/notfound.html';
                   2296:             }
1.477     raeburn  2297:         }
                   2298:     }
1.485     raeburn  2299:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2300:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2301:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2302:     }
                   2303:     return $fetchresult;
                   2304: }
                   2305: 
1.637     raeburn  2306: sub build_filepath {
                   2307:     my ($fpath) = @_;
                   2308:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2309:     unless ($fpath eq '') {
                   2310:         my @parts=split('/',$fpath);
                   2311:         foreach my $part (@parts) {
                   2312:             $filepath.= '/'.$part;
                   2313:             if ((-e $filepath)!=1) {
                   2314:                 mkdir($filepath,0777);
                   2315:             }
                   2316:         }
                   2317:     }
                   2318:     return $filepath;
                   2319: }
                   2320: 
                   2321: sub store_edited_file {
1.638     albertel 2322:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2323:     my $file = $primary_url;
                   2324:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2325:     my $fpath = '';
                   2326:     my $fname = $file;
                   2327:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2328:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2329:     my $filepath = &build_filepath($fpath);
                   2330:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2331:     print $fh $content;
                   2332:     close($fh);
1.638     albertel 2333:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2334:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2335: 			  $home);
1.637     raeburn  2336:     if ($$fetchresult eq 'ok') {
                   2337:         return '/uploaded/'.$fpath.'/'.$fname;
                   2338:     } else {
1.638     albertel 2339:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2340: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2341:         return '/adm/notfound.html';
                   2342:     }
                   2343: }
                   2344: 
1.531     albertel 2345: sub clean_filename {
1.831     albertel 2346:     my ($fname,$args)=@_;
1.315     www      2347: # Replace Windows backslashes by forward slashes
1.257     www      2348:     $fname=~s/\\/\//g;
1.831     albertel 2349:     if (!$args->{'keep_path'}) {
                   2350:         # Get rid of everything but the actual filename
                   2351: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2352:     }
1.315     www      2353: # Replace spaces by underscores
                   2354:     $fname=~s/\s+/\_/g;
                   2355: # Replace all other weird characters by nothing
1.831     albertel 2356:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2357: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2358: # numbers
                   2359:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2360:     return $fname;
                   2361: }
1.1051    raeburn  2362: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2363: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2364: # image with the same aspect ratio as the original, but with dimensions which do 
                   2365: # not exceed $resizewidth and $resizeheight.
                   2366:  
1.984     neumanie 2367: sub resizeImage {
1.1051    raeburn  2368:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2369:     my $ima = Image::Magick->new;
                   2370:     my $resized;
                   2371:     if (-e $img_path) {
                   2372:         $ima->Read($img_path);
                   2373:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2374:             my $width = $ima->Get('width');
                   2375:             my $height = $ima->Get('height');
                   2376:             if ($width > $resizewidth) {
                   2377: 	        my $factor = $width/$resizewidth;
                   2378:                 my $newheight = $height/$factor;
                   2379:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2380:                 $resized = 1;
                   2381:             }
                   2382:         }
                   2383:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2384:             my $width = $ima->Get('width');
                   2385:             my $height = $ima->Get('height');
                   2386:             if ($height > $resizeheight) {
                   2387:                 my $factor = $height/$resizeheight;
                   2388:                 my $newwidth = $width/$factor;
                   2389:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2390:                 $resized = 1;
                   2391:             }
                   2392:         }
                   2393:         if ($resized) {
                   2394:             $ima->Write($img_path);
                   2395:         }
                   2396:     }
                   2397:     return;
1.977     amueller 2398: }
                   2399: 
1.608     albertel 2400: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2401: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2402: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2403: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2404: #                                    canceloverwrite, or ''. 
                   2405: #                   if 'coursedoc': upload to the current course
                   2406: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2407: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2408: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2409: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2410: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2411: #        $allfiles - reference to hash for embedded objects
                   2412: #        $codebase - reference to hash for codebase of java objects
                   2413: #        $desuname - username for permanent storage of uploaded file
                   2414: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2415: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2416: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2417: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2418: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2419: #        $mimetype - reference to scalar to accommodate mime type determined
                   2420: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2421: # 
1.686     albertel 2422: # output: url of file in userspace, or error: <message> 
                   2423: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2424: 
1.531     albertel 2425: sub userfileupload {
1.1090    raeburn  2426:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2427:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2428:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2429:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2430:     $fname=&clean_filename($fname);
1.1090    raeburn  2431:     # See if there is anything left
1.257     www      2432:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2433:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2434:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2435:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2436:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2437:         my $now = time;
1.1090    raeburn  2438:         my $filepath;
1.1095    raeburn  2439:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2440:              $filepath = 'tmp/helprequests/'.$now;
                   2441:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2442:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2443:                          '_'.$env{'user.domain'}.'/pending';
                   2444:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2445:             my ($docuname,$docudom);
                   2446:             if ($destudom) {
                   2447:                 $docudom = $destudom;
                   2448:             } else {
                   2449:                 $docudom = $env{'user.domain'};
                   2450:             }
                   2451:             if ($destuname) {
                   2452:                 $docuname = $destuname;
                   2453:             } else {
                   2454:                 $docuname = $env{'user.name'};
                   2455:             }
                   2456:             if (exists($env{'form.group'})) {
                   2457:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2458:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2459:             }
                   2460:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2461:             if ($context eq 'canceloverwrite') {
                   2462:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2463:                 if (-e  $tempfile) {
                   2464:                     my @info = stat($tempfile);
                   2465:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2466:                         unlink($tempfile);
                   2467:                     }
                   2468:                 }
                   2469:                 return;
1.523     raeburn  2470:             }
                   2471:         }
1.1090    raeburn  2472:         # Create the directory if not present
1.741     raeburn  2473:         my @parts=split(/\//,$filepath);
                   2474:         my $fullpath = $perlvar{'lonDaemons'};
                   2475:         for (my $i=0;$i<@parts;$i++) {
                   2476:             $fullpath .= '/'.$parts[$i];
                   2477:             if ((-e $fullpath)!=1) {
                   2478:                 mkdir($fullpath,0777);
                   2479:             }
                   2480:         }
                   2481:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2482:         print $fh $env{'form.'.$formname};
                   2483:         close($fh);
1.1090    raeburn  2484:         if ($context eq 'existingfile') {
                   2485:             my @info = stat($fullpath.'/'.$fname);
                   2486:             return ($fullpath.'/'.$fname,$info[9]);
                   2487:         } else {
                   2488:             return $fullpath.'/'.$fname;
                   2489:         }
1.523     raeburn  2490:     }
1.995     raeburn  2491:     if ($subdir eq 'scantron') {
                   2492:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2493:     } else {
1.995     raeburn  2494:         $fname="$subdir/$fname";
                   2495:     }
1.1090    raeburn  2496:     if ($context eq 'coursedoc') {
1.638     albertel 2497: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2498: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2499:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2500:             return &finishuserfileupload($docuname,$docudom,
                   2501: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2502: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2503:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2504:         } else {
1.620     albertel 2505:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2506:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2507: 				       $fname,$formname,$parser,
1.1095    raeburn  2508: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2509:         }
1.719     banghart 2510:     } elsif (defined($destuname)) {
                   2511:         my $docuname=$destuname;
                   2512:         my $docudom=$destudom;
1.860     raeburn  2513: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2514: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2515:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2516:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2517:     } else {
1.638     albertel 2518:         my $docuname=$env{'user.name'};
                   2519:         my $docudom=$env{'user.domain'};
1.714     raeburn  2520:         if (exists($env{'form.group'})) {
                   2521:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2522:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2523:         }
1.860     raeburn  2524: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2525: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2526:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2527:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2528:     }
1.271     www      2529: }
                   2530: 
                   2531: sub finishuserfileupload {
1.860     raeburn  2532:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2533:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2534:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2535:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2536:   
1.860     raeburn  2537:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2538:     $file=$fname;
                   2539:     if ($fname=~m|/|) {
                   2540:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2541: 	$path.=$fnamepath.'/';
                   2542:     }
1.259     www      2543:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2544:     my $count;
                   2545:     for ($count=4;$count<=$#parts;$count++) {
                   2546:         $filepath.="/$parts[$count]";
                   2547:         if ((-e $filepath)!=1) {
                   2548: 	    mkdir($filepath,0777);
                   2549:         }
                   2550:     }
1.984     neumanie 2551: 
1.258     www      2552: # Save the file
                   2553:     {
1.701     albertel 2554: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2555: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2556: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2557: 	    return '/adm/notfound.html';
                   2558: 	}
1.1090    raeburn  2559:         if ($context eq 'overwrite') {
                   2560:             my $source =  $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
                   2561:             my $target = $filepath.'/'.$file;
                   2562:             if (-e $source) {
                   2563:                 my @info = stat($source);
                   2564:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2565:                     unless (&File::Copy::move($source,$target)) {
                   2566:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2567:                         return "Moving from $source failed";
                   2568:                     }
                   2569:                 } else {
                   2570:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2571:                 }
                   2572:             } else {
                   2573:                 return "Temporary file: $source missing";
                   2574:             }
                   2575:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2576: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2577: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2578: 	    return '/adm/notfound.html';
                   2579: 	}
1.570     albertel 2580: 	close(FH);
1.1051    raeburn  2581:         if ($resizewidth && $resizeheight) {
                   2582:             my $mm = new File::MMagic;
                   2583:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2584:             if ($mime_type =~ m{^image/}) {
                   2585: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2586:             }  
1.977     amueller 2587: 	}
1.258     www      2588:     }
1.637     raeburn  2589:     if ($parser eq 'parse') {
1.1024    raeburn  2590:         my $mm = new File::MMagic;
1.1095    raeburn  2591:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2592:         if ($type eq 'text/html') {
1.1024    raeburn  2593:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2594:                                                        $allfiles,$codebase);
                   2595:             unless ($parse_result eq 'ok') {
                   2596:                 &logthis('Failed to parse '.$filepath.$file.
                   2597: 	   	         ' for embedded media: '.$parse_result); 
                   2598:             }
1.637     raeburn  2599:         }
1.1095    raeburn  2600:         if (ref($mimetype)) {
                   2601:             $$mimetype = $type;
                   2602:         }
1.637     raeburn  2603:     }
1.860     raeburn  2604:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2605:         my $input = $filepath.'/'.$file;
                   2606:         my $output = $filepath.'/'.'tn-'.$file;
                   2607:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2608:         system("convert -sample $thumbsize $input $output");
                   2609:         if (-e $filepath.'/'.'tn-'.$file) {
                   2610:             $fetchthumb  = 1; 
                   2611:         }
                   2612:     }
1.858     raeburn  2613:  
1.259     www      2614: # Notify homeserver to grep it
                   2615: #
1.984     neumanie 2616:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2617:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2618:     if ($fetchresult eq 'ok') {
1.860     raeburn  2619:         if ($fetchthumb) {
                   2620:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2621:             if ($thumbresult ne 'ok') {
                   2622:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2623:                          $docuhome.': '.$thumbresult);
                   2624:             }
                   2625:         }
1.259     www      2626: #
1.258     www      2627: # Return the URL to it
1.494     albertel 2628:         return '/uploaded/'.$path.$file;
1.263     www      2629:     } else {
1.494     albertel 2630:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2631: 		 ': '.$fetchresult);
1.263     www      2632:         return '/adm/notfound.html';
1.858     raeburn  2633:     }
1.493     albertel 2634: }
                   2635: 
1.637     raeburn  2636: sub extract_embedded_items {
1.961     raeburn  2637:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2638:     my @state = ();
                   2639:     my %javafiles = (
                   2640:                       codebase => '',
                   2641:                       code => '',
                   2642:                       archive => ''
                   2643:                     );
                   2644:     my %mediafiles = (
                   2645:                       src => '',
                   2646:                       movie => '',
                   2647:                      );
1.648     raeburn  2648:     my $p;
                   2649:     if ($content) {
                   2650:         $p = HTML::LCParser->new($content);
                   2651:     } else {
1.961     raeburn  2652:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2653:     }
1.641     albertel 2654:     while (my $t=$p->get_token()) {
1.640     albertel 2655: 	if ($t->[0] eq 'S') {
                   2656: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2657: 	    push(@state, $tagname);
1.648     raeburn  2658:             if (lc($tagname) eq 'allow') {
                   2659:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2660:             }
1.640     albertel 2661: 	    if (lc($tagname) eq 'img') {
                   2662: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2663: 	    }
1.886     albertel 2664: 	    if (lc($tagname) eq 'a') {
                   2665: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2666: 	    }
1.645     raeburn  2667:             if (lc($tagname) eq 'script') {
                   2668:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2669:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2670:                 } else {
                   2671:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2672:                 }
                   2673:             }
                   2674:             if (lc($tagname) eq 'link') {
                   2675:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2676:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2677:                 }
                   2678:             }
1.640     albertel 2679: 	    if (lc($tagname) eq 'object' ||
                   2680: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2681: 		foreach my $item (keys(%javafiles)) {
                   2682: 		    $javafiles{$item} = '';
                   2683: 		}
                   2684: 	    }
                   2685: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2686: 		my $name = lc($attr->{'name'});
                   2687: 		foreach my $item (keys(%javafiles)) {
                   2688: 		    if ($name eq $item) {
                   2689: 			$javafiles{$item} = $attr->{'value'};
                   2690: 			last;
                   2691: 		    }
                   2692: 		}
                   2693: 		foreach my $item (keys(%mediafiles)) {
                   2694: 		    if ($name eq $item) {
                   2695: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2696: 			last;
                   2697: 		    }
                   2698: 		}
                   2699: 	    }
                   2700: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2701: 		foreach my $item (keys(%javafiles)) {
                   2702: 		    if ($attr->{$item}) {
                   2703: 			$javafiles{$item} = $attr->{$item};
                   2704: 			last;
                   2705: 		    }
                   2706: 		}
                   2707: 		foreach my $item (keys(%mediafiles)) {
                   2708: 		    if ($attr->{$item}) {
                   2709: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2710: 			last;
                   2711: 		    }
                   2712: 		}
                   2713: 	    }
                   2714: 	} elsif ($t->[0] eq 'E') {
                   2715: 	    my ($tagname) = ($t->[1]);
                   2716: 	    if ($javafiles{'codebase'} ne '') {
                   2717: 		$javafiles{'codebase'} .= '/';
                   2718: 	    }  
                   2719: 	    if (lc($tagname) eq 'applet' ||
                   2720: 		lc($tagname) eq 'object' ||
                   2721: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2722: 		) {
                   2723: 		foreach my $item (keys(%javafiles)) {
                   2724: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2725: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2726: 			&add_filetype($allfiles,$file,$item);
                   2727: 		    }
                   2728: 		}
                   2729: 	    } 
                   2730: 	    pop @state;
                   2731: 	}
                   2732:     }
1.637     raeburn  2733:     return 'ok';
                   2734: }
                   2735: 
1.639     albertel 2736: sub add_filetype {
                   2737:     my ($allfiles,$file,$type)=@_;
                   2738:     if (exists($allfiles->{$file})) {
                   2739: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2740: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2741: 	}
                   2742:     } else {
                   2743: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2744:     }
                   2745: }
                   2746: 
1.493     albertel 2747: sub removeuploadedurl {
1.984     neumanie 2748:     my ($url)=@_;	
                   2749:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2750:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2751: }
                   2752: 
                   2753: sub removeuserfile {
                   2754:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2755:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2756:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2757:     if ($result eq 'ok') {	
1.798     raeburn  2758:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2759:             my $metafile = $fname.'.meta';
                   2760:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2761: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2762:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2763:             my $sqlresult = 
1.823     albertel 2764:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2765:                                         'portfolio_metadata',$group,
                   2766:                                         'delete');
1.798     raeburn  2767:         }
                   2768:     }
                   2769:     return $result;
1.257     www      2770: }
1.15      www      2771: 
1.530     albertel 2772: sub mkdiruserfile {
                   2773:     my ($docuname,$docudom,$dir)=@_;
                   2774:     my $home=&homeserver($docuname,$docudom);
                   2775:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2776: }
                   2777: 
1.531     albertel 2778: sub renameuserfile {
                   2779:     my ($docuname,$docudom,$old,$new)=@_;
                   2780:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2781:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2782:                         &escape("$old").':'.&escape("$new"),$home);
                   2783:     if ($result eq 'ok') {
                   2784:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2785:             my $oldmeta = $old.'.meta';
                   2786:             my $newmeta = $new.'.meta';
                   2787:             my $metaresult = 
                   2788:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2789: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2790:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2791:             my $sqlresult = 
1.823     albertel 2792:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2793:                                         'portfolio_metadata',$group,
                   2794:                                         'delete');
1.798     raeburn  2795:         }
                   2796:     }
                   2797:     return $result;
1.531     albertel 2798: }
                   2799: 
1.14      www      2800: # ------------------------------------------------------------------------- Log
                   2801: 
                   2802: sub log {
                   2803:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2804:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2805: }
                   2806: 
                   2807: # ------------------------------------------------------------------ Course Log
1.352     www      2808: #
                   2809: # This routine flushes several buffers of non-mission-critical nature
                   2810: #
1.157     www      2811: 
                   2812: sub flushcourselogs {
1.352     www      2813:     &logthis('Flushing log buffers');
                   2814: #
                   2815: # course logs
                   2816: # This is a log of all transactions in a course, which can be used
                   2817: # for data mining purposes
                   2818: #
                   2819: # It also collects the courseid database, which lists last transaction
                   2820: # times and course titles for all courseids
                   2821: #
                   2822:     my %courseidbuffer=();
1.921     raeburn  2823:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2824:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2825: 		          &escape($courselogs{$crsid}),
                   2826: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2827: 	    delete $courselogs{$crsid};
                   2828:         } else {
                   2829:             &logthis('Failed to flush log buffer for '.$crsid);
                   2830:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2831:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2832:                         " exceeded maximum size, deleting.</font>");
                   2833:                delete $courselogs{$crsid};
                   2834:             }
1.352     www      2835:         }
1.920     raeburn  2836:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2837:             'description' => $coursedescrbuf{$crsid},
                   2838:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2839:             'type'        => $coursetypebuf{$crsid},
                   2840:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2841:         };
1.191     harris41 2842:     }
1.352     www      2843: #
                   2844: # Write course id database (reverse lookup) to homeserver of courses 
                   2845: # Is used in pickcourse
                   2846: #
1.840     albertel 2847:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2848:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2849:                                     $courseidbuffer{$crs_home},
                   2850:                                     $crs_home,'timeonly');
1.352     www      2851:     }
                   2852: #
                   2853: # File accesses
                   2854: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2855: #
1.449     matthew  2856:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2857:         if ($entry =~ /___count$/) {
                   2858:             my ($dom,$name);
1.807     albertel 2859:             ($dom,$name,undef)=
1.811     albertel 2860: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2861:             if (! defined($dom) || $dom eq '' || 
                   2862:                 ! defined($name) || $name eq '') {
1.620     albertel 2863:                 my $cid = $env{'request.course.id'};
                   2864:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2865:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2866:             }
1.450     matthew  2867:             my $value = $accesshash{$entry};
                   2868:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2869:             my %temphash=($url => $value);
1.449     matthew  2870:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2871:             if ($result eq 'ok') {
                   2872:                 delete $accesshash{$entry};
                   2873:             } elsif ($result eq 'unknown_cmd') {
                   2874:                 # Target server has old code running on it.
1.450     matthew  2875:                 my %temphash=($entry => $value);
1.449     matthew  2876:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2877:                     delete $accesshash{$entry};
                   2878:                 }
                   2879:             }
                   2880:         } else {
1.811     albertel 2881:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2882:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2883:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2884:                 delete $accesshash{$entry};
                   2885:             }
1.185     www      2886:         }
1.191     harris41 2887:     }
1.352     www      2888: #
                   2889: # Roles
                   2890: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2891: #
1.800     albertel 2892:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2893:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2894: 	    split(/\:/,$entry);
                   2895:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2896:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2897:                 $rudom,$runame) eq 'ok') {
                   2898: 	    delete $userrolehash{$entry};
                   2899:         }
                   2900:     }
1.662     raeburn  2901: #
                   2902: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2903: #
                   2904:     my %domrolebuffer = ();
1.1000    raeburn  2905:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2906:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2907:         if ($domrolebuffer{$rudom}) {
                   2908:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2909:                       '='.&escape($domainrolehash{$entry});
                   2910:         } else {
                   2911:             $domrolebuffer{$rudom}.=&escape($entry).
                   2912:                       '='.&escape($domainrolehash{$entry});
                   2913:         }
                   2914:         delete $domainrolehash{$entry};
                   2915:     }
                   2916:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2917: 	my %servers = &get_servers($dom,'library');
                   2918: 	foreach my $tryserver (keys(%servers)) {
                   2919: 	    unless (&reply('domroleput:'.$dom.':'.
                   2920: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2921: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2922: 	    }
1.662     raeburn  2923:         }
                   2924:     }
1.186     www      2925:     $dumpcount++;
1.157     www      2926: }
                   2927: 
                   2928: sub courselog {
                   2929:     my $what=shift;
1.158     www      2930:     $what=time.':'.$what;
1.620     albertel 2931:     unless ($env{'request.course.id'}) { return ''; }
                   2932:     $coursedombuf{$env{'request.course.id'}}=
                   2933:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2934:     $coursenumbuf{$env{'request.course.id'}}=
                   2935:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2936:     $coursehombuf{$env{'request.course.id'}}=
                   2937:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2938:     $coursedescrbuf{$env{'request.course.id'}}=
                   2939:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2940:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2941:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2942:     $courseownerbuf{$env{'request.course.id'}}=
                   2943:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2944:     $coursetypebuf{$env{'request.course.id'}}=
                   2945:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2946:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2947: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2948:     } else {
1.620     albertel 2949: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2950:     }
1.620     albertel 2951:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2952: 	&flushcourselogs();
                   2953:     }
1.158     www      2954: }
                   2955: 
                   2956: sub courseacclog {
                   2957:     my $fnsymb=shift;
1.620     albertel 2958:     unless ($env{'request.course.id'}) { return ''; }
                   2959:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2960:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2961:         $what.=':POST';
1.583     matthew  2962:         # FIXME: Probably ought to escape things....
1.800     albertel 2963: 	foreach my $key (keys(%env)) {
                   2964:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2965:                 my $formitem = $1;
                   2966:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2967:                     $what.=':'.$formitem.'='.$env{$key};
                   2968:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2969:                     $what.=':'.$formitem.'='.$env{$key};
                   2970:                 }
1.158     www      2971:             }
1.191     harris41 2972:         }
1.583     matthew  2973:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2974:         # FIXME: We should not be depending on a form parameter that someone
                   2975:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2976:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2977:             $what.= ':POST';
                   2978:             # FIXME: Probably ought to escape things....
                   2979:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2980:                                  'crsdiscuss') {
1.620     albertel 2981:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2982:             }
                   2983:         }
1.158     www      2984:     }
                   2985:     &courselog($what);
1.149     www      2986: }
                   2987: 
1.185     www      2988: sub countacc {
                   2989:     my $url=&declutter(shift);
1.458     matthew  2990:     return if (! defined($url) || $url eq '');
1.620     albertel 2991:     unless ($env{'request.course.id'}) { return ''; }
                   2992:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2993:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2994:     $accesshash{$key}++;
1.185     www      2995: }
1.349     www      2996: 
1.361     www      2997: sub linklog {
                   2998:     my ($from,$to)=@_;
                   2999:     $from=&declutter($from);
                   3000:     $to=&declutter($to);
                   3001:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3002:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3003: }
                   3004:   
1.349     www      3005: sub userrolelog {
                   3006:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3007:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3008:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3009:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3010:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3011:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3012:        $userrolehash
                   3013:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3014:                     =$tend.':'.$tstart;
1.662     raeburn  3015:     }
1.898     albertel 3016:     if (($env{'request.role'} =~ /dc\./) &&
                   3017: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3018: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3019: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3020:          ($trole=~/^co/))) {
1.898     albertel 3021:        $userrolehash
                   3022:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3023:                     =$tend.':'.$tstart;
                   3024:     }
1.662     raeburn  3025:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3026:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3027:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3028:         ($trole=~/^sc/)) {
                   3029:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3030:        $domainrolehash
                   3031:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3032:                     = $tend.':'.$tstart;
                   3033:     }
1.351     www      3034: }
                   3035: 
1.957     raeburn  3036: sub courserolelog {
                   3037:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3038:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3039:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3040:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3041:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3042:         ($trole eq 'co')) {
1.957     raeburn  3043:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3044:             my $cdom = $1;
                   3045:             my $cnum = $2;
                   3046:             my $sec = $3;
                   3047:             my $namespace = 'rolelog';
                   3048:             my %storehash = (
                   3049:                                role    => $trole,
                   3050:                                start   => $tstart,
                   3051:                                end     => $tend,
                   3052:                                selfenroll => $selfenroll,
                   3053:                                context    => $context,
                   3054:                             );
                   3055:             if ($trole eq 'gr') {
                   3056:                 $namespace = 'groupslog';
                   3057:                 $storehash{'group'} = $sec;
                   3058:             } else {
                   3059:                 $storehash{'section'} = $sec;
                   3060:             }
                   3061:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3062:             if (($trole ne 'st') || ($sec ne '')) {
                   3063:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3064:             }
1.957     raeburn  3065:         }
                   3066:     }
                   3067:     return;
                   3068: }
                   3069: 
1.351     www      3070: sub get_course_adv_roles {
1.948     raeburn  3071:     my ($cid,$codes) = @_;
1.620     albertel 3072:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3073:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3074:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3075:     my %nothide=();
1.800     albertel 3076:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3077:         if ($user !~ /:/) {
                   3078: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3079:         } else {
                   3080:             $nothide{$user}=1;
                   3081:         }
1.470     www      3082:     }
1.351     www      3083:     my %returnhash=();
                   3084:     my %dumphash=
                   3085:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3086:     my $now=time;
1.997     raeburn  3087:     my %privileged;
1.1000    raeburn  3088:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3089: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3090:         if (($tstart) && ($tstart<0)) { next; }
                   3091:         if (($tend) && ($tend<$now)) { next; }
                   3092:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3093:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3094: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3095:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3096:             my %dompersonnel =
1.998     raeburn  3097:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3098:             $privileged{$domain} = {};
                   3099:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3100:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3101:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3102:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3103:                         $privileged{$udom}{$uname} = 1;
                   3104:                     }
                   3105:                 }
                   3106:             }
                   3107:         }
                   3108:         if ((exists($privileged{$domain}{$username})) && 
                   3109:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3110: 	if ($role eq 'cr') { next; }
1.948     raeburn  3111:         if ($codes) {
                   3112:             if ($section) { $role .= ':'.$section; }
                   3113:             if ($returnhash{$role}) {
                   3114:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3115:             } else {
                   3116:                 $returnhash{$role}=$username.':'.$domain;
                   3117:             }
1.351     www      3118:         } else {
1.988     raeburn  3119:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3120:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3121:             if ($returnhash{$key}) {
                   3122: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3123:             } else {
                   3124:                 $returnhash{$key}=$username.':'.$domain;
                   3125:             }
1.351     www      3126:         }
1.948     raeburn  3127:     }
1.400     www      3128:     return %returnhash;
                   3129: }
                   3130: 
                   3131: sub get_my_roles {
1.937     raeburn  3132:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3133:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3134:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3135:     my (%dumphash,%nothide);
1.1086    raeburn  3136:     if ($context eq 'userroles') {
                   3137:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3138:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3139:     } else {
                   3140:         %dumphash=
1.400     www      3141:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3142:         if ($hidepriv) {
                   3143:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3144:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3145:                 if ($user !~ /:/) {
                   3146:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3147:                 } else {
                   3148:                     $nothide{$user} = 1;
                   3149:                 }
                   3150:             }
                   3151:         }
1.858     raeburn  3152:     }
1.400     www      3153:     my %returnhash=();
                   3154:     my $now=time;
1.999     raeburn  3155:     my %privileged;
1.800     albertel 3156:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3157:         my ($role,$tend,$tstart);
                   3158:         if ($context eq 'userroles') {
                   3159: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3160:         } else {
                   3161:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3162:         }
1.400     www      3163:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3164:         my $status = 'active';
1.939     raeburn  3165:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3166:             $status = 'previous';
                   3167:         } 
                   3168:         if (($tstart) && ($now<$tstart)) {
                   3169:             $status = 'future';
                   3170:         }
                   3171:         if (ref($types) eq 'ARRAY') {
                   3172:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3173:                 next;
                   3174:             } 
                   3175:         } else {
                   3176:             if ($status ne 'active') {
                   3177:                 next;
                   3178:             }
                   3179:         }
1.867     raeburn  3180:         my ($rolecode,$username,$domain,$section,$area);
                   3181:         if ($context eq 'userroles') {
                   3182:             ($area,$rolecode) = split(/_/,$entry);
                   3183:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3184:         } else {
                   3185:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3186:         }
1.832     raeburn  3187:         if (ref($roledoms) eq 'ARRAY') {
                   3188:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3189:                 next;
                   3190:             }
                   3191:         }
                   3192:         if (ref($roles) eq 'ARRAY') {
                   3193:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3194:                 if ($role =~ /^cr\//) {
                   3195:                     if (!grep(/^cr$/,@{$roles})) {
                   3196:                         next;
                   3197:                     }
1.1104    raeburn  3198:                 } elsif ($role =~ /^gr\//) {
                   3199:                     if (!grep(/^gr$/,@{$roles})) {
                   3200:                         next;
                   3201:                     }
1.922     raeburn  3202:                 } else {
                   3203:                     next;
                   3204:                 }
1.832     raeburn  3205:             }
1.867     raeburn  3206:         }
1.937     raeburn  3207:         if ($hidepriv) {
1.999     raeburn  3208:             if ($context eq 'userroles') {
                   3209:                 if ((&privileged($username,$domain)) &&
                   3210:                     (!$nothide{$username.':'.$domain})) {
                   3211:                     next;
                   3212:                 }
                   3213:             } else {
                   3214:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3215:                     my %dompersonnel =
                   3216:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3217:                     $privileged{$domain} = {};
                   3218:                     if (keys(%dompersonnel)) {
                   3219:                         foreach my $server (keys(%dompersonnel)) {
                   3220:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3221:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3222:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3223:                                     $privileged{$udom}{$uname} = $trole;
                   3224:                                 }
                   3225:                             }
                   3226:                         }
                   3227:                     }
                   3228:                 }
                   3229:                 if (exists($privileged{$domain}{$username})) {
                   3230:                     if (!$nothide{$username.':'.$domain}) {
                   3231:                         next;
                   3232:                     }
                   3233:                 }
1.937     raeburn  3234:             }
                   3235:         }
1.933     raeburn  3236:         if ($withsec) {
                   3237:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3238:                 $tstart.':'.$tend;
                   3239:         } else {
                   3240:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3241:         }
1.832     raeburn  3242:     }
1.373     www      3243:     return %returnhash;
1.399     www      3244: }
                   3245: 
                   3246: # ----------------------------------------------------- Frontpage Announcements
                   3247: #
                   3248: #
                   3249: 
                   3250: sub postannounce {
                   3251:     my ($server,$text)=@_;
1.844     albertel 3252:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3253:     unless ($text=~/\w/) { $text=''; }
                   3254:     return &reply('setannounce:'.&escape($text),$server);
                   3255: }
                   3256: 
                   3257: sub getannounce {
1.448     albertel 3258: 
                   3259:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3260: 	my $announcement='';
1.800     albertel 3261: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3262: 	close($fh);
1.399     www      3263: 	if ($announcement=~/\w/) { 
                   3264: 	    return 
                   3265:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3266:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3267: 	} else {
                   3268: 	    return '';
                   3269: 	}
                   3270:     } else {
                   3271: 	return '';
                   3272:     }
1.351     www      3273: }
1.353     www      3274: 
                   3275: # ---------------------------------------------------------- Course ID routines
                   3276: # Deal with domain's nohist_courseid.db files
                   3277: #
                   3278: 
                   3279: sub courseidput {
1.921     raeburn  3280:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3281:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3282:     my $outcome;
                   3283:     if ($caller eq 'timeonly') {
                   3284:         my $cids = '';
                   3285:         foreach my $item (keys(%$storehash)) {
                   3286:             $cids.=&escape($item).'&';
                   3287:         }
                   3288:         $cids=~s/\&$//;
                   3289:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3290:                           $coursehome);       
                   3291:     } else {
                   3292:         my $items = '';
                   3293:         foreach my $item (keys(%$storehash)) {
                   3294:             $items.= &escape($item).'='.
                   3295:                      &freeze_escape($$storehash{$item}).'&';
                   3296:         }
                   3297:         $items=~s/\&$//;
                   3298:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3299:                           $coursehome);
1.918     raeburn  3300:     }
                   3301:     if ($outcome eq 'unknown_cmd') {
                   3302:         my $what;
                   3303:         foreach my $cid (keys(%$storehash)) {
                   3304:             $what .= &escape($cid).'=';
1.921     raeburn  3305:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3306:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3307:             }
                   3308:             $what =~ s/\:$/&/;
                   3309:         }
                   3310:         $what =~ s/\&$//;  
                   3311:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3312:     } else {
                   3313:         return $outcome;
                   3314:     }
1.353     www      3315: }
                   3316: 
                   3317: sub courseiddump {
1.921     raeburn  3318:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3319:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3320:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3321:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3322:     my $as_hash = 1;
                   3323:     my %returnhash;
                   3324:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3325:     my %libserv = &all_library();
                   3326:     foreach my $tryserver (keys(%libserv)) {
                   3327:         if ( (  $hostidflag == 1 
                   3328: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3329: 	     || (!defined($hostidflag)) ) {
                   3330: 
1.918     raeburn  3331: 	    if (($domfilter eq '') ||
                   3332: 		(&host_domain($tryserver) eq $domfilter)) {
                   3333:                 my $rep = 
                   3334:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3335:                          $sincefilter.':'.&escape($descfilter).':'.
                   3336:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3337:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3338:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3339:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3340:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3341:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3342:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3343:                          &escape($creationcontext).':'.$domcloner,
                   3344:                          $tryserver);
1.918     raeburn  3345:                 my @pairs=split(/\&/,$rep);
                   3346:                 foreach my $item (@pairs) {
                   3347:                     my ($key,$value)=split(/\=/,$item,2);
                   3348:                     $key = &unescape($key);
                   3349:                     next if ($key =~ /^error: 2 /);
                   3350:                     my $result = &thaw_unescape($value);
                   3351:                     if (ref($result) eq 'HASH') {
                   3352:                         $returnhash{$key}=$result;
                   3353:                     } else {
1.921     raeburn  3354:                         my @responses = split(/:/,$value);
                   3355:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3356:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3357:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3358:                         }
1.1008    raeburn  3359:                     }
1.353     www      3360:                 }
                   3361:             }
                   3362:         }
                   3363:     }
                   3364:     return %returnhash;
                   3365: }
                   3366: 
1.1055    raeburn  3367: sub courselastaccess {
                   3368:     my ($cdom,$cnum,$hostidref) = @_;
                   3369:     my %returnhash;
                   3370:     if ($cdom && $cnum) {
                   3371:         my $chome = &homeserver($cnum,$cdom);
                   3372:         if ($chome ne 'no_host') {
                   3373:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3374:             &extract_lastaccess(\%returnhash,$rep);
                   3375:         }
                   3376:     } else {
                   3377:         if (!$cdom) { $cdom=''; }
                   3378:         my %libserv = &all_library();
                   3379:         foreach my $tryserver (keys(%libserv)) {
                   3380:             if (ref($hostidref) eq 'ARRAY') {
                   3381:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3382:             } 
                   3383:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3384:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3385:                 &extract_lastaccess(\%returnhash,$rep);
                   3386:             }
                   3387:         }
                   3388:     }
                   3389:     return %returnhash;
                   3390: }
                   3391: 
                   3392: sub extract_lastaccess {
                   3393:     my ($returnhash,$rep) = @_;
                   3394:     if (ref($returnhash) eq 'HASH') {
                   3395:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3396:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3397:                  $rep eq '') {
                   3398:             my @pairs=split(/\&/,$rep);
                   3399:             foreach my $item (@pairs) {
                   3400:                 my ($key,$value)=split(/\=/,$item,2);
                   3401:                 $key = &unescape($key);
                   3402:                 next if ($key =~ /^error: 2 /);
                   3403:                 $returnhash->{$key} = &thaw_unescape($value);
                   3404:             }
                   3405:         }
                   3406:     }
                   3407:     return;
                   3408: }
                   3409: 
1.658     raeburn  3410: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3411: 
                   3412: sub dcmailput {
1.685     raeburn  3413:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3414:     my $status = &Apache::lonnet::critical(
1.740     www      3415:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3416:        &escape($message),$server);
1.662     raeburn  3417:     return $status;
                   3418: }
                   3419: 
1.658     raeburn  3420: sub dcmaildump {
                   3421:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3422:     my %returnhash=();
1.846     albertel 3423: 
                   3424:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3425:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3426:                                                          &escape($enddate).':';
                   3427: 	my @esc_senders=map { &escape($_)} @$senders;
                   3428: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3429: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3430:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3431:             if (($key) && ($value)) {
                   3432:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3433:             }
                   3434:         }
                   3435:     }
                   3436:     return %returnhash;
                   3437: }
1.662     raeburn  3438: # ---------------------------------------------------------- Domain roles
                   3439: 
                   3440: sub get_domain_roles {
                   3441:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3442:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3443:         $startdate = '.';
                   3444:     }
1.1018    raeburn  3445:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3446:         $enddate = '.';
                   3447:     }
1.922     raeburn  3448:     my $rolelist;
                   3449:     if (ref($roles) eq 'ARRAY') {
                   3450:         $rolelist = join(':',@{$roles});
                   3451:     }
1.662     raeburn  3452:     my %personnel = ();
1.841     albertel 3453: 
                   3454:     my %servers = &get_servers($dom,'library');
                   3455:     foreach my $tryserver (keys(%servers)) {
                   3456: 	%{$personnel{$tryserver}}=();
                   3457: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3458: 					    &escape($startdate).':'.
                   3459: 					    &escape($enddate).':'.
                   3460: 					    &escape($rolelist), $tryserver))) {
                   3461: 	    my ($key,$value) = split(/\=/,$line,2);
                   3462: 	    if (($key) && ($value)) {
                   3463: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3464: 	    }
                   3465: 	}
1.662     raeburn  3466:     }
                   3467:     return %personnel;
                   3468: }
1.658     raeburn  3469: 
1.1057    www      3470: # ----------------------------------------------------------- Interval timing 
1.149     www      3471: 
1.504     albertel 3472: sub get_first_access {
                   3473:     my ($type,$argsymb)=@_;
1.790     albertel 3474:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3475:     if ($argsymb) { $symb=$argsymb; }
                   3476:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3477:     if ($type eq 'course') {
                   3478: 	$res='course';
                   3479:     } elsif ($type eq 'map') {
1.588     albertel 3480: 	$res=&symbread($map);
                   3481:     } else {
                   3482: 	$res=$symb;
                   3483:     }
                   3484:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3485:     return $times{"$courseid\0$res"};
1.504     albertel 3486: }
                   3487: 
                   3488: sub set_first_access {
                   3489:     my ($type)=@_;
1.790     albertel 3490:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3491:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3492:     if ($type eq 'course') {
                   3493: 	$res='course';
                   3494:     } elsif ($type eq 'map') {
1.588     albertel 3495: 	$res=&symbread($map);
                   3496:     } else {
                   3497: 	$res=$symb;
                   3498:     }
                   3499:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3500:     if (!$firstaccess) {
1.588     albertel 3501: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3502:     }
                   3503:     return 'already_set';
1.504     albertel 3504: }
                   3505: 
1.110     www      3506: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3507: 
                   3508: sub expirespread {
                   3509:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3510:     my $cid=$env{'request.course.id'}; 
1.110     www      3511:     if ($cid) {
                   3512:        my $now=time;
                   3513:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3514:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3515:                             $env{'course.'.$cid.'.num'}.
1.110     www      3516: 	        	    ':nohist_expirationdates:'.
                   3517:                             &escape($key).'='.$now,
1.620     albertel 3518:                             $env{'course.'.$cid.'.home'})
1.110     www      3519:     }
                   3520:     return 'ok';
1.14      www      3521: }
                   3522: 
1.109     www      3523: # ----------------------------------------------------- Devalidate Spreadsheets
                   3524: 
                   3525: sub devalidate {
1.325     www      3526:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3527:     my $cid=$env{'request.course.id'}; 
1.109     www      3528:     if ($cid) {
1.391     matthew  3529:         # delete the stored spreadsheets for
                   3530:         # - the student level sheet of this user in course's homespace
                   3531:         # - the assessment level sheet for this resource 
                   3532:         #   for this user in user's homespace
1.553     albertel 3533: 	# - current conditional state info
1.325     www      3534: 	my $key=$uname.':'.$udom.':';
1.109     www      3535:         my $status=
1.299     matthew  3536: 	    &del('nohist_calculatedsheets',
1.391     matthew  3537: 		 [$key.'studentcalc:'],
1.620     albertel 3538: 		 $env{'course.'.$cid.'.domain'},
                   3539: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3540: 		.' '.
                   3541: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3542: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3543:         unless ($status eq 'ok ok') {
                   3544:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3545:                     $uname.' at '.$udom.' for '.
1.109     www      3546: 		    $symb.': '.$status);
1.133     albertel 3547:         }
1.553     albertel 3548: 	&delenv('user.state.'.$cid);
1.109     www      3549:     }
                   3550: }
                   3551: 
1.265     albertel 3552: sub get_scalar {
                   3553:     my ($string,$end) = @_;
                   3554:     my $value;
                   3555:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3556: 	$value = $1;
                   3557:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3558: 	$value = $1;
                   3559:     }
                   3560:     return &unescape($value);
                   3561: }
                   3562: 
                   3563: sub array2str {
                   3564:   my (@array) = @_;
                   3565:   my $result=&arrayref2str(\@array);
                   3566:   $result=~s/^__ARRAY_REF__//;
                   3567:   $result=~s/__END_ARRAY_REF__$//;
                   3568:   return $result;
                   3569: }
                   3570: 
1.204     albertel 3571: sub arrayref2str {
                   3572:   my ($arrayref) = @_;
1.265     albertel 3573:   my $result='__ARRAY_REF__';
1.204     albertel 3574:   foreach my $elem (@$arrayref) {
1.265     albertel 3575:     if(ref($elem) eq 'ARRAY') {
                   3576:       $result.=&arrayref2str($elem).'&';
                   3577:     } elsif(ref($elem) eq 'HASH') {
                   3578:       $result.=&hashref2str($elem).'&';
                   3579:     } elsif(ref($elem)) {
                   3580:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3581:     } else {
                   3582:       $result.=&escape($elem).'&';
                   3583:     }
                   3584:   }
                   3585:   $result=~s/\&$//;
1.265     albertel 3586:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3587:   return $result;
                   3588: }
                   3589: 
1.168     albertel 3590: sub hash2str {
1.204     albertel 3591:   my (%hash) = @_;
                   3592:   my $result=&hashref2str(\%hash);
1.265     albertel 3593:   $result=~s/^__HASH_REF__//;
                   3594:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3595:   return $result;
                   3596: }
                   3597: 
                   3598: sub hashref2str {
                   3599:   my ($hashref)=@_;
1.265     albertel 3600:   my $result='__HASH_REF__';
1.800     albertel 3601:   foreach my $key (sort(keys(%$hashref))) {
                   3602:     if (ref($key) eq 'ARRAY') {
                   3603:       $result.=&arrayref2str($key).'=';
                   3604:     } elsif (ref($key) eq 'HASH') {
                   3605:       $result.=&hashref2str($key).'=';
                   3606:     } elsif (ref($key)) {
1.265     albertel 3607:       $result.='=';
1.800     albertel 3608:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3609:     } else {
1.800     albertel 3610: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3611:     }
                   3612: 
1.800     albertel 3613:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3614:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3615:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3616:       $result.=&hashref2str($hashref->{$key}).'&';
                   3617:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3618:        $result.='&';
1.800     albertel 3619:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3620:     } else {
1.800     albertel 3621:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3622:     }
                   3623:   }
1.168     albertel 3624:   $result=~s/\&$//;
1.265     albertel 3625:   $result .= '__END_HASH_REF__';
1.168     albertel 3626:   return $result;
                   3627: }
                   3628: 
                   3629: sub str2hash {
1.265     albertel 3630:     my ($string)=@_;
                   3631:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3632:     return %$hash;
                   3633: }
                   3634: 
                   3635: sub str2hashref {
1.168     albertel 3636:   my ($string) = @_;
1.265     albertel 3637: 
                   3638:   my %hash;
                   3639: 
                   3640:   if($string !~ /^__HASH_REF__/) {
                   3641:       if (! ($string eq '' || !defined($string))) {
                   3642: 	  $hash{'error'}='Not hash reference';
                   3643:       }
                   3644:       return (\%hash, $string);
                   3645:   }
                   3646: 
                   3647:   $string =~ s/^__HASH_REF__//;
                   3648: 
                   3649:   while($string !~ /^__END_HASH_REF__/) {
                   3650:       #key
                   3651:       my $key='';
                   3652:       if($string =~ /^__HASH_REF__/) {
                   3653:           ($key, $string)=&str2hashref($string);
                   3654:           if(defined($key->{'error'})) {
                   3655:               $hash{'error'}='Bad data';
                   3656:               return (\%hash, $string);
                   3657:           }
                   3658:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3659:           ($key, $string)=&str2arrayref($string);
                   3660:           if($key->[0] eq 'Array reference error') {
                   3661:               $hash{'error'}='Bad data';
                   3662:               return (\%hash, $string);
                   3663:           }
                   3664:       } else {
                   3665:           $string =~ s/^(.*?)=//;
1.267     albertel 3666: 	  $key=&unescape($1);
1.265     albertel 3667:       }
                   3668:       $string =~ s/^=//;
                   3669: 
                   3670:       #value
                   3671:       my $value='';
                   3672:       if($string =~ /^__HASH_REF__/) {
                   3673:           ($value, $string)=&str2hashref($string);
                   3674:           if(defined($value->{'error'})) {
                   3675:               $hash{'error'}='Bad data';
                   3676:               return (\%hash, $string);
                   3677:           }
                   3678:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3679:           ($value, $string)=&str2arrayref($string);
                   3680:           if($value->[0] eq 'Array reference error') {
                   3681:               $hash{'error'}='Bad data';
                   3682:               return (\%hash, $string);
                   3683:           }
                   3684:       } else {
                   3685: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3686:       }
                   3687:       $string =~ s/^&//;
                   3688: 
                   3689:       $hash{$key}=$value;
1.204     albertel 3690:   }
1.265     albertel 3691: 
                   3692:   $string =~ s/^__END_HASH_REF__//;
                   3693: 
                   3694:   return (\%hash, $string);
1.204     albertel 3695: }
                   3696: 
                   3697: sub str2array {
1.265     albertel 3698:     my ($string)=@_;
                   3699:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3700:     return @$array;
                   3701: }
                   3702: 
                   3703: sub str2arrayref {
1.204     albertel 3704:   my ($string) = @_;
1.265     albertel 3705:   my @array;
                   3706: 
                   3707:   if($string !~ /^__ARRAY_REF__/) {
                   3708:       if (! ($string eq '' || !defined($string))) {
                   3709: 	  $array[0]='Array reference error';
                   3710:       }
                   3711:       return (\@array, $string);
                   3712:   }
                   3713: 
                   3714:   $string =~ s/^__ARRAY_REF__//;
                   3715: 
                   3716:   while($string !~ /^__END_ARRAY_REF__/) {
                   3717:       my $value='';
                   3718:       if($string =~ /^__HASH_REF__/) {
                   3719:           ($value, $string)=&str2hashref($string);
                   3720:           if(defined($value->{'error'})) {
                   3721:               $array[0] ='Array reference error';
                   3722:               return (\@array, $string);
                   3723:           }
                   3724:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3725:           ($value, $string)=&str2arrayref($string);
                   3726:           if($value->[0] eq 'Array reference error') {
                   3727:               $array[0] ='Array reference error';
                   3728:               return (\@array, $string);
                   3729:           }
                   3730:       } else {
                   3731: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3732:       }
                   3733:       $string =~ s/^&//;
                   3734: 
                   3735:       push(@array, $value);
1.191     harris41 3736:   }
1.265     albertel 3737: 
                   3738:   $string =~ s/^__END_ARRAY_REF__//;
                   3739: 
                   3740:   return (\@array, $string);
1.168     albertel 3741: }
                   3742: 
1.167     albertel 3743: # -------------------------------------------------------------------Temp Store
                   3744: 
1.168     albertel 3745: sub tmpreset {
                   3746:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3747:   if (!$symb) {
                   3748:     $symb=&symbread();
1.620     albertel 3749:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3750:   }
                   3751:   $symb=escape($symb);
                   3752: 
1.620     albertel 3753:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3754:   $namespace=~s/\//\_/g;
                   3755:   $namespace=~s/\W//g;
                   3756: 
1.620     albertel 3757:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3758:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3759:   if ($domain eq 'public' && $stuname eq 'public') {
                   3760:       $stuname=$ENV{'REMOTE_ADDR'};
                   3761:   }
1.168     albertel 3762:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3763:   my %hash;
                   3764:   if (tie(%hash,'GDBM_File',
                   3765: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3766: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3767:     foreach my $key (keys(%hash)) {
1.180     albertel 3768:       if ($key=~ /:$symb/) {
1.168     albertel 3769: 	delete($hash{$key});
                   3770:       }
                   3771:     }
                   3772:   }
                   3773: }
                   3774: 
1.167     albertel 3775: sub tmpstore {
1.168     albertel 3776:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3777: 
                   3778:   if (!$symb) {
                   3779:     $symb=&symbread();
1.620     albertel 3780:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3781:   }
                   3782:   $symb=escape($symb);
                   3783: 
                   3784:   if (!$namespace) {
                   3785:     # I don't think we would ever want to store this for a course.
                   3786:     # it seems this will only be used if we don't have a course.
1.620     albertel 3787:     #$namespace=$env{'request.course.id'};
1.168     albertel 3788:     #if (!$namespace) {
1.620     albertel 3789:       $namespace=$env{'request.state'};
1.168     albertel 3790:     #}
                   3791:   }
                   3792:   $namespace=~s/\//\_/g;
                   3793:   $namespace=~s/\W//g;
1.620     albertel 3794:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3795:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3796:   if ($domain eq 'public' && $stuname eq 'public') {
                   3797:       $stuname=$ENV{'REMOTE_ADDR'};
                   3798:   }
1.168     albertel 3799:   my $now=time;
                   3800:   my %hash;
                   3801:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3802:   if (tie(%hash,'GDBM_File',
                   3803: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3804: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3805:     $hash{"version:$symb"}++;
                   3806:     my $version=$hash{"version:$symb"};
                   3807:     my $allkeys=''; 
                   3808:     foreach my $key (keys(%$storehash)) {
                   3809:       $allkeys.=$key.':';
1.591     albertel 3810:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3811:     }
                   3812:     $hash{"$version:$symb:timestamp"}=$now;
                   3813:     $allkeys.='timestamp';
                   3814:     $hash{"$version:keys:$symb"}=$allkeys;
                   3815:     if (untie(%hash)) {
                   3816:       return 'ok';
                   3817:     } else {
                   3818:       return "error:$!";
                   3819:     }
                   3820:   } else {
                   3821:     return "error:$!";
                   3822:   }
                   3823: }
1.167     albertel 3824: 
1.168     albertel 3825: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3826: 
1.168     albertel 3827: sub tmprestore {
                   3828:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3829: 
1.168     albertel 3830:   if (!$symb) {
                   3831:     $symb=&symbread();
1.620     albertel 3832:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3833:   }
                   3834:   $symb=escape($symb);
                   3835: 
1.620     albertel 3836:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3837: 
1.620     albertel 3838:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3839:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3840:   if ($domain eq 'public' && $stuname eq 'public') {
                   3841:       $stuname=$ENV{'REMOTE_ADDR'};
                   3842:   }
1.168     albertel 3843:   my %returnhash;
                   3844:   $namespace=~s/\//\_/g;
                   3845:   $namespace=~s/\W//g;
                   3846:   my %hash;
                   3847:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3848:   if (tie(%hash,'GDBM_File',
                   3849: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3850: 	  &GDBM_READER(),0640)) {
1.168     albertel 3851:     my $version=$hash{"version:$symb"};
                   3852:     $returnhash{'version'}=$version;
                   3853:     my $scope;
                   3854:     for ($scope=1;$scope<=$version;$scope++) {
                   3855:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3856:       my @keys=split(/:/,$vkeys);
                   3857:       my $key;
                   3858:       $returnhash{"$scope:keys"}=$vkeys;
                   3859:       foreach $key (@keys) {
1.591     albertel 3860: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3861: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3862:       }
                   3863:     }
1.168     albertel 3864:     if (!(untie(%hash))) {
                   3865:       return "error:$!";
                   3866:     }
                   3867:   } else {
                   3868:     return "error:$!";
                   3869:   }
                   3870:   return %returnhash;
1.167     albertel 3871: }
                   3872: 
1.9       www      3873: # ----------------------------------------------------------------------- Store
                   3874: 
                   3875: sub store {
1.124     www      3876:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3877:     my $home='';
                   3878: 
1.168     albertel 3879:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3880: 
1.213     www      3881:     $symb=&symbclean($symb);
1.122     albertel 3882:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3883: 
1.620     albertel 3884:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3885:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3886: 
                   3887:     &devalidate($symb,$stuname,$domain);
1.109     www      3888: 
                   3889:     $symb=escape($symb);
1.187     www      3890:     if (!$namespace) { 
1.620     albertel 3891:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3892:           return ''; 
                   3893:        } 
                   3894:     }
1.620     albertel 3895:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3896: 
                   3897:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3898:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3899: 
1.12      www      3900:     my $namevalue='';
1.800     albertel 3901:     foreach my $key (keys(%$storehash)) {
                   3902:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3903:     }
1.12      www      3904:     $namevalue=~s/\&$//;
1.187     www      3905:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3906:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3907: }
                   3908: 
1.47      www      3909: # -------------------------------------------------------------- Critical Store
                   3910: 
                   3911: sub cstore {
1.124     www      3912:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3913:     my $home='';
                   3914: 
1.168     albertel 3915:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3916: 
1.213     www      3917:     $symb=&symbclean($symb);
1.122     albertel 3918:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3919: 
1.620     albertel 3920:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3921:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3922: 
                   3923:     &devalidate($symb,$stuname,$domain);
1.109     www      3924: 
                   3925:     $symb=escape($symb);
1.187     www      3926:     if (!$namespace) { 
1.620     albertel 3927:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3928:           return ''; 
                   3929:        } 
                   3930:     }
1.620     albertel 3931:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3932: 
                   3933:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3934:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3935: 
1.47      www      3936:     my $namevalue='';
1.800     albertel 3937:     foreach my $key (keys(%$storehash)) {
                   3938:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3939:     }
1.47      www      3940:     $namevalue=~s/\&$//;
1.187     www      3941:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3942:     return critical
                   3943:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3944: }
                   3945: 
1.9       www      3946: # --------------------------------------------------------------------- Restore
                   3947: 
                   3948: sub restore {
1.124     www      3949:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3950:     my $home='';
                   3951: 
1.168     albertel 3952:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3953: 
1.122     albertel 3954:     if (!$symb) {
                   3955:       unless ($symb=escape(&symbread())) { return ''; }
                   3956:     } else {
1.213     www      3957:       $symb=&escape(&symbclean($symb));
1.122     albertel 3958:     }
1.188     www      3959:     if (!$namespace) { 
1.620     albertel 3960:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3961:           return ''; 
                   3962:        } 
                   3963:     }
1.620     albertel 3964:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3965:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3966:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3967:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3968: 
1.12      www      3969:     my %returnhash=();
1.800     albertel 3970:     foreach my $line (split(/\&/,$answer)) {
                   3971: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3972:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3973:     }
1.75      www      3974:     my $version;
                   3975:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3976:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3977:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3978:        }
1.75      www      3979:     }
1.13      www      3980:     return %returnhash;
1.34      www      3981: }
                   3982: 
                   3983: # ---------------------------------------------------------- Course Description
                   3984: 
                   3985: sub coursedescription {
1.731     albertel 3986:     my ($courseid,$args)=@_;
1.34      www      3987:     $courseid=~s/^\///;
1.49      www      3988:     $courseid=~s/\_/\//g;
1.34      www      3989:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3990:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3991:     my $normalid=$cdomain.'_'.$cnum;
                   3992:     # need to always cache even if we get errors otherwise we keep 
                   3993:     # trying and trying and trying to get the course description.
                   3994:     my %envhash=();
                   3995:     my %returnhash=();
1.731     albertel 3996:     
                   3997:     my $expiretime=600;
                   3998:     if ($env{'request.course.id'} eq $normalid) {
                   3999: 	$expiretime=120;
                   4000:     }
                   4001: 
                   4002:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4003:     if (!$args->{'freshen_cache'}
                   4004: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4005: 	foreach my $key (keys(%env)) {
                   4006: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4007: 	    my ($setting) = $1;
                   4008: 	    $returnhash{$setting} = $env{$key};
                   4009: 	}
                   4010: 	return %returnhash;
                   4011:     }
                   4012: 
                   4013:     # get the data agin
                   4014:     if (!$args->{'one_time'}) {
                   4015: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4016:     }
1.811     albertel 4017: 
1.34      www      4018:     if ($chome ne 'no_host') {
1.302     albertel 4019:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4020:        if (!exists($returnhash{'con_lost'})) {
                   4021:            $returnhash{'home'}= $chome;
                   4022: 	   $returnhash{'domain'} = $cdomain;
                   4023: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4024:            if (!defined($returnhash{'type'})) {
                   4025:                $returnhash{'type'} = 'Course';
                   4026:            }
1.130     albertel 4027:            while (my ($name,$value) = each %returnhash) {
1.53      www      4028:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4029:            }
1.270     www      4030:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4031:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4032: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4033:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4034:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4035:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4036:        }
                   4037:     }
1.731     albertel 4038:     if (!$args->{'one_time'}) {
1.949     raeburn  4039: 	&appenv(\%envhash);
1.731     albertel 4040:     }
1.302     albertel 4041:     return %returnhash;
1.461     www      4042: }
                   4043: 
1.1080    raeburn  4044: sub update_released_required {
                   4045:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4046:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4047:         $cid = $env{'request.course.id'};
                   4048:         $cdom = $env{'course.'.$cid.'.domain'};
                   4049:         $cnum = $env{'course.'.$cid.'.num'};
                   4050:         $chome = $env{'course.'.$cid.'.home'};
                   4051:     }
                   4052:     if ($needsrelease) {
                   4053:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4054:         my $needsupdate;
                   4055:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4056:             $needsupdate = 1;
                   4057:         } else {
                   4058:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4059:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4060:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4061:                 $needsupdate = 1;
                   4062:             }
                   4063:         }
                   4064:         if ($needsupdate) {
                   4065:             my %needshash = (
                   4066:                              'internal.releaserequired' => $needsrelease,
                   4067:                             );
                   4068:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4069:             if ($putresult eq 'ok') {
                   4070:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4071:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4072:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4073:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4074:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4075:                 }
                   4076:             }
                   4077:         }
                   4078:     }
                   4079:     return;
                   4080: }
                   4081: 
1.461     www      4082: # -------------------------------------------------See if a user is privileged
                   4083: 
                   4084: sub privileged {
                   4085:     my ($username,$domain)=@_;
                   4086:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4087: 			&homeserver($username,$domain));
1.1033    raeburn  4088:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4089:         ($rolesdump =~ /^error:/)) {
                   4090:         return 0;
                   4091:     }
1.461     www      4092:     my $now=time;
                   4093:     if ($rolesdump ne '') {
1.800     albertel 4094:         foreach my $entry (split(/&/,$rolesdump)) {
                   4095: 	    if ($entry!~/^rolesdef_/) {
                   4096: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4097: 		$area=~s/\_\w\w$//;
                   4098: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4099: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4100: 		    my $active=1;
                   4101: 		    if ($tend) {
                   4102: 			if ($tend<$now) { $active=0; }
                   4103: 		    }
                   4104: 		    if ($tstart) {
                   4105: 			if ($tstart>$now) { $active=0; }
                   4106: 		    }
                   4107: 		    if ($active) { return 1; }
                   4108: 		}
                   4109: 	    }
                   4110: 	}
                   4111:     }
                   4112:     return 0;
1.9       www      4113: }
1.1       albertel 4114: 
1.103     harris41 4115: # -------------------------------------------------------- Get user privileges
1.11      www      4116: 
                   4117: sub rolesinit {
                   4118:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4119:     my $now=time;
                   4120:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4121:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4122:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4123:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4124:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4125:         return \%userroles;
                   4126:     }
1.11      www      4127:     my %allroles=();
1.678     raeburn  4128:     my %allgroups=();   
1.11      www      4129: 
                   4130:     if ($rolesdump ne '') {
1.800     albertel 4131:         foreach my $entry (split(/&/,$rolesdump)) {
                   4132: 	  if ($entry!~/^rolesdef_/) {
                   4133:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4134: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4135:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4136: 	    if ($role=~/^cr/) { 
1.807     albertel 4137: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4138: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4139: 		    ($tend,$tstart)=split('_',$trest);
                   4140: 		} else {
                   4141: 		    $trole=$role;
                   4142: 		}
1.678     raeburn  4143:             } elsif ($role =~ m|^gr/|) {
                   4144:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4145:                 next if ($tstart eq '-1');
1.678     raeburn  4146:                 ($trole,$group_privs) = split(/\//,$trole);
                   4147:                 $group_privs = &unescape($group_privs);
1.587     albertel 4148: 	    } else {
                   4149: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4150: 	    }
1.743     albertel 4151: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4152: 					 $username);
                   4153: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4154:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4155:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4156:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4157: 		my $spec=$trole.'.'.$area;
                   4158: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4159: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4160:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4161:                 } elsif ($trole eq 'gr') {
                   4162:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4163: 		} else {
1.567     raeburn  4164:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4165: 		}
1.12      www      4166:             }
1.662     raeburn  4167:           }
1.191     harris41 4168:         }
1.743     albertel 4169:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4170:         $userroles{'user.adv'}    = $adv;
                   4171: 	$userroles{'user.author'} = $author;
1.620     albertel 4172:         $env{'user.adv'}=$adv;
1.11      www      4173:     }
1.743     albertel 4174:     return \%userroles;  
1.11      www      4175: }
                   4176: 
1.567     raeburn  4177: sub set_arearole {
                   4178:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4179: # log the associated role with the area
                   4180:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4181:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4182: }
                   4183: 
                   4184: sub custom_roleprivs {
                   4185:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4186:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4187:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4188:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4189:         my ($rdummy,$roledef)=
                   4190:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4191:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4192:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4193:             if (defined($syspriv)) {
1.1043    raeburn  4194:                 if ($trest =~ /^$match_community$/) {
                   4195:                     $syspriv =~ s/bre\&S//; 
                   4196:                 }
1.567     raeburn  4197:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4198:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4199:             }
                   4200:             if ($tdomain ne '') {
                   4201:                 if (defined($dompriv)) {
                   4202:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4203:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4204:                 }
                   4205:                 if (($trest ne '') && (defined($coursepriv))) {
                   4206:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4207:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4208:                 }
                   4209:             }
                   4210:         }
                   4211:     }
                   4212: }
                   4213: 
1.678     raeburn  4214: sub group_roleprivs {
                   4215:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4216:     my $access = 1;
                   4217:     my $now = time;
                   4218:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4219:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4220:     if ($access) {
1.811     albertel 4221:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4222:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4223:     }
                   4224: }
1.567     raeburn  4225: 
                   4226: sub standard_roleprivs {
                   4227:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4228:     if (defined($pr{$trole.':s'})) {
                   4229:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4230:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4231:     }
                   4232:     if ($tdomain ne '') {
                   4233:         if (defined($pr{$trole.':d'})) {
                   4234:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4235:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4236:         }
                   4237:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4238:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4239:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4240:         }
                   4241:     }
                   4242: }
                   4243: 
                   4244: sub set_userprivs {
1.1064    raeburn  4245:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4246:     my $author=0;
                   4247:     my $adv=0;
1.678     raeburn  4248:     my %grouproles = ();
                   4249:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4250:         my @groupkeys; 
1.1000    raeburn  4251:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4252:             push(@groupkeys,$role);
                   4253:         }
                   4254:         if (ref($groups_roles) eq 'HASH') {
                   4255:             foreach my $key (keys(%{$groups_roles})) {
                   4256:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4257:                     push(@groupkeys,$key);
                   4258:                 }
                   4259:             }
                   4260:         }
                   4261:         if (@groupkeys > 0) {
                   4262:             foreach my $role (@groupkeys) {
                   4263:                 my ($trole,$area,$sec,$extendedarea);
                   4264:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4265:                     $trole = $1;
                   4266:                     $area = $2;
                   4267:                     $sec = $3;
                   4268:                     $extendedarea = $area.$sec;
                   4269:                     if (exists($$allgroups{$area})) {
                   4270:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4271:                             my $spec = $trole.'.'.$extendedarea;
                   4272:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4273:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4274:                         }
1.678     raeburn  4275:                     }
                   4276:                 }
                   4277:             }
                   4278:         }
                   4279:     }
1.800     albertel 4280:     foreach my $group (keys(%grouproles)) {
                   4281:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4282:     }
1.800     albertel 4283:     foreach my $role (keys(%{$allroles})) {
                   4284:         my %thesepriv;
1.941     raeburn  4285:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4286:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4287:             if ($item ne '') {
                   4288:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4289:                 if ($restrictions eq '') {
                   4290:                     $thesepriv{$privilege}='F';
                   4291:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4292:                     $thesepriv{$privilege}.=$restrictions;
                   4293:                 }
                   4294:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4295:             }
                   4296:         }
                   4297:         my $thesestr='';
1.1104    raeburn  4298:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4299: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4300: 	}
                   4301:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4302:     }
                   4303:     return ($author,$adv);
                   4304: }
                   4305: 
1.994     raeburn  4306: sub role_status {
1.1104    raeburn  4307:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4308:     my @pwhere = ();
                   4309:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4310:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4311:         unless (!defined($$role) || $$role eq '') {
                   4312:             $$where=join('.',@pwhere);
                   4313:             $$trolecode=$$role.'.'.$$where;
                   4314:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4315:             $$tstatus='is';
1.1104    raeburn  4316:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4317:                 $$tstatus='future';
1.1034    raeburn  4318:                 if ($$tstart<$now) {
                   4319:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4320:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4321:                             my (%allroles,%allgroups,$group_privs,
                   4322:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4323:                             my %userroles = (
                   4324:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4325:                             );
1.1064    raeburn  4326:                             @rolecodes = ('cm'); 
1.1002    raeburn  4327:                             my $spec=$$role.'.'.$$where;
                   4328:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4329:                             if ($$role =~ /^cr\//) {
                   4330:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4331:                                 push(@rolecodes,'cr');
1.1002    raeburn  4332:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4333:                                 push(@rolecodes,$$role);
1.1002    raeburn  4334:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4335:                                                     $env{'user.name'});
1.1064    raeburn  4336:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4337:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4338:                                 $group_privs = &unescape($group_privs);
                   4339:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4340:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104    raeburn  4341:                                 &get_groups_roles($tdomain,$trest,
                   4342:                                                   \%course_roles,\@rolecodes,
                   4343:                                                   \%groups_roles);
1.1002    raeburn  4344:                             } else {
1.1064    raeburn  4345:                                 push(@rolecodes,$$role);
1.1002    raeburn  4346:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4347:                             }
1.1064    raeburn  4348:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4349:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4350:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4351:                         }
                   4352:                     }
1.1034    raeburn  4353:                     $$tstatus = 'is';
1.1002    raeburn  4354:                 }
1.994     raeburn  4355:             }
                   4356:             if ($$tend) {
1.1104    raeburn  4357:                 if ($$tend<$update) {
1.994     raeburn  4358:                     $$tstatus='expired';
                   4359:                 } elsif ($$tend<$now) {
                   4360:                     $$tstatus='will_not';
                   4361:                 }
                   4362:             }
                   4363:         }
                   4364:     }
                   4365: }
                   4366: 
1.1104    raeburn  4367: sub get_groups_roles {
                   4368:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4369:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4370:                   (ref($rolecodes) eq 'ARRAY') && 
                   4371:                   (ref($groups_roles) eq 'HASH')); 
                   4372:     if (keys(%{$cdom_courseroles}) > 0) {
                   4373:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4374:         if ($cdom ne '' && $cnum ne '') {
                   4375:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4376:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4377:                     my $crsrole = $1;
                   4378:                     my $crssec = $2;
                   4379:                     if ($crsrole =~ /^cr/) {
                   4380:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4381:                             push(@{$rolecodes},'cr');
                   4382:                         }
                   4383:                     } else {
                   4384:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4385:                             push(@{$rolecodes},$crsrole);
                   4386:                         }
                   4387:                     }
                   4388:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4389:                     if ($crssec ne '') {
                   4390:                         $rolekey .= "/$crssec";
                   4391:                     }
                   4392:                     $rolekey .= './';
                   4393:                     $groups_roles->{$rolekey} = $rolecodes;
                   4394:                 }
                   4395:             }
                   4396:         }
                   4397:     }
                   4398:     return;
                   4399: }
                   4400: 
                   4401: sub delete_env_groupprivs {
                   4402:     my ($where,$courseroles,$possroles) = @_;
                   4403:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4404:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4405:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4406:         %{$courseroles->{$udom}} =
                   4407:             &get_my_roles('','','userroles',['active'],
                   4408:                           $possroles,[$udom],1);
                   4409:     }
                   4410:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4411:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4412:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4413:             my $area = '/'.$cdom.'/'.$cnum;
                   4414:             my $privkey = "user.priv.$crsrole.$area";
                   4415:             if ($crssec ne '') {
                   4416:                 $privkey .= '/'.$crssec;
                   4417:             }
                   4418:             $privkey .= ".$area/$group";
                   4419:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4420:         }
                   4421:     }
                   4422:     return;
                   4423: }
                   4424: 
1.994     raeburn  4425: sub check_adhoc_privs {
1.1104    raeburn  4426:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4427:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4428:     if ($env{$cckey}) {
                   4429:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4430:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4431:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4432:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4433:         }
                   4434:     } else {
1.1088    raeburn  4435:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4436:     }
                   4437: }
                   4438: 
                   4439: sub set_adhoc_privileges {
                   4440: # role can be cc or ca
1.1088    raeburn  4441:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4442:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4443:     my $spec = $role.'.'.$area;
                   4444:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4445:                                   $env{'user.name'});
                   4446:     my %ccrole = ();
                   4447:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4448:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4449:     &appenv(\%userroles,[$role,'cm']);
                   4450:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4451:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4452:         &appenv( {'request.role'        => $spec,
                   4453:                   'request.role.domain' => $dcdom,
                   4454:                   'request.course.sec'  => ''
                   4455:                  }
                   4456:                );
                   4457:         my $tadv=0;
                   4458:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4459:         &appenv({'request.role.adv'    => $tadv});
                   4460:     }
1.994     raeburn  4461: }
                   4462: 
1.12      www      4463: # --------------------------------------------------------------- get interface
                   4464: 
                   4465: sub get {
1.131     albertel 4466:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4467:    my $items='';
1.800     albertel 4468:    foreach my $item (@$storearr) {
                   4469:        $items.=&escape($item).'&';
1.191     harris41 4470:    }
1.12      www      4471:    $items=~s/\&$//;
1.620     albertel 4472:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4473:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4474:    my $uhome=&homeserver($uname,$udomain);
                   4475: 
1.133     albertel 4476:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4477:    my @pairs=split(/\&/,$rep);
1.273     albertel 4478:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4479:      return @pairs;
                   4480:    }
1.15      www      4481:    my %returnhash=();
1.42      www      4482:    my $i=0;
1.800     albertel 4483:    foreach my $item (@$storearr) {
                   4484:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4485:       $i++;
1.191     harris41 4486:    }
1.15      www      4487:    return %returnhash;
1.27      www      4488: }
                   4489: 
                   4490: # --------------------------------------------------------------- del interface
                   4491: 
                   4492: sub del {
1.133     albertel 4493:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4494:    my $items='';
1.800     albertel 4495:    foreach my $item (@$storearr) {
                   4496:        $items.=&escape($item).'&';
1.191     harris41 4497:    }
1.984     neumanie 4498: 
1.27      www      4499:    $items=~s/\&$//;
1.620     albertel 4500:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4501:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4502:    my $uhome=&homeserver($uname,$udomain);
                   4503:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4504: }
                   4505: 
                   4506: # -------------------------------------------------------------- dump interface
                   4507: 
                   4508: sub dump {
1.1086    raeburn  4509:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4510:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4511:     if (!$uname) { $uname=$env{'user.name'}; }
                   4512:     my $uhome=&homeserver($uname,$udomain);
                   4513:     if ($regexp) {
                   4514: 	$regexp=&escape($regexp);
                   4515:     } else {
                   4516: 	$regexp='.';
                   4517:     }
1.1086    raeburn  4518:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4519:     my @pairs=split(/\&/,$rep);
                   4520:     my %returnhash=();
1.1098    foxr     4521:     if (!($rep =~ /^error/ )) {
                   4522: 	foreach my $item (@pairs) {
                   4523: 	    my ($key,$value)=split(/=/,$item,2);
                   4524: 	    $key = &unescape($key);
                   4525: 	    next if ($key =~ /^error: 2 /);
                   4526: 	    $returnhash{$key}=&thaw_unescape($value);
                   4527: 	}
1.755     albertel 4528:     }
                   4529:     return %returnhash;
1.407     www      4530: }
                   4531: 
1.1098    foxr     4532: 
1.717     albertel 4533: # --------------------------------------------------------- dumpstore interface
                   4534: 
                   4535: sub dumpstore {
                   4536:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4537:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4538:    if (!$uname) { $uname=$env{'user.name'}; }
                   4539:    my $uhome=&homeserver($uname,$udomain);
                   4540:    if ($regexp) {
                   4541:        $regexp=&escape($regexp);
                   4542:    } else {
                   4543:        $regexp='.';
                   4544:    }
                   4545:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4546:    my @pairs=split(/\&/,$rep);
                   4547:    my %returnhash=();
                   4548:    foreach my $item (@pairs) {
                   4549:        my ($key,$value)=split(/=/,$item,2);
                   4550:        next if ($key =~ /^error: 2 /);
                   4551:        $returnhash{$key}=&thaw_unescape($value);
                   4552:    }
                   4553:    return %returnhash;
1.717     albertel 4554: }
                   4555: 
1.407     www      4556: # -------------------------------------------------------------- keys interface
                   4557: 
                   4558: sub getkeys {
                   4559:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4560:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4561:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4562:    my $uhome=&homeserver($uname,$udomain);
                   4563:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4564:    my @keyarray=();
1.800     albertel 4565:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4566:       next if ($key =~ /^error: 2 /);
1.800     albertel 4567:       push(@keyarray,&unescape($key));
1.407     www      4568:    }
                   4569:    return @keyarray;
1.318     matthew  4570: }
                   4571: 
1.319     matthew  4572: # --------------------------------------------------------------- currentdump
                   4573: sub currentdump {
1.328     matthew  4574:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4575:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4576:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4577:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4578:    my $uhome = &homeserver($sname,$sdom);
                   4579:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4580:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4581:    #
1.318     matthew  4582:    my %returnhash=();
1.319     matthew  4583:    #
                   4584:    if ($rep eq "unknown_cmd") { 
                   4585:        # an old lond will not know currentdump
                   4586:        # Do a dump and make it look like a currentdump
1.822     albertel 4587:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4588:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4589:        my %hash = @tmp;
                   4590:        @tmp=();
1.424     matthew  4591:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4592:    } else {
                   4593:        my @pairs=split(/\&/,$rep);
1.800     albertel 4594:        foreach my $pair (@pairs) {
                   4595:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4596:            my ($symb,$param) = split(/:/,$key);
                   4597:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4598:                                                         &thaw_unescape($value);
1.319     matthew  4599:        }
1.191     harris41 4600:    }
1.12      www      4601:    return %returnhash;
1.424     matthew  4602: }
                   4603: 
                   4604: sub convert_dump_to_currentdump{
                   4605:     my %hash = %{shift()};
                   4606:     my %returnhash;
                   4607:     # Code ripped from lond, essentially.  The only difference
                   4608:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4609:     # we might run in to problems with parameter names =~ /^v\./
                   4610:     while (my ($key,$value) = each(%hash)) {
                   4611:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4612: 	$symb  = &unescape($symb);
                   4613: 	$param = &unescape($param);
1.424     matthew  4614:         next if ($v eq 'version' || $symb eq 'keys');
                   4615:         next if (exists($returnhash{$symb}) &&
                   4616:                  exists($returnhash{$symb}->{$param}) &&
                   4617:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4618:         $returnhash{$symb}->{$param}=$value;
                   4619:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4620:     }
                   4621:     #
                   4622:     # Remove all of the keys in the hashes which keep track of
                   4623:     # the version of the parameter.
                   4624:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4625:         # use a foreach because we are going to delete from the hash.
                   4626:         foreach my $key (keys(%$param_hash)) {
                   4627:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4628:         }
                   4629:     }
                   4630:     return \%returnhash;
1.12      www      4631: }
                   4632: 
1.627     albertel 4633: # ------------------------------------------------------ critical inc interface
                   4634: 
                   4635: sub cinc {
                   4636:     return &inc(@_,'critical');
                   4637: }
                   4638: 
1.449     matthew  4639: # --------------------------------------------------------------- inc interface
                   4640: 
                   4641: sub inc {
1.627     albertel 4642:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4643:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4644:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4645:     my $uhome=&homeserver($uname,$udomain);
                   4646:     my $items='';
                   4647:     if (! ref($store)) {
                   4648:         # got a single value, so use that instead
                   4649:         $items = &escape($store).'=&';
                   4650:     } elsif (ref($store) eq 'SCALAR') {
                   4651:         $items = &escape($$store).'=&';        
                   4652:     } elsif (ref($store) eq 'ARRAY') {
                   4653:         $items = join('=&',map {&escape($_);} @{$store});
                   4654:     } elsif (ref($store) eq 'HASH') {
                   4655:         while (my($key,$value) = each(%{$store})) {
                   4656:             $items.= &escape($key).'='.&escape($value).'&';
                   4657:         }
                   4658:     }
                   4659:     $items=~s/\&$//;
1.627     albertel 4660:     if ($critical) {
                   4661: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4662:     } else {
                   4663: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4664:     }
1.449     matthew  4665: }
                   4666: 
1.12      www      4667: # --------------------------------------------------------------- put interface
                   4668: 
                   4669: sub put {
1.134     albertel 4670:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4671:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4672:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4673:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4674:    my $items='';
1.800     albertel 4675:    foreach my $item (keys(%$storehash)) {
                   4676:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4677:    }
1.12      www      4678:    $items=~s/\&$//;
1.134     albertel 4679:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4680: }
                   4681: 
1.631     albertel 4682: # ------------------------------------------------------------ newput interface
                   4683: 
                   4684: sub newput {
                   4685:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4686:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4687:    if (!$uname) { $uname=$env{'user.name'}; }
                   4688:    my $uhome=&homeserver($uname,$udomain);
                   4689:    my $items='';
                   4690:    foreach my $key (keys(%$storehash)) {
                   4691:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4692:    }
                   4693:    $items=~s/\&$//;
                   4694:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4695: }
                   4696: 
                   4697: # ---------------------------------------------------------  putstore interface
                   4698: 
1.524     raeburn  4699: sub putstore {
1.715     albertel 4700:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4701:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4702:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4703:    my $uhome=&homeserver($uname,$udomain);
                   4704:    my $items='';
1.715     albertel 4705:    foreach my $key (keys(%$storehash)) {
                   4706:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4707:    }
1.715     albertel 4708:    $items=~s/\&$//;
1.716     albertel 4709:    my $esc_symb=&escape($symb);
                   4710:    my $esc_v=&escape($version);
1.715     albertel 4711:    my $reply =
1.716     albertel 4712:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4713: 	      $uhome);
                   4714:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4715:        # gfall back to way things use to be done
1.715     albertel 4716:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4717: 			    $uname);
1.524     raeburn  4718:    }
1.715     albertel 4719:    return $reply;
                   4720: }
                   4721: 
                   4722: sub old_putstore {
1.716     albertel 4723:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4724:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4725:     if (!$uname) { $uname=$env{'user.name'}; }
                   4726:     my $uhome=&homeserver($uname,$udomain);
                   4727:     my %newstorehash;
1.800     albertel 4728:     foreach my $item (keys(%$storehash)) {
                   4729: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4730: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4731:     }
                   4732:     my $items='';
                   4733:     my %allitems = ();
1.800     albertel 4734:     foreach my $item (keys(%newstorehash)) {
                   4735: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4736: 	    my $key = $1.':keys:'.$2;
                   4737: 	    $allitems{$key} .= $3.':';
                   4738: 	}
1.800     albertel 4739: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4740:     }
1.800     albertel 4741:     foreach my $item (keys(%allitems)) {
                   4742: 	$allitems{$item} =~ s/\:$//;
                   4743: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4744:     }
                   4745:     $items=~s/\&$//;
                   4746:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4747: }
                   4748: 
1.47      www      4749: # ------------------------------------------------------ critical put interface
                   4750: 
                   4751: sub cput {
1.134     albertel 4752:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4753:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4754:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4755:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4756:    my $items='';
1.800     albertel 4757:    foreach my $item (keys(%$storehash)) {
                   4758:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4759:    }
1.47      www      4760:    $items=~s/\&$//;
1.134     albertel 4761:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4762: }
                   4763: 
                   4764: # -------------------------------------------------------------- eget interface
                   4765: 
                   4766: sub eget {
1.133     albertel 4767:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4768:    my $items='';
1.800     albertel 4769:    foreach my $item (@$storearr) {
                   4770:        $items.=&escape($item).'&';
1.191     harris41 4771:    }
1.12      www      4772:    $items=~s/\&$//;
1.620     albertel 4773:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4774:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4775:    my $uhome=&homeserver($uname,$udomain);
                   4776:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4777:    my @pairs=split(/\&/,$rep);
                   4778:    my %returnhash=();
1.42      www      4779:    my $i=0;
1.800     albertel 4780:    foreach my $item (@$storearr) {
                   4781:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4782:       $i++;
1.191     harris41 4783:    }
1.12      www      4784:    return %returnhash;
                   4785: }
                   4786: 
1.667     albertel 4787: # ------------------------------------------------------------ tmpput interface
                   4788: sub tmpput {
1.802     raeburn  4789:     my ($storehash,$server,$context)=@_;
1.667     albertel 4790:     my $items='';
1.800     albertel 4791:     foreach my $item (keys(%$storehash)) {
                   4792: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4793:     }
                   4794:     $items=~s/\&$//;
1.802     raeburn  4795:     if (defined($context)) {
                   4796:         $items .= ':'.&escape($context);
                   4797:     }
1.667     albertel 4798:     return &reply("tmpput:$items",$server);
                   4799: }
                   4800: 
                   4801: # ------------------------------------------------------------ tmpget interface
                   4802: sub tmpget {
1.688     albertel 4803:     my ($token,$server)=@_;
                   4804:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4805:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4806:     my %returnhash;
                   4807:     foreach my $item (split(/\&/,$rep)) {
                   4808: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4809:         next if ($key =~ /^error: 2 /);
1.667     albertel 4810: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4811:     }
                   4812:     return %returnhash;
                   4813: }
                   4814: 
1.1113  ! raeburn  4815: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 4816: sub tmpdel {
                   4817:     my ($token,$server)=@_;
                   4818:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4819:     return &reply("tmpdel:$token",$server);
                   4820: }
                   4821: 
1.765     albertel 4822: # -------------------------------------------------- portfolio access checking
                   4823: 
                   4824: sub portfolio_access {
1.766     albertel 4825:     my ($requrl) = @_;
1.765     albertel 4826:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4827:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4828:     if ($result) {
                   4829:         my %setters;
                   4830:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4831:             my ($startblock,$endblock) =
                   4832:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4833:             if ($startblock && $endblock) {
                   4834:                 return 'B';
                   4835:             }
                   4836:         } else {
                   4837:             my ($startblock,$endblock) =
                   4838:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4839:             if ($startblock && $endblock) {
                   4840:                 return 'B';
                   4841:             }
                   4842:         }
                   4843:     }
1.765     albertel 4844:     if ($result eq 'ok') {
1.766     albertel 4845:        return 'F';
1.765     albertel 4846:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4847:        return 'A';
1.765     albertel 4848:     }
1.766     albertel 4849:     return '';
1.765     albertel 4850: }
                   4851: 
                   4852: sub get_portfolio_access {
1.767     albertel 4853:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4854: 
                   4855:     if (!ref($access_hash)) {
                   4856: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4857: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4858: 						   $file_name);
                   4859: 	$access_hash = $access_controls{$file_name};
                   4860:     }
                   4861: 
1.765     albertel 4862:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4863:     my $now = time;
                   4864:     if (ref($access_hash) eq 'HASH') {
                   4865:         foreach my $key (keys(%{$access_hash})) {
                   4866:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4867:             if ($start > $now) {
                   4868:                 next;
                   4869:             }
                   4870:             if ($end && $end<$now) {
                   4871:                 next;
                   4872:             }
                   4873:             if ($scope eq 'public') {
                   4874:                 $public = $key;
                   4875:                 last;
                   4876:             } elsif ($scope eq 'guest') {
                   4877:                 $guest = $key;
                   4878:             } elsif ($scope eq 'domains') {
                   4879:                 push(@domains,$key);
                   4880:             } elsif ($scope eq 'users') {
                   4881:                 push(@users,$key);
                   4882:             } elsif ($scope eq 'course') {
                   4883:                 push(@courses,$key);
                   4884:             } elsif ($scope eq 'group') {
                   4885:                 push(@groups,$key);
                   4886:             }
                   4887:         }
                   4888:         if ($public) {
                   4889:             return 'ok';
                   4890:         }
                   4891:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4892:             if ($guest) {
                   4893:                 return $guest;
                   4894:             }
                   4895:         } else {
                   4896:             if (@domains > 0) {
                   4897:                 foreach my $domkey (@domains) {
                   4898:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4899:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4900:                             return 'ok';
                   4901:                         }
                   4902:                     }
                   4903:                 }
                   4904:             }
                   4905:             if (@users > 0) {
                   4906:                 foreach my $userkey (@users) {
1.865     raeburn  4907:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4908:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4909:                             if (ref($item) eq 'HASH') {
                   4910:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4911:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4912:                                     return 'ok';
                   4913:                                 }
                   4914:                             }
                   4915:                         }
                   4916:                     } 
1.765     albertel 4917:                 }
                   4918:             }
                   4919:             my %roleshash;
                   4920:             my @courses_and_groups = @courses;
                   4921:             push(@courses_and_groups,@groups); 
                   4922:             if (@courses_and_groups > 0) {
                   4923:                 my (%allgroups,%allroles); 
                   4924:                 my ($start,$end,$role,$sec,$group);
                   4925:                 foreach my $envkey (%env) {
1.1060    raeburn  4926:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4927:                         my $cid = $2.'_'.$3; 
                   4928:                         if ($1 eq 'gr') {
                   4929:                             $group = $4;
                   4930:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4931:                         } else {
                   4932:                             if ($4 eq '') {
                   4933:                                 $sec = 'none';
                   4934:                             } else {
                   4935:                                 $sec = $4;
                   4936:                             }
                   4937:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4938:                         }
1.811     albertel 4939:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4940:                         my $cid = $2.'_'.$3;
                   4941:                         if ($4 eq '') {
                   4942:                             $sec = 'none';
                   4943:                         } else {
                   4944:                             $sec = $4;
                   4945:                         }
                   4946:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4947:                     }
                   4948:                 }
                   4949:                 if (keys(%allroles) == 0) {
                   4950:                     return;
                   4951:                 }
                   4952:                 foreach my $key (@courses_and_groups) {
                   4953:                     my %content = %{$$access_hash{$key}};
                   4954:                     my $cnum = $content{'number'};
                   4955:                     my $cdom = $content{'domain'};
                   4956:                     my $cid = $cdom.'_'.$cnum;
                   4957:                     if (!exists($allroles{$cid})) {
                   4958:                         next;
                   4959:                     }    
                   4960:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4961:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4962:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4963:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4964:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4965:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4966:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4967:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4968:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4969:                                         if (grep/^all$/,@sections) {
                   4970:                                             return 'ok';
                   4971:                                         } else {
                   4972:                                             if (grep/^$sec$/,@sections) {
                   4973:                                                 return 'ok';
                   4974:                                             }
                   4975:                                         }
                   4976:                                     }
                   4977:                                 }
                   4978:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4979:                                     if (grep/^none$/,@groups) {
                   4980:                                         return 'ok';
                   4981:                                     }
                   4982:                                 } else {
                   4983:                                     if (grep/^all$/,@groups) {
                   4984:                                         return 'ok';
                   4985:                                     } 
                   4986:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4987:                                         if (grep/^$group$/,@groups) {
                   4988:                                             return 'ok';
                   4989:                                         }
                   4990:                                     }
                   4991:                                 } 
                   4992:                             }
                   4993:                         }
                   4994:                     }
                   4995:                 }
                   4996:             }
                   4997:             if ($guest) {
                   4998:                 return $guest;
                   4999:             }
                   5000:         }
                   5001:     }
                   5002:     return;
                   5003: }
                   5004: 
                   5005: sub course_group_datechecker {
                   5006:     my ($dates,$now,$status) = @_;
                   5007:     my ($start,$end) = split(/\./,$dates);
                   5008:     if (!$start && !$end) {
                   5009:         return 'ok';
                   5010:     }
                   5011:     if (grep/^active$/,@{$status}) {
                   5012:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5013:             return 'ok';
                   5014:         }
                   5015:     }
                   5016:     if (grep/^previous$/,@{$status}) {
                   5017:         if ($end > $now ) {
                   5018:             return 'ok';
                   5019:         }
                   5020:     }
                   5021:     if (grep/^future$/,@{$status}) {
                   5022:         if ($start > $now) {
                   5023:             return 'ok';
                   5024:         }
                   5025:     }
                   5026:     return; 
                   5027: }
                   5028: 
                   5029: sub parse_portfolio_url {
                   5030:     my ($url) = @_;
                   5031: 
                   5032:     my ($type,$udom,$unum,$group,$file_name);
                   5033:     
1.823     albertel 5034:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5035: 	$type = 1;
                   5036:         $udom = $1;
                   5037:         $unum = $2;
                   5038:         $file_name = $3;
1.823     albertel 5039:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5040: 	$type = 2;
                   5041:         $udom = $1;
                   5042:         $unum = $2;
                   5043:         $group = $3;
                   5044:         $file_name = $3.'/'.$4;
                   5045:     }
                   5046:     if (wantarray) {
                   5047: 	return ($type,$udom,$unum,$file_name,$group);
                   5048:     }
                   5049:     return $type;
                   5050: }
                   5051: 
                   5052: sub is_portfolio_url {
                   5053:     my ($url) = @_;
                   5054:     return scalar(&parse_portfolio_url($url));
                   5055: }
                   5056: 
1.798     raeburn  5057: sub is_portfolio_file {
                   5058:     my ($file) = @_;
1.820     raeburn  5059:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5060:         return 1;
                   5061:     }
                   5062:     return;
                   5063: }
                   5064: 
1.976     raeburn  5065: sub usertools_access {
1.1084    raeburn  5066:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5067:     my ($access,%tools);
                   5068:     if ($context eq '') {
                   5069:         $context = 'tools';
                   5070:     }
                   5071:     if ($context eq 'requestcourses') {
                   5072:         %tools = (
                   5073:                       official   => 1,
                   5074:                       unofficial => 1,
1.1006    raeburn  5075:                       community  => 1,
1.985     raeburn  5076:                  );
                   5077:     } else {
                   5078:         %tools = (
                   5079:                       aboutme   => 1,
                   5080:                       blog      => 1,
                   5081:                       portfolio => 1,
                   5082:                  );
                   5083:     }
1.976     raeburn  5084:     return if (!defined($tools{$tool}));
                   5085: 
                   5086:     if ((!defined($udom)) || (!defined($uname))) {
                   5087:         $udom = $env{'user.domain'};
                   5088:         $uname = $env{'user.name'};
                   5089:     }
                   5090: 
1.978     raeburn  5091:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5092:         if ($action ne 'reload') {
1.985     raeburn  5093:             if ($context eq 'requestcourses') {
                   5094:                 return $env{'environment.canrequest.'.$tool};
                   5095:             } else {
                   5096:                 return $env{'environment.availabletools.'.$tool};
                   5097:             }
                   5098:         }
1.976     raeburn  5099:     }
                   5100: 
                   5101:     my ($toolstatus,$inststatus);
                   5102: 
1.985     raeburn  5103:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5104:          ($action ne 'reload')) {
                   5105:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5106:         $inststatus = $env{'environment.inststatus'};
                   5107:     } else {
1.1084    raeburn  5108:         if (ref($userenvref) eq 'HASH') {
                   5109:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5110:             $inststatus = $userenvref->{'inststatus'};
                   5111:         } else {
                   5112:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5113:             $toolstatus = $userenv{$context.'.'.$tool};
                   5114:             $inststatus = $userenv{'inststatus'};
                   5115:         }
1.976     raeburn  5116:     }
                   5117: 
                   5118:     if ($toolstatus ne '') {
                   5119:         if ($toolstatus) {
                   5120:             $access = 1;
                   5121:         } else {
                   5122:             $access = 0;
                   5123:         }
                   5124:         return $access;
                   5125:     }
                   5126: 
1.1084    raeburn  5127:     my ($is_adv,%domdef);
                   5128:     if (ref($is_advref) eq 'HASH') {
                   5129:         $is_adv = $is_advref->{'is_adv'};
                   5130:     } else {
                   5131:         $is_adv = &is_advanced_user($udom,$uname);
                   5132:     }
                   5133:     if (ref($domdefref) eq 'HASH') {
                   5134:         %domdef = %{$domdefref};
                   5135:     } else {
                   5136:         %domdef = &get_domain_defaults($udom);
                   5137:     }
1.976     raeburn  5138:     if (ref($domdef{$tool}) eq 'HASH') {
                   5139:         if ($is_adv) {
                   5140:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5141:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5142:                     $access = 1;
                   5143:                 } else {
                   5144:                     $access = 0;
                   5145:                 }
                   5146:                 return $access;
                   5147:             }
                   5148:         }
                   5149:         if ($inststatus ne '') {
                   5150:             my ($hasaccess,$hasnoaccess);
                   5151:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5152:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5153:                     if ($domdef{$tool}{$affiliation}) {
                   5154:                         $hasaccess = 1;
                   5155:                     } else {
                   5156:                         $hasnoaccess = 1;
                   5157:                     }
                   5158:                 }
                   5159:             }
                   5160:             if ($hasaccess || $hasnoaccess) {
                   5161:                 if ($hasaccess) {
                   5162:                     $access = 1;
                   5163:                 } elsif ($hasnoaccess) {
                   5164:                     $access = 0; 
                   5165:                 }
                   5166:                 return $access;
                   5167:             }
                   5168:         } else {
                   5169:             if ($domdef{$tool}{'default'} ne '') {
                   5170:                 if ($domdef{$tool}{'default'}) {
                   5171:                     $access = 1;
                   5172:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5173:                     $access = 0;
                   5174:                 }
                   5175:                 return $access;
                   5176:             }
                   5177:         }
                   5178:     } else {
1.985     raeburn  5179:         if ($context eq 'tools') {
                   5180:             $access = 1;
                   5181:         } else {
                   5182:             $access = 0;
                   5183:         }
1.976     raeburn  5184:         return $access;
                   5185:     }
                   5186: }
                   5187: 
1.1050    raeburn  5188: sub is_course_owner {
                   5189:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5190:     if (($udom eq '') || ($uname eq '')) {
                   5191:         $udom = $env{'user.domain'};
                   5192:         $uname = $env{'user.name'};
                   5193:     }
                   5194:     unless (($udom eq '') || ($uname eq '')) {
                   5195:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5196:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5197:                 return 1;
                   5198:             } else {
                   5199:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5200:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5201:                     return 1;
                   5202:                 }
                   5203:             }
                   5204:         }
                   5205:     }
                   5206:     return;
                   5207: }
                   5208: 
1.976     raeburn  5209: sub is_advanced_user {
                   5210:     my ($udom,$uname) = @_;
1.1085    raeburn  5211:     if ($udom ne '' && $uname ne '') {
                   5212:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5213:             return $env{'user.adv'};  
                   5214:         }
                   5215:     }
1.976     raeburn  5216:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5217:     my %allroles;
                   5218:     my $is_adv;
                   5219:     foreach my $role (keys(%roleshash)) {
                   5220:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5221:         my $area = '/'.$tdomain.'/'.$trest;
                   5222:         if ($sec ne '') {
                   5223:             $area .= '/'.$sec;
                   5224:         }
                   5225:         if (($area ne '') && ($trole ne '')) {
                   5226:             my $spec=$trole.'.'.$area;
                   5227:             if ($trole =~ /^cr\//) {
                   5228:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5229:             } elsif ($trole ne 'gr') {
                   5230:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5231:             }
                   5232:         }
                   5233:     }
                   5234:     foreach my $role (keys(%allroles)) {
                   5235:         last if ($is_adv);
                   5236:         foreach my $item (split(/:/,$allroles{$role})) {
                   5237:             if ($item ne '') {
                   5238:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5239:                 if ($privilege eq 'adv') {
                   5240:                     $is_adv = 1;
                   5241:                     last;
                   5242:                 }
                   5243:             }
                   5244:         }
                   5245:     }
                   5246:     return $is_adv;
                   5247: }
1.798     raeburn  5248: 
1.1035    raeburn  5249: sub check_can_request {
1.1036    raeburn  5250:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5251:     my $canreq = 0;
                   5252:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5253:     my @options = ('approval','validate','autolimit');
                   5254:     my $optregex = join('|',@options);
                   5255:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5256:         foreach my $type (@{$types}) {
                   5257:             if (&usertools_access($env{'user.name'},
                   5258:                                   $env{'user.domain'},
                   5259:                                   $type,undef,'requestcourses')) {
                   5260:                 $canreq ++;
1.1036    raeburn  5261:                 if (ref($request_domains) eq 'HASH') {
                   5262:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5263:                 }
1.1035    raeburn  5264:                 if ($dom eq $env{'user.domain'}) {
                   5265:                     $can_request->{$type} = 1;
                   5266:                 }
                   5267:             }
                   5268:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5269:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5270:                 if (@curr > 0) {
1.1036    raeburn  5271:                     foreach my $item (@curr) {
                   5272:                         if (ref($request_domains) eq 'HASH') {
                   5273:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5274:                             if ($otherdom ne '') {
                   5275:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5276:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5277:                                         push(@{$request_domains->{$type}},$otherdom);
                   5278:                                     }
                   5279:                                 } else {
                   5280:                                     push(@{$request_domains->{$type}},$otherdom);
                   5281:                                 }
                   5282:                             }
                   5283:                         }
                   5284:                     }
                   5285:                     unless($dom eq $env{'user.domain'}) {
                   5286:                         $canreq ++;
1.1035    raeburn  5287:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5288:                             $can_request->{$type} = 1;
                   5289:                         }
                   5290:                     }
                   5291:                 }
                   5292:             }
                   5293:         }
                   5294:     }
                   5295:     return $canreq;
                   5296: }
                   5297: 
1.341     www      5298: # ---------------------------------------------- Custom access rule evaluation
                   5299: 
                   5300: sub customaccess {
                   5301:     my ($priv,$uri)=@_;
1.807     albertel 5302:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5303:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5304:     $udom = &LONCAPA::clean_domain($udom);
                   5305:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5306:     my $access=0;
1.800     albertel 5307:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5308: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5309: 	if ($type eq 'user') {
                   5310: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5311: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5312: 		if ($tdom) {
                   5313: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5314: 		}
1.896     albertel 5315: 		if ($tuname) {
                   5316: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5317: 		}
                   5318: 		$access=($effect eq 'allow');
                   5319: 		last;
                   5320: 	    }
                   5321: 	} else {
                   5322: 	    if ($role) {
                   5323: 		if ($role ne $urole) { next; }
                   5324: 	    }
                   5325: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5326: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5327: 		if ($tdom) {
                   5328: 		    if ($tdom ne $udom) { next; }
                   5329: 		}
                   5330: 		if ($tcrs) {
                   5331: 		    if ($tcrs ne $ucrs) { next; }
                   5332: 		}
                   5333: 		if ($tsec) {
                   5334: 		    if ($tsec ne $usec) { next; }
                   5335: 		}
                   5336: 		$access=($effect eq 'allow');
                   5337: 		last;
                   5338: 	    }
                   5339: 	    if ($realm eq '' && $role eq '') {
                   5340: 		$access=($effect eq 'allow');
                   5341: 	    }
1.402     bowersj2 5342: 	}
1.341     www      5343:     }
                   5344:     return $access;
                   5345: }
                   5346: 
1.103     harris41 5347: # ------------------------------------------------- Check for a user privilege
1.12      www      5348: 
                   5349: sub allowed {
1.810     raeburn  5350:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5351:     my $ver_orguri=$uri;
1.439     www      5352:     $uri=&deversion($uri);
1.152     www      5353:     my $orguri=$uri;
1.52      www      5354:     $uri=&declutter($uri);
1.809     raeburn  5355: 
1.810     raeburn  5356:     if ($priv eq 'evb') {
                   5357: # Evade communication block restrictions for specified role in a course
                   5358:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5359:             return $1;
                   5360:         } else {
                   5361:             return;
                   5362:         }
                   5363:     }
                   5364: 
1.620     albertel 5365:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5366: # Free bre access to adm and meta resources
1.775     albertel 5367:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5368: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5369: 	&& ($priv eq 'bre')) {
1.14      www      5370: 	return 'F';
1.159     www      5371:     }
                   5372: 
1.545     banghart 5373: # Free bre access to user's own portfolio contents
1.714     raeburn  5374:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5375:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5376: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5377:         my %setters;
                   5378:         my ($startblock,$endblock) = 
                   5379:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5380:         if ($startblock && $endblock) {
                   5381:             return 'B';
                   5382:         } else {
                   5383:             return 'F';
                   5384:         }
1.545     banghart 5385:     }
                   5386: 
1.762     raeburn  5387: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5388:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5389:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5390:         if (exists($env{'request.course.id'})) {
                   5391:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5392:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5393:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5394:                 my $courseprivid=$env{'request.course.id'};
                   5395:                 $courseprivid=~s/\_/\//;
                   5396:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5397:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5398:                     return $1; 
1.762     raeburn  5399:                 } else {
                   5400:                     if ($env{'request.course.sec'}) {
                   5401:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5402:                     }
                   5403:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5404:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5405:                         return $2;
                   5406:                     }
1.714     raeburn  5407:                 }
                   5408:             }
                   5409:         }
                   5410:     }
                   5411: 
1.159     www      5412: # Free bre to public access
                   5413: 
                   5414:     if ($priv eq 'bre') {
1.238     www      5415:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5416: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5417:            return 'F'; 
                   5418:         }
1.238     www      5419:         if ($copyright eq 'priv') {
                   5420:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5421: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5422: 		return '';
                   5423:             }
                   5424:         }
                   5425:         if ($copyright eq 'domain') {
                   5426:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5427: 	    unless (($env{'user.domain'} eq $1) ||
                   5428:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5429: 		return '';
                   5430:             }
1.262     matthew  5431:         }
1.620     albertel 5432:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5433:             # Library role, so allow browsing of resources in this domain.
                   5434:             return 'F';
1.238     www      5435:         }
1.341     www      5436:         if ($copyright eq 'custom') {
                   5437: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5438:         }
1.14      www      5439:     }
1.264     matthew  5440:     # Domain coordinator is trying to create a course
1.620     albertel 5441:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5442:         # uri is the requested domain in this case.
                   5443:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5444:         # a role of dc for the domain in question.
1.620     albertel 5445:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5446:     }
1.29      www      5447: 
1.52      www      5448:     my $thisallowed='';
                   5449:     my $statecond=0;
                   5450:     my $courseprivid='';
                   5451: 
1.1039    raeburn  5452:     my $ownaccess;
1.1043    raeburn  5453:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5454:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5455:         if ($uri eq '') {
                   5456:             $ownaccess = 1;
                   5457:         } else {
                   5458:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5459:                 my $udom = $env{'user.domain'};
                   5460:                 my $uname = $env{'user.name'};
                   5461:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5462:                     $ownaccess = 1;
1.1040    raeburn  5463:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5464:                     unless ($uri =~ m{\.\./}) {
                   5465:                         $ownaccess = 1;
                   5466:                     }
                   5467:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5468:                     my $now = time;
                   5469:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5470:                         my $adom = $1;
                   5471:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5472:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5473:                                 my ($start,$end) = split('.',$env{$key});
                   5474:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5475:                                     $ownaccess = 1;
                   5476:                                     last;
                   5477:                                 }
                   5478:                             }
                   5479:                         }
                   5480:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5481:                         my $adom = $1;
                   5482:                         my $aname = $2;
1.1042    raeburn  5483:                         foreach my $role ('ca','aa') { 
                   5484:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5485:                                 my ($start,$end) =
                   5486:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5487:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5488:                                     $ownaccess = 1;
                   5489:                                     last;
                   5490:                                 }
1.1039    raeburn  5491:                             }
                   5492:                         }
                   5493:                     }
                   5494:                 }
                   5495:             }
                   5496:         }
                   5497:     }
                   5498: 
1.52      www      5499: # Course
                   5500: 
1.620     albertel 5501:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5502:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5503:             $thisallowed.=$1;
                   5504:         }
1.52      www      5505:     }
1.29      www      5506: 
1.52      www      5507: # Domain
                   5508: 
1.620     albertel 5509:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5510:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5511:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5512:             $thisallowed.=$1;
                   5513:         }
1.12      www      5514:     }
1.52      www      5515: 
                   5516: # Course: uri itself is a course
1.66      www      5517:     my $courseuri=$uri;
                   5518:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5519:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5520: 
1.620     albertel 5521:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5522:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5523:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5524:             $thisallowed.=$1;
                   5525:         }
1.12      www      5526:     }
1.29      www      5527: 
1.665     albertel 5528: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5529: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5530:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5531: 	$thisallowed='';
1.671     raeburn  5532:         my ($match)=&is_on_map($uri);
                   5533:         if ($match) {
                   5534:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5535:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5536:                 $thisallowed.=$1;
                   5537:             }
                   5538:         } else {
1.705     albertel 5539:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5540:             if ($refuri) {
                   5541:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5542:                     $thisallowed='F';
1.671     raeburn  5543:                 } else {
                   5544:                     $refuri=&declutter($refuri);
                   5545:                     my ($match) = &is_on_map($refuri);
                   5546:                     if ($match) {
                   5547:                         $thisallowed='F';
                   5548:                     }
1.669     raeburn  5549:                 }
1.671     raeburn  5550:             }
                   5551:         }
1.314     www      5552:     }
1.492     albertel 5553: 
1.766     albertel 5554:     if ($priv eq 'bre'
                   5555: 	&& $thisallowed ne 'F' 
                   5556: 	&& $thisallowed ne '2'
                   5557: 	&& &is_portfolio_url($uri)) {
                   5558: 	$thisallowed = &portfolio_access($uri);
                   5559:     }
                   5560:     
1.52      www      5561: # Full access at system, domain or course-wide level? Exit.
1.29      www      5562:     if ($thisallowed=~/F/) {
                   5563: 	return 'F';
                   5564:     }
                   5565: 
1.52      www      5566: # If this is generating or modifying users, exit with special codes
1.29      www      5567: 
1.643     www      5568:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5569: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5570: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5571: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5572: 	    unless ($auname) { return $thisallowed; }
                   5573: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5574: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5575: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5576: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5577: 	}
1.52      www      5578: 	return $thisallowed;
                   5579:     }
                   5580: #
1.103     harris41 5581: # Gathered so far: system, domain and course wide privileges
1.52      www      5582: #
                   5583: # Course: See if uri or referer is an individual resource that is part of 
                   5584: # the course
                   5585: 
1.620     albertel 5586:     if ($env{'request.course.id'}) {
1.232     www      5587: 
1.620     albertel 5588:        $courseprivid=$env{'request.course.id'};
                   5589:        if ($env{'request.course.sec'}) {
                   5590:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5591:        }
                   5592:        $courseprivid=~s/\_/\//;
                   5593:        my $checkreferer=1;
1.232     www      5594:        my ($match,$cond)=&is_on_map($uri);
                   5595:        if ($match) {
                   5596:            $statecond=$cond;
1.620     albertel 5597:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5598:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5599:                $thisallowed.=$1;
                   5600:                $checkreferer=0;
                   5601:            }
1.29      www      5602:        }
1.83      www      5603:        
1.148     www      5604:        if ($checkreferer) {
1.620     albertel 5605: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5606:             unless ($refuri) {
1.800     albertel 5607:                 foreach my $key (keys(%env)) {
                   5608: 		    if ($key=~/^httpref\..*\*/) {
                   5609: 			my $pattern=$key;
1.156     www      5610:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5611:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5612:                         $pattern=~s/\//\\\//g;
1.152     www      5613:                         if ($orguri=~/$pattern/) {
1.800     albertel 5614: 			    $refuri=$env{$key};
1.148     www      5615:                         }
                   5616:                     }
1.191     harris41 5617:                 }
1.148     www      5618:             }
1.232     www      5619: 
1.148     www      5620:          if ($refuri) { 
1.152     www      5621: 	  $refuri=&declutter($refuri);
1.232     www      5622:           my ($match,$cond)=&is_on_map($refuri);
                   5623:             if ($match) {
                   5624:               my $refstatecond=$cond;
1.620     albertel 5625:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5626:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5627:                   $thisallowed.=$1;
1.53      www      5628:                   $uri=$refuri;
                   5629:                   $statecond=$refstatecond;
1.52      www      5630:               }
                   5631:           }
1.148     www      5632:         }
1.29      www      5633:        }
1.52      www      5634:    }
1.29      www      5635: 
1.52      www      5636: #
1.103     harris41 5637: # Gathered now: all privileges that could apply, and condition number
1.52      www      5638: # 
                   5639: #
                   5640: # Full or no access?
                   5641: #
1.29      www      5642: 
1.52      www      5643:     if ($thisallowed=~/F/) {
                   5644: 	return 'F';
                   5645:     }
1.29      www      5646: 
1.52      www      5647:     unless ($thisallowed) {
                   5648:         return '';
                   5649:     }
1.29      www      5650: 
1.52      www      5651: # Restrictions exist, deal with them
                   5652: #
                   5653: #   C:according to course preferences
                   5654: #   R:according to resource settings
                   5655: #   L:unless locked
                   5656: #   X:according to user session state
                   5657: #
                   5658: 
                   5659: # Possibly locked functionality, check all courses
1.54      www      5660: # Locks might take effect only after 10 minutes cache expiration for other
                   5661: # courses, and 2 minutes for current course
1.52      www      5662: 
                   5663:     my $envkey;
                   5664:     if ($thisallowed=~/L/) {
1.1000    raeburn  5665:         foreach $envkey (keys(%env)) {
1.54      www      5666:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5667:                my $courseid=$2;
                   5668:                my $roleid=$1.'.'.$2;
1.92      www      5669:                $courseid=~s/^\///;
1.54      www      5670:                my $expiretime=600;
1.620     albertel 5671:                if ($env{'request.role'} eq $roleid) {
1.54      www      5672: 		  $expiretime=120;
                   5673:                }
                   5674: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5675:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5676:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5677: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5678:                }
1.620     albertel 5679:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5680:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5681: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5682:                        &log($env{'user.domain'},$env{'user.name'},
                   5683:                             $env{'user.home'},
1.57      www      5684:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5685:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5686:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5687: 		       return '';
                   5688:                    }
                   5689:                }
1.620     albertel 5690:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5691:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5692: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5693:                        &log($env{'user.domain'},$env{'user.name'},
                   5694:                             $env{'user.home'},
1.57      www      5695:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5696:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5697:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5698: 		       return '';
                   5699:                    }
                   5700:                }
                   5701: 	   }
1.29      www      5702:        }
1.52      www      5703:     }
                   5704:    
                   5705: #
                   5706: # Rest of the restrictions depend on selected course
                   5707: #
                   5708: 
1.620     albertel 5709:     unless ($env{'request.course.id'}) {
1.766     albertel 5710: 	if ($thisallowed eq 'A') {
                   5711: 	    return 'A';
1.814     raeburn  5712:         } elsif ($thisallowed eq 'B') {
                   5713:             return 'B';
1.766     albertel 5714: 	} else {
                   5715: 	    return '1';
                   5716: 	}
1.52      www      5717:     }
1.29      www      5718: 
1.52      www      5719: #
                   5720: # Now user is definitely in a course
                   5721: #
1.53      www      5722: 
                   5723: 
                   5724: # Course preferences
                   5725: 
                   5726:    if ($thisallowed=~/C/) {
1.620     albertel 5727:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5728:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5729:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5730: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5731: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5732: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5733: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5734: 			$env{'request.course.id'});
                   5735: 	   }
1.237     www      5736:            return '';
                   5737:        }
                   5738: 
1.620     albertel 5739:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5740: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5741: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5742: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5743: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5744: 			$env{'request.course.id'});
                   5745: 	   }
1.54      www      5746:            return '';
                   5747:        }
1.53      www      5748:    }
                   5749: 
                   5750: # Resource preferences
                   5751: 
                   5752:    if ($thisallowed=~/R/) {
1.620     albertel 5753:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5754:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5755: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5756: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5757: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5758: 	   }
                   5759: 	   return '';
1.54      www      5760:        }
1.53      www      5761:    }
1.30      www      5762: 
1.246     www      5763: # Restricted by state or randomout?
1.30      www      5764: 
1.52      www      5765:    if ($thisallowed=~/X/) {
1.620     albertel 5766:       if ($env{'acc.randomout'}) {
1.579     albertel 5767: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5768:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5769:             return ''; 
                   5770:          }
1.247     www      5771:       }
                   5772:       if (&condval($statecond)) {
1.52      www      5773: 	 return '2';
                   5774:       } else {
                   5775:          return '';
                   5776:       }
                   5777:    }
1.30      www      5778: 
1.766     albertel 5779:     if ($thisallowed eq 'A') {
                   5780: 	return 'A';
1.814     raeburn  5781:     } elsif ($thisallowed eq 'B') {
                   5782:         return 'B';
1.766     albertel 5783:     }
1.52      www      5784:    return 'F';
1.232     www      5785: }
                   5786: 
1.710     albertel 5787: sub split_uri_for_cond {
                   5788:     my $uri=&deversion(&declutter(shift));
                   5789:     my @uriparts=split(/\//,$uri);
                   5790:     my $filename=pop(@uriparts);
                   5791:     my $pathname=join('/',@uriparts);
                   5792:     return ($pathname,$filename);
                   5793: }
1.232     www      5794: # --------------------------------------------------- Is a resource on the map?
                   5795: 
                   5796: sub is_on_map {
1.710     albertel 5797:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5798:     #Trying to find the conditional for the file
1.620     albertel 5799:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5800: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5801:     if ($match) {
1.289     bowersj2 5802: 	return (1,$1);
                   5803:     } else {
1.434     www      5804: 	return (0,0);
1.289     bowersj2 5805:     }
1.12      www      5806: }
                   5807: 
1.427     www      5808: # --------------------------------------------------------- Get symb from alias
                   5809: 
                   5810: sub get_symb_from_alias {
                   5811:     my $symb=shift;
                   5812:     my ($map,$resid,$url)=&decode_symb($symb);
                   5813: # Already is a symb
                   5814:     if ($url) { return $symb; }
                   5815: # Must be an alias
                   5816:     my $aliassymb='';
                   5817:     my %bighash;
1.620     albertel 5818:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5819:                             &GDBM_READER(),0640)) {
                   5820:         my $rid=$bighash{'mapalias_'.$symb};
                   5821: 	if ($rid) {
                   5822: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5823: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5824: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5825: 	}
                   5826:         untie %bighash;
                   5827:     }
                   5828:     return $aliassymb;
                   5829: }
                   5830: 
1.12      www      5831: # ----------------------------------------------------------------- Define Role
                   5832: 
                   5833: sub definerole {
                   5834:   if (allowed('mcr','/')) {
                   5835:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5836:     foreach my $role (split(':',$sysrole)) {
                   5837: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5838:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5839:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5840: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5841:                return "refused:s:$crole&$cqual"; 
                   5842:             }
                   5843:         }
1.191     harris41 5844:     }
1.800     albertel 5845:     foreach my $role (split(':',$domrole)) {
                   5846: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5847:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5848:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5849: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5850:                return "refused:d:$crole&$cqual"; 
                   5851:             }
                   5852:         }
1.191     harris41 5853:     }
1.800     albertel 5854:     foreach my $role (split(':',$courole)) {
                   5855: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5856:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5857:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5858: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5859:                return "refused:c:$crole&$cqual"; 
                   5860:             }
                   5861:         }
1.191     harris41 5862:     }
1.620     albertel 5863:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5864:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5865: 	        "rolesdef_$rolename=".
                   5866:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5867:     return reply($command,$env{'user.home'});
1.12      www      5868:   } else {
                   5869:     return 'refused';
                   5870:   }
1.105     harris41 5871: }
                   5872: 
                   5873: # ---------------- Make a metadata query against the network of library servers
                   5874: 
                   5875: sub metadata_query {
1.244     matthew  5876:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5877:     my %rhash;
1.845     albertel 5878:     my %libserv = &all_library();
1.244     matthew  5879:     my @server_list = (defined($server_array) ? @$server_array
                   5880:                                               : keys(%libserv) );
                   5881:     for my $server (@server_list) {
1.118     harris41 5882: 	unless ($custom or $customshow) {
                   5883: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5884: 	    $rhash{$server}=$reply;
                   5885: 	}
                   5886: 	else {
                   5887: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5888: 			     &escape($custom).':'.&escape($customshow),
                   5889: 			     $server);
                   5890: 	    $rhash{$server}=$reply;
                   5891: 	}
1.112     harris41 5892:     }
1.118     harris41 5893:     return \%rhash;
1.240     www      5894: }
                   5895: 
                   5896: # ----------------------------------------- Send log queries and wait for reply
                   5897: 
                   5898: sub log_query {
                   5899:     my ($uname,$udom,$query,%filters)=@_;
                   5900:     my $uhome=&homeserver($uname,$udom);
                   5901:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5902:     my $uhost=&hostname($uhome);
1.800     albertel 5903:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5904:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5905:                        $uhome);
1.479     albertel 5906:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5907:     return get_query_reply($queryid);
                   5908: }
                   5909: 
1.818     raeburn  5910: # -------------------------- Update MySQL table for portfolio file
                   5911: 
                   5912: sub update_portfolio_table {
1.821     raeburn  5913:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5914:     if ($group ne '') {
                   5915:         $file_name =~s /^\Q$group\E//;
                   5916:     }
1.818     raeburn  5917:     my $homeserver = &homeserver($uname,$udom);
                   5918:     my $queryid=
1.821     raeburn  5919:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5920:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5921:     my $reply = &get_query_reply($queryid);
                   5922:     return $reply;
                   5923: }
                   5924: 
1.899     raeburn  5925: # -------------------------- Update MySQL allusers table
                   5926: 
                   5927: sub update_allusers_table {
                   5928:     my ($uname,$udom,$names) = @_;
                   5929:     my $homeserver = &homeserver($uname,$udom);
                   5930:     my $queryid=
                   5931:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5932:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5933:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5934:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5935:                'generation='.&escape($names->{'generation'}).'%%'.
                   5936:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5937:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  5938:     return;
1.899     raeburn  5939: }
                   5940: 
1.508     raeburn  5941: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5942: 
                   5943: sub fetch_enrollment_query {
1.511     raeburn  5944:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5945:     my $homeserver;
1.547     raeburn  5946:     my $maxtries = 1;
1.508     raeburn  5947:     if ($context eq 'automated') {
                   5948:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5949:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5950:     } else {
                   5951:         $homeserver = &homeserver($cnum,$dom);
                   5952:     }
1.838     albertel 5953:     my $host=&hostname($homeserver);
1.506     raeburn  5954:     my $cmd = '';
1.1000    raeburn  5955:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5956:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5957:     }
                   5958:     $cmd =~ s/%%$//;
                   5959:     $cmd = &escape($cmd);
                   5960:     my $query = 'fetchenrollment';
1.620     albertel 5961:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5962:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5963:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5964:         return 'error: '.$queryid;
                   5965:     }
1.506     raeburn  5966:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5967:     my $tries = 1;
                   5968:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5969:         $reply = &get_query_reply($queryid);
                   5970:         $tries ++;
                   5971:     }
1.526     raeburn  5972:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5973:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5974:     } else {
1.901     albertel 5975:         my @responses = split(/:/,$reply);
1.515     raeburn  5976:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5977:             foreach my $line (@responses) {
                   5978:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5979:                 $$replyref{$key} = $value;
                   5980:             }
                   5981:         } else {
1.506     raeburn  5982:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5983:             foreach my $line (@responses) {
                   5984:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5985:                 $$replyref{$key} = $value;
                   5986:                 if ($value > 0) {
1.800     albertel 5987:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5988:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5989:                         my $destname = $pathname.'/'.$filename;
                   5990:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5991:                         if ($xml_classlist =~ /^error/) {
                   5992:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5993:                         } else {
1.506     raeburn  5994:                             if ( open(FILE,">$destname") ) {
                   5995:                                 print FILE &unescape($xml_classlist);
                   5996:                                 close(FILE);
1.526     raeburn  5997:                             } else {
                   5998:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5999:                             }
                   6000:                         }
                   6001:                     }
                   6002:                 }
                   6003:             }
                   6004:         }
                   6005:         return 'ok';
                   6006:     }
                   6007:     return 'error';
                   6008: }
                   6009: 
1.242     www      6010: sub get_query_reply {
                   6011:     my $queryid=shift;
1.240     www      6012:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   6013:     my $reply='';
                   6014:     for (1..100) {
                   6015: 	sleep 2;
                   6016:         if (-e $replyfile.'.end') {
1.448     albertel 6017: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6018: 		$reply = join('',<$fh>);
                   6019: 		close($fh);
1.240     www      6020: 	   } else { return 'error: reply_file_error'; }
1.242     www      6021:            return &unescape($reply);
                   6022: 	}
1.240     www      6023:     }
1.242     www      6024:     return 'timeout:'.$queryid;
1.240     www      6025: }
                   6026: 
                   6027: sub courselog_query {
1.241     www      6028: #
                   6029: # possible filters:
                   6030: # url: url or symb
                   6031: # username
                   6032: # domain
                   6033: # action: view, submit, grade
                   6034: # start: timestamp
                   6035: # end: timestamp
                   6036: #
1.240     www      6037:     my (%filters)=@_;
1.620     albertel 6038:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6039:     if ($filters{'url'}) {
                   6040: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6041:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6042:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6043:     }
1.620     albertel 6044:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6045:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6046:     return &log_query($cname,$cdom,'courselog',%filters);
                   6047: }
                   6048: 
                   6049: sub userlog_query {
1.858     raeburn  6050: #
                   6051: # possible filters:
                   6052: # action: log check role
                   6053: # start: timestamp
                   6054: # end: timestamp
                   6055: #
1.240     www      6056:     my ($uname,$udom,%filters)=@_;
                   6057:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6058: }
                   6059: 
1.506     raeburn  6060: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6061: 
                   6062: sub auto_run {
1.508     raeburn  6063:     my ($cnum,$cdom) = @_;
1.876     raeburn  6064:     my $response = 0;
                   6065:     my $settings;
                   6066:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6067:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6068:         $settings = $domconfig{'autoenroll'};
                   6069:         if ($settings->{'run'} eq '1') {
                   6070:             $response = 1;
                   6071:         }
                   6072:     } else {
1.934     raeburn  6073:         my $homeserver;
                   6074:         if (&is_course($cdom,$cnum)) {
                   6075:             $homeserver = &homeserver($cnum,$cdom);
                   6076:         } else {
                   6077:             $homeserver = &domain($cdom,'primary');
                   6078:         }
                   6079:         if ($homeserver ne 'no_host') {
                   6080:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6081:         }
1.876     raeburn  6082:     }
1.506     raeburn  6083:     return $response;
                   6084: }
1.776     albertel 6085: 
1.506     raeburn  6086: sub auto_get_sections {
1.508     raeburn  6087:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6088:     my $homeserver;
                   6089:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6090:         $homeserver = &homeserver($cnum,$cdom);
                   6091:     }
                   6092:     if (!defined($homeserver)) { 
                   6093:         if ($cdom =~ /^$match_domain$/) {
                   6094:             $homeserver = &domain($cdom,'primary');
                   6095:         }
                   6096:     }
                   6097:     my @secs;
                   6098:     if (defined($homeserver)) {
                   6099:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6100:         unless ($response eq 'refused') {
                   6101:             @secs = split(/:/,$response);
                   6102:         }
1.506     raeburn  6103:     }
                   6104:     return @secs;
                   6105: }
1.776     albertel 6106: 
1.506     raeburn  6107: sub auto_new_course {
1.1099    raeburn  6108:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6109:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6110:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6111:     return $response;
                   6112: }
1.776     albertel 6113: 
1.506     raeburn  6114: sub auto_validate_courseID {
1.508     raeburn  6115:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6116:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6117:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6118:     return $response;
                   6119: }
1.776     albertel 6120: 
1.1007    raeburn  6121: sub auto_validate_instcode {
1.1020    raeburn  6122:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6123:     my ($homeserver,$response);
                   6124:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6125:         $homeserver = &homeserver($cnum,$cdom);
                   6126:     }
                   6127:     if (!defined($homeserver)) {
                   6128:         if ($cdom =~ /^$match_domain$/) {
                   6129:             $homeserver = &domain($cdom,'primary');
                   6130:         }
                   6131:     }
1.1065    raeburn  6132:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6133:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6134:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6135:     return ($outcome,$description);
1.1007    raeburn  6136: }
                   6137: 
1.506     raeburn  6138: sub auto_create_password {
1.873     raeburn  6139:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6140:     my ($homeserver,$response);
1.506     raeburn  6141:     my $create_passwd = 0;
                   6142:     my $authchk = '';
1.873     raeburn  6143:     if ($udom =~ /^$match_domain$/) {
                   6144:         $homeserver = &domain($udom,'primary');
                   6145:     }
                   6146:     if ($homeserver eq '') {
                   6147:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6148:             $homeserver = &homeserver($cnum,$cdom);
                   6149:         }
                   6150:     }
                   6151:     if ($homeserver eq '') {
                   6152:         $authchk = 'nodomain';
1.506     raeburn  6153:     } else {
1.873     raeburn  6154:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6155:         if ($response eq 'refused') {
                   6156:             $authchk = 'refused';
                   6157:         } else {
1.901     albertel 6158:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6159:         }
1.506     raeburn  6160:     }
                   6161:     return ($authparam,$create_passwd,$authchk);
                   6162: }
                   6163: 
1.706     raeburn  6164: sub auto_photo_permission {
                   6165:     my ($cnum,$cdom,$students) = @_;
                   6166:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6167:     my ($outcome,$perm_reqd,$conditions) = 
                   6168: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6169:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6170: 	return (undef,undef);
                   6171:     }
1.706     raeburn  6172:     return ($outcome,$perm_reqd,$conditions);
                   6173: }
                   6174: 
                   6175: sub auto_checkphotos {
                   6176:     my ($uname,$udom,$pid) = @_;
                   6177:     my $homeserver = &homeserver($uname,$udom);
                   6178:     my ($result,$resulttype);
                   6179:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6180: 				   &escape($uname).':'.&escape($pid),
                   6181: 				   $homeserver));
1.709     albertel 6182:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6183: 	return (undef,undef);
                   6184:     }
1.706     raeburn  6185:     if ($outcome) {
                   6186:         ($result,$resulttype) = split(/:/,$outcome);
                   6187:     } 
                   6188:     return ($result,$resulttype);
                   6189: }
                   6190: 
                   6191: sub auto_photochoice {
                   6192:     my ($cnum,$cdom) = @_;
                   6193:     my $homeserver = &homeserver($cnum,$cdom);
                   6194:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6195: 						       &escape($cdom),
                   6196: 						       $homeserver)));
1.709     albertel 6197:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6198: 	return (undef,undef);
                   6199:     }
1.706     raeburn  6200:     return ($update,$comment);
                   6201: }
                   6202: 
                   6203: sub auto_photoupdate {
                   6204:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6205:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6206:     my $host=&hostname($homeserver);
1.706     raeburn  6207:     my $cmd = '';
                   6208:     my $maxtries = 1;
1.800     albertel 6209:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6210:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6211:     }
                   6212:     $cmd =~ s/%%$//;
                   6213:     $cmd = &escape($cmd);
                   6214:     my $query = 'institutionalphotos';
                   6215:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6216:     unless ($queryid=~/^\Q$host\E\_/) {
                   6217:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6218:         return 'error: '.$queryid;
                   6219:     }
                   6220:     my $reply = &get_query_reply($queryid);
                   6221:     my $tries = 1;
                   6222:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6223:         $reply = &get_query_reply($queryid);
                   6224:         $tries ++;
                   6225:     }
                   6226:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6227:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6228:     } else {
                   6229:         my @responses = split(/:/,$reply);
                   6230:         my $outcome = shift(@responses); 
                   6231:         foreach my $item (@responses) {
                   6232:             my ($key,$value) = split(/=/,$item);
                   6233:             $$photo{$key} = $value;
                   6234:         }
                   6235:         return $outcome;
                   6236:     }
                   6237:     return 'error';
                   6238: }
                   6239: 
1.521     raeburn  6240: sub auto_instcode_format {
1.793     albertel 6241:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6242: 	$cat_order) = @_;
1.521     raeburn  6243:     my $courses = '';
1.772     raeburn  6244:     my @homeservers;
1.521     raeburn  6245:     if ($caller eq 'global') {
1.841     albertel 6246: 	my %servers = &get_servers($codedom,'library');
                   6247: 	foreach my $tryserver (keys(%servers)) {
                   6248: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6249: 		push(@homeservers,$tryserver);
                   6250: 	    }
1.584     raeburn  6251:         }
1.1022    raeburn  6252:     } elsif ($caller eq 'requests') {
                   6253:         if ($codedom =~ /^$match_domain$/) {
                   6254:             my $chome = &domain($codedom,'primary');
                   6255:             unless ($chome eq 'no_host') {
                   6256:                 push(@homeservers,$chome);
                   6257:             }
                   6258:         }
1.521     raeburn  6259:     } else {
1.772     raeburn  6260:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6261:     }
1.793     albertel 6262:     foreach my $code (keys(%{$instcodes})) {
                   6263:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6264:     }
                   6265:     chop($courses);
1.772     raeburn  6266:     my $ok_response = 0;
                   6267:     my $response;
                   6268:     while (@homeservers > 0 && $ok_response == 0) {
                   6269:         my $server = shift(@homeservers); 
                   6270:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6271:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6272:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6273: 		split(/:/,$response);
1.772     raeburn  6274:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6275:             push(@{$codetitles},&str2array($codetitles_str));
                   6276:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6277:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6278:             $ok_response = 1;
                   6279:         }
                   6280:     }
                   6281:     if ($ok_response) {
1.521     raeburn  6282:         return 'ok';
1.772     raeburn  6283:     } else {
                   6284:         return $response;
1.521     raeburn  6285:     }
                   6286: }
                   6287: 
1.792     raeburn  6288: sub auto_instcode_defaults {
                   6289:     my ($domain,$returnhash,$code_order) = @_;
                   6290:     my @homeservers;
1.841     albertel 6291: 
                   6292:     my %servers = &get_servers($domain,'library');
                   6293:     foreach my $tryserver (keys(%servers)) {
                   6294: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6295: 	    push(@homeservers,$tryserver);
                   6296: 	}
1.792     raeburn  6297:     }
1.841     albertel 6298: 
1.792     raeburn  6299:     my $response;
1.841     albertel 6300:     foreach my $server (@homeservers) {
1.792     raeburn  6301:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6302:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6303: 	
                   6304: 	foreach my $pair (split(/\&/,$response)) {
                   6305: 	    my ($name,$value)=split(/\=/,$pair);
                   6306: 	    if ($name eq 'code_order') {
                   6307: 		@{$code_order} = split(/\&/,&unescape($value));
                   6308: 	    } else {
                   6309: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6310: 	    }
                   6311: 	}
                   6312: 	return 'ok';
1.792     raeburn  6313:     }
1.841     albertel 6314: 
                   6315:     return $response;
1.1003    raeburn  6316: }
                   6317: 
                   6318: sub auto_possible_instcodes {
1.1007    raeburn  6319:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6320:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6321:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6322:         return;
                   6323:     }
1.1003    raeburn  6324:     my (@homeservers,$uhome);
                   6325:     if (defined(&domain($domain,'primary'))) {
                   6326:         $uhome=&domain($domain,'primary');
                   6327:         push(@homeservers,&domain($domain,'primary'));
                   6328:     } else {
                   6329:         my %servers = &get_servers($domain,'library');
                   6330:         foreach my $tryserver (keys(%servers)) {
                   6331:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6332:                 push(@homeservers,$tryserver);
                   6333:             }
                   6334:         }
                   6335:     }
                   6336:     my $response;
                   6337:     foreach my $server (@homeservers) {
                   6338:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6339:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6340:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6341:             split(':',$response);
                   6342:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6343:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6344:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6345:             my ($name,$value)=split('=',$item);
                   6346:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6347:         }
                   6348:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6349:             my ($name,$value)=split('=',$item);
                   6350:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6351:         }
                   6352:         return 'ok';
                   6353:     }
                   6354:     return $response;
                   6355: }
1.792     raeburn  6356: 
1.1010    raeburn  6357: sub auto_courserequest_checks {
                   6358:     my ($dom) = @_;
1.1020    raeburn  6359:     my ($homeserver,%validations);
                   6360:     if ($dom =~ /^$match_domain$/) {
                   6361:         $homeserver = &domain($dom,'primary');
                   6362:     }
                   6363:     unless ($homeserver eq 'no_host') {
                   6364:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6365:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6366:             my @items = split(/&/,$response);
                   6367:             foreach my $item (@items) {
                   6368:                 my ($key,$value) = split('=',$item);
                   6369:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6370:             }
                   6371:         }
                   6372:     }
1.1010    raeburn  6373:     return %validations; 
                   6374: }
                   6375: 
1.1020    raeburn  6376: sub auto_courserequest_validation {
                   6377:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6378:     my ($homeserver,$response);
                   6379:     if ($dom =~ /^$match_domain$/) {
                   6380:         $homeserver = &domain($dom,'primary');
                   6381:     }
                   6382:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6383:           
1.1020    raeburn  6384:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6385:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6386:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6387:                                     $homeserver));
                   6388:     }
                   6389:     return $response;
                   6390: }
                   6391: 
1.777     albertel 6392: sub auto_validate_class_sec {
1.918     raeburn  6393:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6394:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6395:     my $ownerlist;
                   6396:     if (ref($owners) eq 'ARRAY') {
                   6397:         $ownerlist = join(',',@{$owners});
                   6398:     } else {
                   6399:         $ownerlist = $owners;
                   6400:     }
1.773     raeburn  6401:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6402:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6403:     return $response;
                   6404: }
                   6405: 
1.679     raeburn  6406: # ------------------------------------------------------- Course Group routines
                   6407: 
                   6408: sub get_coursegroups {
1.809     raeburn  6409:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6410:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6411: }
                   6412: 
1.679     raeburn  6413: sub modify_coursegroup {
                   6414:     my ($cdom,$cnum,$groupsettings) = @_;
                   6415:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6416: }
                   6417: 
1.809     raeburn  6418: sub toggle_coursegroup_status {
                   6419:     my ($cdom,$cnum,$group,$action) = @_;
                   6420:     my ($from_namespace,$to_namespace);
                   6421:     if ($action eq 'delete') {
                   6422:         $from_namespace = 'coursegroups';
                   6423:         $to_namespace = 'deleted_groups';
                   6424:     } else {
                   6425:         $from_namespace = 'deleted_groups';
                   6426:         $to_namespace = 'coursegroups';
                   6427:     }
                   6428:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6429:     if (my $tmp = &error(%curr_group)) {
                   6430:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6431:         return ('read error',$tmp);
                   6432:     } else {
                   6433:         my %savedsettings = %curr_group; 
1.809     raeburn  6434:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6435:         my $deloutcome;
                   6436:         if ($result eq 'ok') {
1.809     raeburn  6437:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6438:         } else {
                   6439:             return ('write error',$result);
                   6440:         }
                   6441:         if ($deloutcome eq 'ok') {
                   6442:             return 'ok';
                   6443:         } else {
                   6444:             return ('delete error',$deloutcome);
                   6445:         }
                   6446:     }
                   6447: }
                   6448: 
1.679     raeburn  6449: sub modify_group_roles {
1.957     raeburn  6450:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6451:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6452:     my $role = 'gr/'.&escape($userprivs);
                   6453:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6454:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6455:     if ($result eq 'ok') {
                   6456:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6457:     }
1.679     raeburn  6458:     return $result;
                   6459: }
                   6460: 
                   6461: sub modify_coursegroup_membership {
                   6462:     my ($cdom,$cnum,$membership) = @_;
                   6463:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6464:     return $result;
                   6465: }
                   6466: 
1.682     raeburn  6467: sub get_active_groups {
                   6468:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6469:     my $now = time;
                   6470:     my %groups = ();
                   6471:     foreach my $key (keys(%env)) {
1.811     albertel 6472:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6473:             my ($start,$end) = split(/\./,$env{$key});
                   6474:             if (($end!=0) && ($end<$now)) { next; }
                   6475:             if (($start!=0) && ($start>$now)) { next; }
                   6476:             if ($1 eq $cdom && $2 eq $cnum) {
                   6477:                 $groups{$3} = $env{$key} ;
                   6478:             }
                   6479:         }
                   6480:     }
                   6481:     return %groups;
                   6482: }
                   6483: 
1.683     raeburn  6484: sub get_group_membership {
                   6485:     my ($cdom,$cnum,$group) = @_;
                   6486:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6487: }
                   6488: 
                   6489: sub get_users_groups {
                   6490:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6491:     my @usersgroups;
1.683     raeburn  6492:     my $cachetime=1800;
                   6493: 
                   6494:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6495:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6496:     if (defined($cached)) {
1.734     albertel 6497:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6498:     } else {  
                   6499:         $grouplist = '';
1.816     raeburn  6500:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6501:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6502:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6503:         my $access_end = $env{'course.'.$courseid.
                   6504:                               '.default_enrollment_end_date'};
                   6505:         my $now = time;
                   6506:         foreach my $key (keys(%roleshash)) {
                   6507:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6508:                 my $group = $1;
                   6509:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6510:                     my $start = $2;
                   6511:                     my $end = $1;
                   6512:                     if ($start == -1) { next; } # deleted from group
                   6513:                     if (($start!=0) && ($start>$now)) { next; }
                   6514:                     if (($end!=0) && ($end<$now)) {
                   6515:                         if ($access_end && $access_end < $now) {
                   6516:                             if ($access_end - $end < 86400) {
                   6517:                                 push(@usersgroups,$group);
1.733     raeburn  6518:                             }
                   6519:                         }
1.817     raeburn  6520:                         next;
1.733     raeburn  6521:                     }
1.817     raeburn  6522:                     push(@usersgroups,$group);
1.683     raeburn  6523:                 }
                   6524:             }
                   6525:         }
1.817     raeburn  6526:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6527:         $grouplist = join(':',@usersgroups);
                   6528:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6529:     }
1.733     raeburn  6530:     return @usersgroups;
1.683     raeburn  6531: }
                   6532: 
                   6533: sub devalidate_getgroups_cache {
                   6534:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6535:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6536: 
1.683     raeburn  6537:     my $hashid="$udom:$uname:$courseid";
                   6538:     &devalidate_cache_new('getgroups',$hashid);
                   6539: }
                   6540: 
1.12      www      6541: # ------------------------------------------------------------------ Plain Text
                   6542: 
                   6543: sub plaintext {
1.988     raeburn  6544:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6545:     if ($short =~ m{^cr/}) {
1.758     albertel 6546: 	return (split('/',$short))[-1];
                   6547:     }
1.742     raeburn  6548:     if (!defined($cid)) {
                   6549:         $cid = $env{'request.course.id'};
                   6550:     }
                   6551:     my %rolenames = (
1.1008    raeburn  6552:                       Course    => 'std',
                   6553:                       Community => 'alt1',
1.742     raeburn  6554:                     );
1.1037    raeburn  6555:     if ($cid ne '') {
                   6556:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6557:             unless ($forcedefault) {
                   6558:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6559:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6560:                 return &Apache::lonlocal::mt($roletext);
                   6561:             }
                   6562:         }
                   6563:     }
                   6564:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6565:         (defined($rolenames{$type})) && 
                   6566:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6567:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6568:     } elsif ($cid ne '') {
                   6569:         my $crstype = $env{'course.'.$cid.'.type'};
                   6570:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6571:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6572:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6573:         }
1.742     raeburn  6574:     }
1.1037    raeburn  6575:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6576: }
                   6577: 
                   6578: # ----------------------------------------------------------------- Assign Role
                   6579: 
                   6580: sub assignrole {
1.957     raeburn  6581:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6582:         $context)=@_;
1.21      www      6583:     my $mrole;
                   6584:     if ($role =~ /^cr\//) {
1.393     www      6585:         my $cwosec=$url;
1.811     albertel 6586:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6587: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6588:            my $refused = 1;
                   6589:            if ($context eq 'requestcourses') {
                   6590:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6591:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6592:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6593:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6594:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6595:                            if ($crsenv{'internal.courseowner'} eq
                   6596:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6597:                                $refused = '';
                   6598:                            }
                   6599:                        }
                   6600:                    }
                   6601:                }
                   6602:            }
                   6603:            if ($refused) {
                   6604:                &logthis('Refused custom assignrole: '.
                   6605:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6606:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6607:                return 'refused';
                   6608:            }
1.104     www      6609:         }
1.21      www      6610:         $mrole='cr';
1.678     raeburn  6611:     } elsif ($role =~ /^gr\//) {
                   6612:         my $cwogrp=$url;
1.811     albertel 6613:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6614:         unless (&allowed('mdg',$cwogrp)) {
                   6615:             &logthis('Refused group assignrole: '.
                   6616:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6617:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6618:             return 'refused';
                   6619:         }
                   6620:         $mrole='gr';
1.21      www      6621:     } else {
1.82      www      6622:         my $cwosec=$url;
1.811     albertel 6623:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6624:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6625:             my $refused;
                   6626:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6627:                 if (!(&allowed('c'.$role,$url))) {
                   6628:                     $refused = 1;
                   6629:                 }
                   6630:             } else {
                   6631:                 $refused = 1;
                   6632:             }
1.947     raeburn  6633:             if ($refused) {
1.1045    raeburn  6634:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6635:                 if (!$selfenroll && $context eq 'course') {
                   6636:                     my %crsenv;
                   6637:                     if ($role eq 'cc' || $role eq 'co') {
                   6638:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6639:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6640:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6641:                                 if ($crsenv{'internal.courseowner'} eq 
                   6642:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6643:                                     $refused = '';
                   6644:                                 }
                   6645:                             }
                   6646:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6647:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6648:                                 if ($crsenv{'internal.courseowner'} eq 
                   6649:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6650:                                     $refused = '';
                   6651:                                 }
                   6652:                             }
                   6653:                         }
                   6654:                     }
                   6655:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6656:                     $refused = '';
1.1017    raeburn  6657:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6658:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6659:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6660:                         my $wrongcc;
                   6661:                         if ($cnum =~ /^$match_community$/) {
                   6662:                             $wrongcc = 1 if ($role eq 'cc');
                   6663:                         } else {
                   6664:                             $wrongcc = 1 if ($role eq 'co');
                   6665:                         }
                   6666:                         unless ($wrongcc) {
                   6667:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6668:                             if ($crsenv{'internal.courseowner'} eq 
                   6669:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6670:                                 $refused = '';
                   6671:                             }
1.1017    raeburn  6672:                         }
                   6673:                     }
                   6674:                 }
                   6675:                 if ($refused) {
1.947     raeburn  6676:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6677:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6678: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6679:                     return 'refused';
                   6680:                 }
1.932     raeburn  6681:             }
1.104     www      6682:         }
1.21      www      6683:         $mrole=$role;
                   6684:     }
1.620     albertel 6685:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6686:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6687:     if ($end) { $command.='_'.$end; }
1.21      www      6688:     if ($start) {
                   6689: 	if ($end) { 
1.81      www      6690:            $command.='_'.$start; 
1.21      www      6691:         } else {
1.81      www      6692:            $command.='_0_'.$start;
1.21      www      6693:         }
                   6694:     }
1.739     raeburn  6695:     my $origstart = $start;
                   6696:     my $origend = $end;
1.957     raeburn  6697:     my $delflag;
1.357     www      6698: # actually delete
                   6699:     if ($deleteflag) {
1.373     www      6700: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6701: # modify command to delete the role
1.620     albertel 6702:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6703:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6704: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6705: # set start and finish to negative values for userrolelog
                   6706:            $start=-1;
                   6707:            $end=-1;
1.957     raeburn  6708:            $delflag = 1;
1.357     www      6709:         }
                   6710:     }
                   6711: # send command
1.349     www      6712:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6713: # log new user role if status is ok
1.349     www      6714:     if ($answer eq 'ok') {
1.663     raeburn  6715: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6716: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6717:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6718:         unless ($role =~ /^gr/) {
                   6719:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6720:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6721:         }
1.1053    raeburn  6722:         if ($role eq 'cc') {
                   6723:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6724:         }
1.349     www      6725:     }
                   6726:     return $answer;
1.169     harris41 6727: }
                   6728: 
1.1053    raeburn  6729: sub autoupdate_coowners {
                   6730:     my ($url,$end,$start,$uname,$udom) = @_;
                   6731:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6732:     if (($cdom ne '') && ($cnum ne '')) {
                   6733:         my $now = time;
                   6734:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6735:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6736:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6737:             my $instcode = $coursehash{'internal.coursecode'};
                   6738:             if ($instcode ne '') {
1.1056    raeburn  6739:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6740:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6741:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6742:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6743:                         if ($result eq 'valid') {
                   6744:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6745:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6746:                                     push(@newcoowners,$coowner);
                   6747:                                 }
                   6748:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6749:                                     push(@newcoowners,$uname.':'.$udom);
                   6750:                                 }
                   6751:                                 @newcoowners = sort(@newcoowners);
                   6752:                             } else {
                   6753:                                 push(@newcoowners,$uname.':'.$udom);
                   6754:                             }
                   6755:                         } else {
                   6756:                             if ($coursehash{'internal.co-owners'}) {
                   6757:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6758:                                     unless ($coowner eq $uname.':'.$udom) {
                   6759:                                         push(@newcoowners,$coowner);
                   6760:                                     }
                   6761:                                 }
                   6762:                                 unless (@newcoowners > 0) {
                   6763:                                     $delcoowners = 1;
                   6764:                                     $coowners = '';
                   6765:                                 }
                   6766:                             }
                   6767:                         }
                   6768:                         if (@newcoowners || $delcoowners) {
                   6769:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6770:                                             $delcoowners,@newcoowners);
                   6771:                         }
                   6772:                     }
                   6773:                 }
                   6774:             }
                   6775:         }
                   6776:     }
                   6777: }
                   6778: 
                   6779: sub store_coowners {
                   6780:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6781:     my $cid = $cdom.'_'.$cnum;
                   6782:     my ($coowners,$delresult,$putresult);
                   6783:     if (@newcoowners) {
                   6784:         $coowners = join(',',@newcoowners);
                   6785:         my %coownershash = (
                   6786:                             'internal.co-owners' => $coowners,
                   6787:                            );
                   6788:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6789:         if ($putresult eq 'ok') {
                   6790:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6791:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6792:             }
                   6793:         }
                   6794:     }
                   6795:     if ($delcoowners) {
                   6796:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6797:         if ($delresult eq 'ok') {
                   6798:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6799:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6800:             }
                   6801:         }
                   6802:     }
                   6803:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6804:         my %crsinfo =
                   6805:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6806:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6807:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6808:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6809:         }
                   6810:     }
                   6811: }
                   6812: 
1.169     harris41 6813: # -------------------------------------------------- Modify user authentication
1.197     www      6814: # Overrides without validation
                   6815: 
1.169     harris41 6816: sub modifyuserauth {
                   6817:     my ($udom,$uname,$umode,$upass)=@_;
                   6818:     my $uhome=&homeserver($uname,$udom);
1.197     www      6819:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6820:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6821:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6822:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6823:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6824: 		     &escape($upass),$uhome);
1.620     albertel 6825:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6826:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6827:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6828:     &log($udom,,$uname,$uhome,
1.620     albertel 6829:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6830:                                      $env{'user.name'}.', '.$umode.
1.197     www      6831:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6832:     unless ($reply eq 'ok') {
1.197     www      6833:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6834: 	return 'error: '.$reply;
                   6835:     }   
1.170     harris41 6836:     return 'ok';
1.80      www      6837: }
                   6838: 
1.81      www      6839: # --------------------------------------------------------------- Modify a user
1.80      www      6840: 
1.81      www      6841: sub modifyuser {
1.206     matthew  6842:     my ($udom,    $uname, $uid,
                   6843:         $umode,   $upass, $first,
                   6844:         $middle,  $last,  $gene,
1.1058    raeburn  6845:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6846:     $udom= &LONCAPA::clean_domain($udom);
                   6847:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6848:     my $showcandelete = 'none';
                   6849:     if (ref($candelete) eq 'ARRAY') {
                   6850:         if (@{$candelete} > 0) {
                   6851:             $showcandelete = join(', ',@{$candelete});
                   6852:         }
                   6853:     }
1.81      www      6854:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6855:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6856: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6857:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6858:                                      ' desiredhome not specified'). 
1.620     albertel 6859:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6860:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6861:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6862:     my $newuser;
                   6863:     if ($uhome eq 'no_host') {
                   6864:         $newuser = 1;
                   6865:     }
1.80      www      6866: # ----------------------------------------------------------------- Create User
1.406     albertel 6867:     if (($uhome eq 'no_host') && 
                   6868: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6869:         my $unhome='';
1.844     albertel 6870:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6871:             $unhome = $desiredhome;
1.620     albertel 6872: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6873: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6874:         } else { # load balancing routine for determining $unhome
1.81      www      6875:             my $loadm=10000000;
1.841     albertel 6876: 	    my %servers = &get_servers($udom,'library');
                   6877: 	    foreach my $tryserver (keys(%servers)) {
                   6878: 		my $answer=reply('load',$tryserver);
                   6879: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6880: 		    $loadm=$answer;
                   6881: 		    $unhome=$tryserver;
                   6882: 		}
1.80      www      6883: 	    }
                   6884:         }
                   6885:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6886: 	    return 'error: unable to find a home server for '.$uname.
                   6887:                    ' in domain '.$udom;
1.80      www      6888:         }
                   6889:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6890:                          &escape($upass),$unhome);
                   6891: 	unless ($reply eq 'ok') {
                   6892:             return 'error: '.$reply;
                   6893:         }   
1.230     stredwic 6894:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6895:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6896: 	    return 'error: unable verify users home machine.';
1.80      www      6897:         }
1.209     matthew  6898:     }   # End of creation of new user
1.80      www      6899: # ---------------------------------------------------------------------- Add ID
                   6900:     if ($uid) {
                   6901:        $uid=~tr/A-Z/a-z/;
                   6902:        my %uidhash=&idrget($udom,$uname);
1.196     www      6903:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6904:          && (!$forceid)) {
1.80      www      6905: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6906: 	      return 'error: user id "'.$uid.'" does not match '.
                   6907:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6908:           }
                   6909:        } else {
                   6910: 	  &idput($udom,($uname => $uid));
                   6911:        }
                   6912:     }
                   6913: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6914:     my @tmp=&get('environment',
1.899     raeburn  6915: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6916:                     'permanentemail','inststatus'],
1.134     albertel 6917: 		   $udom,$uname);
1.1075    raeburn  6918:     my (%names,%oldnames);
1.313     matthew  6919:     if ($tmp[0] =~ m/^error:.*/) { 
                   6920:         %names=(); 
                   6921:     } else {
                   6922:         %names = @tmp;
1.1075    raeburn  6923:         %oldnames = %names;
1.313     matthew  6924:     }
1.388     www      6925: #
1.1058    raeburn  6926: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6927: # of users did not contain them), do not overwrite existing values
                   6928: # unless field is in $candelete array ref.  
                   6929: #
                   6930: 
                   6931:     my @fields = ('firstname','middlename','lastname','generation',
                   6932:                   'permanentemail','id');
                   6933:     my %newvalues;
                   6934:     if (ref($candelete) eq 'ARRAY') {
                   6935:         foreach my $field (@fields) {
                   6936:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6937:                 if ($field eq 'firstname') {
                   6938:                     $names{$field} = $first;
                   6939:                 } elsif ($field eq 'middlename') {
                   6940:                     $names{$field} = $middle;
                   6941:                 } elsif ($field eq 'lastname') {
                   6942:                     $names{$field} = $last;
                   6943:                 } elsif ($field eq 'generation') { 
                   6944:                     $names{$field} = $gene;
                   6945:                 } elsif ($field eq 'permanentemail') {
                   6946:                     $names{$field} = $email;
                   6947:                 } elsif ($field eq 'id') {
                   6948:                     $names{$field}  = $uid;
                   6949:                 }
                   6950:             }
                   6951:         }
                   6952:     }
1.388     www      6953:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6954:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6955:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6956:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6957:     if ($email) {
                   6958:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6959:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6960:     }
1.899     raeburn  6961:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6962:     if (defined($inststatus)) {
                   6963:         $names{'inststatus'} = '';
                   6964:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6965:         if (ref($usertypes) eq 'HASH') {
                   6966:             my @okstatuses; 
                   6967:             foreach my $item (split(/:/,$inststatus)) {
                   6968:                 if (defined($usertypes->{$item})) {
                   6969:                     push(@okstatuses,$item);  
                   6970:                 }
                   6971:             }
                   6972:             if (@okstatuses) {
                   6973:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6974:             }
                   6975:         }
                   6976:     }
1.1075    raeburn  6977:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6978:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  6979:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6980:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6981:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6982:     } else {
                   6983:         $logmsg .= ' during self creation';
                   6984:     }
1.1075    raeburn  6985:     my $changed;
                   6986:     if ($newuser) {
                   6987:         $changed = 1;
                   6988:     } else {
                   6989:         foreach my $field (@fields) {
                   6990:             if ($names{$field} ne $oldnames{$field}) {
                   6991:                 $changed = 1;
                   6992:                 last;
                   6993:             }
                   6994:         }
                   6995:     }
                   6996:     unless ($changed) {
                   6997:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6998:         &logthis($logmsg);
                   6999:         return 'ok';
                   7000:     }
                   7001:     my $reply = &put('environment', \%names, $udom,$uname);
                   7002:     if ($reply ne 'ok') { 
                   7003:         return 'error: '.$reply;
                   7004:     }
1.1087    raeburn  7005:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7006:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7007:     }
1.1075    raeburn  7008:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7009:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7010:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7011:     &logthis($logmsg);
1.134     albertel 7012:     return 'ok';
1.80      www      7013: }
                   7014: 
1.81      www      7015: # -------------------------------------------------------------- Modify student
1.80      www      7016: 
1.81      www      7017: sub modifystudent {
                   7018:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7019:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7020:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7021:     if (!$cid) {
1.620     albertel 7022: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7023: 	    return 'not_in_class';
                   7024: 	}
1.80      www      7025:     }
                   7026: # --------------------------------------------------------------- Make the user
1.81      www      7027:     my $reply=&modifyuser
1.209     matthew  7028: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7029:          $desiredhome,$email,$inststatus);
1.80      www      7030:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7031:     # This will cause &modify_student_enrollment to get the uid from the
                   7032:     # students environment
                   7033:     $uid = undef if (!$forceid);
1.455     albertel 7034:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7035: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7036:     return $reply;
                   7037: }
                   7038: 
                   7039: sub modify_student_enrollment {
1.957     raeburn  7040:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7041:     my ($cdom,$cnum,$chome);
                   7042:     if (!$cid) {
1.620     albertel 7043: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7044: 	    return 'not_in_class';
                   7045: 	}
1.620     albertel 7046: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7047: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7048:     } else {
                   7049: 	($cdom,$cnum)=split(/_/,$cid);
                   7050:     }
1.620     albertel 7051:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7052:     if (!$chome) {
1.457     raeburn  7053: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7054:     }
1.455     albertel 7055:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7056:     # Make sure the user exists
1.81      www      7057:     my $uhome=&homeserver($uname,$udom);
                   7058:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7059: 	return 'error: no such user';
                   7060:     }
1.297     matthew  7061:     # Get student data if we were not given enough information
                   7062:     if (!defined($first)  || $first  eq '' || 
                   7063:         !defined($last)   || $last   eq '' || 
                   7064:         !defined($uid)    || $uid    eq '' || 
                   7065:         !defined($middle) || $middle eq '' || 
                   7066:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7067:         # They did not supply us with enough data to enroll the student, so
                   7068:         # we need to pick up more information.
1.297     matthew  7069:         my %tmp = &get('environment',
1.294     matthew  7070:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7071:                        ,$udom,$uname);
                   7072: 
1.800     albertel 7073:         #foreach my $key (keys(%tmp)) {
                   7074:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7075:         #}
1.294     matthew  7076:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7077:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7078:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7079:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7080:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7081:     }
1.556     albertel 7082:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7083:     my $reply=cput('classlist',
                   7084: 		   {"$uname:$udom" => 
1.515     raeburn  7085: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7086: 		   $cdom,$cnum);
1.81      www      7087:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7088: 	return 'error: '.$reply;
1.652     albertel 7089:     } else {
                   7090: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7091:     }
1.297     matthew  7092:     # Add student role to user
1.83      www      7093:     my $uurl='/'.$cid;
1.81      www      7094:     $uurl=~s/\_/\//g;
                   7095:     if ($usec) {
                   7096: 	$uurl.='/'.$usec;
                   7097:     }
1.957     raeburn  7098:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7099: }
                   7100: 
1.556     albertel 7101: sub format_name {
                   7102:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7103:     my $name;
                   7104:     if ($first ne 'lastname') {
                   7105: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7106:     } else {
                   7107: 	if ($lastname=~/\S/) {
                   7108: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7109: 	    $name=~s/\s+,/,/;
                   7110: 	} else {
                   7111: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7112: 	}
                   7113:     }
                   7114:     $name=~s/^\s+//;
                   7115:     $name=~s/\s+$//;
                   7116:     $name=~s/\s+/ /g;
                   7117:     return $name;
                   7118: }
                   7119: 
1.84      www      7120: # ------------------------------------------------- Write to course preferences
                   7121: 
                   7122: sub writecoursepref {
                   7123:     my ($courseid,%prefs)=@_;
                   7124:     $courseid=~s/^\///;
                   7125:     $courseid=~s/\_/\//g;
                   7126:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7127:     my $chome=homeserver($cnum,$cdomain);
                   7128:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7129: 	return 'error: no such course';
                   7130:     }
                   7131:     my $cstring='';
1.800     albertel 7132:     foreach my $pref (keys(%prefs)) {
                   7133: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7134:     }
1.84      www      7135:     $cstring=~s/\&$//;
                   7136:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7137: }
                   7138: 
                   7139: # ---------------------------------------------------------- Make/modify course
                   7140: 
                   7141: sub createcourse {
1.741     raeburn  7142:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7143:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7144:     $url=&declutter($url);
                   7145:     my $cid='';
1.1028    raeburn  7146:     if ($context eq 'requestcourses') {
                   7147:         my $can_create = 0;
                   7148:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7149:         if ($udom eq $ownerdom) {
                   7150:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7151:                                   $context)) {
                   7152:                 $can_create = 1;
                   7153:             }
                   7154:         } else {
                   7155:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7156:                                            $category);
                   7157:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7158:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7159:                 if (@curr > 0) {
                   7160:                     my @options = qw(approval validate autolimit);
                   7161:                     my $optregex = join('|',@options);
                   7162:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7163:                         $can_create = 1;
                   7164:                     }
                   7165:                 }
                   7166:             }
                   7167:         }
                   7168:         if ($can_create) {
                   7169:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7170:                 unless (&allowed('ccc',$udom)) {
                   7171:                     return 'refused'; 
                   7172:                 }
1.1017    raeburn  7173:             }
                   7174:         } else {
                   7175:             return 'refused';
                   7176:         }
1.1028    raeburn  7177:     } elsif (!&allowed('ccc',$udom)) {
                   7178:         return 'refused';
1.84      www      7179:     }
1.1011    raeburn  7180: # --------------------------------------------------------------- Get Unique ID
                   7181:     my $uname;
                   7182:     if ($cnum =~ /^$match_courseid$/) {
                   7183:         my $chome=&homeserver($cnum,$udom,'true');
                   7184:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7185:             $uname = $cnum;
                   7186:         } else {
1.1038    raeburn  7187:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7188:         }
                   7189:     } else {
1.1038    raeburn  7190:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7191:     }
                   7192:     return $uname if ($uname =~ /^error/);
                   7193: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7194:     if (!defined($course_server)) {
                   7195:         if (defined(&domain($udom,'primary'))) {
                   7196:             $course_server = &domain($udom,'primary');
                   7197:         } else {
                   7198:             $course_server = $env{'user.home'}; 
                   7199:         }
                   7200:     }
                   7201:     my %host_servers =
                   7202:         &Apache::lonnet::get_servers($udom,'library');
                   7203:     unless ($host_servers{$course_server}) {
                   7204:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7205:     }
1.84      www      7206: # ------------------------------------------------------------- Make the course
                   7207:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7208:                       $course_server);
1.84      www      7209:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7210:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7211:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7212: 	return 'error: no such course';
                   7213:     }
1.271     www      7214: # ----------------------------------------------------------------- Course made
1.516     raeburn  7215: # log existence
1.1029    raeburn  7216:     my $now = time;
1.918     raeburn  7217:     my $newcourse = {
                   7218:                     $udom.'_'.$uname => {
1.921     raeburn  7219:                                      description => $description,
                   7220:                                      inst_code   => $inst_code,
                   7221:                                      owner       => $course_owner,
                   7222:                                      type        => $crstype,
1.1029    raeburn  7223:                                      creator     => $env{'user.name'}.':'.
                   7224:                                                     $env{'user.domain'},
                   7225:                                      created     => $now,
                   7226:                                      context     => $context,
1.918     raeburn  7227:                                                 },
                   7228:                     };
1.921     raeburn  7229:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7230: # set toplevel url
1.271     www      7231:     my $topurl=$url;
                   7232:     unless ($nonstandard) {
                   7233: # ------------------------------------------ For standard courses, make top url
                   7234:         my $mapurl=&clutter($url);
1.278     www      7235:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7236:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7237: <map>
                   7238: <resource id="1" type="start"></resource>
                   7239: <resource id="2" src="$mapurl"></resource>
                   7240: <resource id="3" type="finish"></resource>
                   7241: <link index="1" from="1" to="2"></link>
                   7242: <link index="2" from="2" to="3"></link>
                   7243: </map>
                   7244: ENDINITMAP
                   7245:         $topurl=&declutter(
1.638     albertel 7246:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7247:                           );
                   7248:     }
                   7249: # ----------------------------------------------------------- Write preferences
1.84      www      7250:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7251:                      ('description'              => $description,
                   7252:                       'url'                      => $topurl,
                   7253:                       'internal.creator'         => $env{'user.name'}.':'.
                   7254:                                                     $env{'user.domain'},
                   7255:                       'internal.created'         => $now,
                   7256:                       'internal.creationcontext' => $context)
                   7257:                     );
1.84      www      7258:     return '/'.$udom.'/'.$uname;
                   7259: }
                   7260: 
1.1011    raeburn  7261: # ------------------------------------------------------------------- Create ID
                   7262: sub generate_coursenum {
1.1038    raeburn  7263:     my ($udom,$crstype) = @_;
1.1011    raeburn  7264:     my $domdesc = &domain($udom);
                   7265:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7266:     my $first;
                   7267:     if ($crstype eq 'Community') {
                   7268:         $first = '0';
                   7269:     } else {
                   7270:         $first = int(1+rand(9)); 
                   7271:     } 
                   7272:     my $uname=$first.
1.1011    raeburn  7273:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7274:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7275:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7276: # ----------------------------------------------- Make sure that does not exist
                   7277:     my $uhome=&homeserver($uname,$udom,'true');
                   7278:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7279:         if ($crstype eq 'Community') {
                   7280:             $first = '0';
                   7281:         } else {
                   7282:             $first = int(1+rand(9));
                   7283:         }
                   7284:         $uname=$first.
1.1011    raeburn  7285:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7286:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7287:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7288:         $uhome=&homeserver($uname,$udom,'true');
                   7289:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7290:             return 'error: unable to generate unique course-ID';
                   7291:         }
                   7292:     }
                   7293:     return $uname;
                   7294: }
                   7295: 
1.813     albertel 7296: sub is_course {
                   7297:     my ($cdom,$cnum) = @_;
                   7298:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7299: 				undef,'.');
1.813     albertel 7300:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7301:         return 1;
                   7302:     }
                   7303:     return 0;
                   7304: }
                   7305: 
1.1015    raeburn  7306: sub store_userdata {
                   7307:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7308:     my $result;
1.1016    raeburn  7309:     if ($datakey ne '') {
1.1013    raeburn  7310:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7311:             if ($udom eq '' || $uname eq '') {
                   7312:                 $udom = $env{'user.domain'};
                   7313:                 $uname = $env{'user.name'};
                   7314:             }
                   7315:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7316:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7317:                 $result = 'error: no_host';
                   7318:             } else {
                   7319:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7320:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7321: 
                   7322:                 my $namevalue='';
                   7323:                 foreach my $key (keys(%{$storehash})) {
                   7324:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7325:                 }
                   7326:                 $namevalue=~s/\&$//;
1.1105    raeburn  7327:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7328:                                   $namevalue,$uhome);
1.1013    raeburn  7329:             }
                   7330:         } else {
                   7331:             $result = 'error: data to store was not a hash reference'; 
                   7332:         }
                   7333:     } else {
                   7334:         $result= 'error: invalid requestkey'; 
                   7335:     }
                   7336:     return $result;
                   7337: }
                   7338: 
1.21      www      7339: # ---------------------------------------------------------- Assign Custom Role
                   7340: 
                   7341: sub assigncustomrole {
1.957     raeburn  7342:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7343:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7344:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7345: }
                   7346: 
                   7347: # ----------------------------------------------------------------- Revoke Role
                   7348: 
                   7349: sub revokerole {
1.957     raeburn  7350:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7351:     my $now=time;
1.965     raeburn  7352:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7353: }
                   7354: 
                   7355: # ---------------------------------------------------------- Revoke Custom Role
                   7356: 
                   7357: sub revokecustomrole {
1.957     raeburn  7358:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7359:     my $now=time;
1.357     www      7360:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7361:            $deleteflag,$selfenroll,$context);
1.17      www      7362: }
                   7363: 
1.533     banghart 7364: # ------------------------------------------------------------ Disk usage
1.535     albertel 7365: sub diskusage {
1.955     raeburn  7366:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7367:     $directorypath =~ s/\/$//;
                   7368:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7369:                        .&escape($getpropath).':'.&escape($uname).':'
                   7370:                        .&escape($udom),homeserver($uname,$udom));
                   7371:     if ($listing eq 'unknown_cmd') {
                   7372:         if ($getpropath) {
                   7373:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7374:         }
                   7375:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7376:     }
1.514     albertel 7377:     return $listing;
1.512     banghart 7378: }
                   7379: 
1.566     banghart 7380: sub is_locked {
1.1096    raeburn  7381:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7382:     my @check;
                   7383:     my $is_locked;
1.1093    raeburn  7384:     push (@check,$file_name);
1.613     albertel 7385:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7386: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7387:     my ($tmp)=keys(%locked);
                   7388:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7389:     
1.566     banghart 7390:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7391:         $is_locked = 'false';
                   7392:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7393:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7394:                $is_locked = 'true';
1.1096    raeburn  7395:                if (ref($which) eq 'ARRAY') {
                   7396:                    push(@{$which},$entry);
                   7397:                } else {
                   7398:                    last;
                   7399:                }
1.745     raeburn  7400:            }
                   7401:        }
1.566     banghart 7402:     } else {
                   7403:         $is_locked = 'false';
                   7404:     }
1.1093    raeburn  7405:     return $is_locked;
1.566     banghart 7406: }
                   7407: 
1.759     albertel 7408: sub declutter_portfile {
                   7409:     my ($file) = @_;
1.833     albertel 7410:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7411:     return $file;
                   7412: }
                   7413: 
1.559     banghart 7414: # ------------------------------------------------------------- Mark as Read Only
                   7415: 
                   7416: sub mark_as_readonly {
                   7417:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7418:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7419:     my ($tmp)=keys(%current_permissions);
                   7420:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7421:     foreach my $file (@{$files}) {
1.759     albertel 7422: 	$file = &declutter_portfile($file);
1.561     banghart 7423:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7424:     }
1.613     albertel 7425:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7426:     return;
                   7427: }
                   7428: 
1.572     banghart 7429: # ------------------------------------------------------------Save Selected Files
                   7430: 
                   7431: sub save_selected_files {
                   7432:     my ($user, $path, @files) = @_;
                   7433:     my $filename = $user."savedfiles";
1.573     banghart 7434:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7435:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7436:     foreach my $file (@files) {
1.620     albertel 7437:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7438:     }
                   7439:     foreach my $file (@other_files) {
1.574     banghart 7440:         print (OUT $file."\n");
1.572     banghart 7441:     }
1.574     banghart 7442:     close (OUT);
1.572     banghart 7443:     return 'ok';
                   7444: }
                   7445: 
1.574     banghart 7446: sub clear_selected_files {
                   7447:     my ($user) = @_;
                   7448:     my $filename = $user."savedfiles";
                   7449:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7450:     print (OUT undef);
                   7451:     close (OUT);
                   7452:     return ("ok");    
                   7453: }
                   7454: 
1.572     banghart 7455: sub files_in_path {
                   7456:     my ($user, $path) = @_;
                   7457:     my $filename = $user."savedfiles";
                   7458:     my %return_files;
1.574     banghart 7459:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7460:     while (my $line_in = <IN>) {
1.574     banghart 7461:         chomp ($line_in);
                   7462:         my @paths_and_file = split (m!/!, $line_in);
                   7463:         my $file_part = pop (@paths_and_file);
                   7464:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7465:         $path_part.='/';
                   7466:         my $path_and_file = $path_part.$file_part;
                   7467:         if ($path_part eq $path) {
                   7468:             $return_files{$file_part}= 'selected';
                   7469:         }
                   7470:     }
1.574     banghart 7471:     close (IN);
                   7472:     return (\%return_files);
1.572     banghart 7473: }
                   7474: 
                   7475: # called in portfolio select mode, to show files selected NOT in current directory
                   7476: sub files_not_in_path {
                   7477:     my ($user, $path) = @_;
                   7478:     my $filename = $user."savedfiles";
                   7479:     my @return_files;
                   7480:     my $path_part;
1.800     albertel 7481:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7482:     while (my $line = <IN>) {
1.572     banghart 7483:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7484:         my @paths_and_file = split(m|/|, $line);
                   7485:         my $file_part = pop(@paths_and_file);
                   7486:         chomp($file_part);
                   7487:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7488:         $path_part .= '/';
                   7489:         my $path_and_file = $path_part.$file_part;
                   7490:         if ($path_part ne $path) {
1.800     albertel 7491:             push(@return_files, ($path_and_file));
1.572     banghart 7492:         }
                   7493:     }
1.800     albertel 7494:     close(OUT);
1.574     banghart 7495:     return (@return_files);
1.572     banghart 7496: }
                   7497: 
1.745     raeburn  7498: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7499: 
1.745     raeburn  7500: sub get_portfile_permissions {
                   7501:     my ($domain,$user) = @_;
1.613     albertel 7502:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7503:     my ($tmp)=keys(%current_permissions);
                   7504:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7505:     return \%current_permissions;
                   7506: }
                   7507: 
                   7508: #---------------------------------------------Get portfolio file access controls
                   7509: 
1.749     raeburn  7510: sub get_access_controls {
1.745     raeburn  7511:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7512:     my %access;
                   7513:     my $real_file = $file;
                   7514:     $file =~ s/\.meta$//;
1.745     raeburn  7515:     if (defined($file)) {
1.749     raeburn  7516:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7517:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7518:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7519:             }
                   7520:         }
1.745     raeburn  7521:     } else {
1.749     raeburn  7522:         foreach my $key (keys(%{$current_permissions})) {
                   7523:             if ($key =~ /\0accesscontrol$/) {
                   7524:                 if (defined($group)) {
                   7525:                     if ($key !~ m-^\Q$group\E/-) {
                   7526:                         next;
                   7527:                     }
                   7528:                 }
                   7529:                 my ($fullpath) = split(/\0/,$key);
                   7530:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7531:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7532:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7533:                     }
                   7534:                 }
                   7535:             }
                   7536:         }
                   7537:     }
                   7538:     return %access;
                   7539: }
                   7540: 
                   7541: sub modify_access_controls {
                   7542:     my ($file_name,$changes,$domain,$user)=@_;
                   7543:     my ($outcome,$deloutcome);
                   7544:     my %store_permissions;
                   7545:     my %new_values;
                   7546:     my %new_control;
                   7547:     my %translation;
                   7548:     my @deletions = ();
                   7549:     my $now = time;
                   7550:     if (exists($$changes{'activate'})) {
                   7551:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7552:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7553:             my $numnew = scalar(@newitems);
                   7554:             for (my $i=0; $i<$numnew; $i++) {
                   7555:                 my $newkey = $newitems[$i];
                   7556:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7557:                 if ($newkey =~ /^\d+:/) { 
                   7558:                     $newkey =~ s/^(\d+)/$newid/;
                   7559:                     $translation{$1} = $newid;
                   7560:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7561:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7562:                     $translation{$1} = $newid;
                   7563:                 }
1.749     raeburn  7564:                 $new_values{$file_name."\0".$newkey} = 
                   7565:                                           $$changes{'activate'}{$newitems[$i]};
                   7566:                 $new_control{$newkey} = $now;
                   7567:             }
                   7568:         }
                   7569:     }
                   7570:     my %todelete;
                   7571:     my %changed_items;
                   7572:     foreach my $action ('delete','update') {
                   7573:         if (exists($$changes{$action})) {
                   7574:             if (ref($$changes{$action}) eq 'HASH') {
                   7575:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7576:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7577:                     if ($action eq 'delete') { 
                   7578:                         $todelete{$itemnum} = 1;
                   7579:                     } else {
                   7580:                         $changed_items{$itemnum} = $key;
                   7581:                     }
                   7582:                 }
1.745     raeburn  7583:             }
                   7584:         }
1.749     raeburn  7585:     }
                   7586:     # get lock on access controls for file.
                   7587:     my $lockhash = {
                   7588:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7589:                                                        ':'.$env{'user.domain'},
                   7590:                    }; 
                   7591:     my $tries = 0;
                   7592:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7593:    
                   7594:     while (($gotlock ne 'ok') && $tries <3) {
                   7595:         $tries ++;
                   7596:         sleep 1;
                   7597:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7598:     }
                   7599:     if ($gotlock eq 'ok') {
                   7600:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7601:         my ($tmp)=keys(%curr_permissions);
                   7602:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7603:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7604:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7605:             if (ref($curr_controls) eq 'HASH') {
                   7606:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7607:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7608:                     if (defined($todelete{$itemnum})) {
                   7609:                         push(@deletions,$file_name."\0".$control_item);
                   7610:                     } else {
                   7611:                         if (defined($changed_items{$itemnum})) {
                   7612:                             $new_control{$changed_items{$itemnum}} = $now;
                   7613:                             push(@deletions,$file_name."\0".$control_item);
                   7614:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7615:                         } else {
                   7616:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7617:                         }
                   7618:                     }
1.745     raeburn  7619:                 }
                   7620:             }
                   7621:         }
1.970     raeburn  7622:         my ($group);
                   7623:         if (&is_course($domain,$user)) {
                   7624:             ($group,my $file) = split(/\//,$file_name,2);
                   7625:         }
1.749     raeburn  7626:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7627:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7628:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7629:         #  remove lock
                   7630:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7631:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7632:         my $sqlresult =
1.970     raeburn  7633:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7634:                                     $group);
1.749     raeburn  7635:     } else {
                   7636:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7637:     }
1.749     raeburn  7638:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7639: }
                   7640: 
1.827     raeburn  7641: sub make_public_indefinitely {
                   7642:     my ($requrl) = @_;
                   7643:     my $now = time;
                   7644:     my $action = 'activate';
                   7645:     my $aclnum = 0;
                   7646:     if (&is_portfolio_url($requrl)) {
                   7647:         my (undef,$udom,$unum,$file_name,$group) =
                   7648:             &parse_portfolio_url($requrl);
                   7649:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7650:         my %access_controls = &get_access_controls($current_perms,
                   7651:                                                    $group,$file_name);
                   7652:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7653:             my ($num,$scope,$end,$start) = 
                   7654:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7655:             if ($scope eq 'public') {
                   7656:                 if ($start <= $now && $end == 0) {
                   7657:                     $action = 'none';
                   7658:                 } else {
                   7659:                     $action = 'update';
                   7660:                     $aclnum = $num;
                   7661:                 }
                   7662:                 last;
                   7663:             }
                   7664:         }
                   7665:         if ($action eq 'none') {
                   7666:              return 'ok';
                   7667:         } else {
                   7668:             my %changes;
                   7669:             my $newend = 0;
                   7670:             my $newstart = $now;
                   7671:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7672:             $changes{$action}{$newkey} = {
                   7673:                 type => 'public',
                   7674:                 time => {
                   7675:                     start => $newstart,
                   7676:                     end   => $newend,
                   7677:                 },
                   7678:             };
                   7679:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7680:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7681:             return $outcome;
                   7682:         }
                   7683:     } else {
                   7684:         return 'invalid';
                   7685:     }
                   7686: }
                   7687: 
1.745     raeburn  7688: #------------------------------------------------------Get Marked as Read Only
                   7689: 
                   7690: sub get_marked_as_readonly {
                   7691:     my ($domain,$user,$what,$group) = @_;
                   7692:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7693:     my @readonly_files;
1.629     banghart 7694:     my $cmp1=$what;
                   7695:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7696:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7697:         if (defined($group)) {
                   7698:             if ($file_name !~ m-^\Q$group\E/-) {
                   7699:                 next;
                   7700:             }
                   7701:         }
1.561     banghart 7702:         if (ref($value) eq "ARRAY"){
                   7703:             foreach my $stored_what (@{$value}) {
1.629     banghart 7704:                 my $cmp2=$stored_what;
1.759     albertel 7705:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7706:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7707:                 }
1.629     banghart 7708:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7709:                     push(@readonly_files, $file_name);
1.745     raeburn  7710:                     last;
1.563     banghart 7711:                 } elsif (!defined($what)) {
                   7712:                     push(@readonly_files, $file_name);
1.745     raeburn  7713:                     last;
1.561     banghart 7714:                 }
                   7715:             }
1.745     raeburn  7716:         }
1.561     banghart 7717:     }
                   7718:     return @readonly_files;
                   7719: }
1.577     banghart 7720: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7721: 
1.577     banghart 7722: sub get_marked_as_readonly_hash {
1.745     raeburn  7723:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7724:     my %readonly_files;
1.745     raeburn  7725:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7726:         if (defined($group)) {
                   7727:             if ($file_name !~ m-^\Q$group\E/-) {
                   7728:                 next;
                   7729:             }
                   7730:         }
1.577     banghart 7731:         if (ref($value) eq "ARRAY"){
                   7732:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7733:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7734:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7735:                         if ($lock_descriptor eq 'graded') {
                   7736:                             $readonly_files{$file_name} = 'graded';
                   7737:                         } elsif ($lock_descriptor eq 'handback') {
                   7738:                             $readonly_files{$file_name} = 'handback';
                   7739:                         } else {
                   7740:                             if (!exists($readonly_files{$file_name})) {
                   7741:                                 $readonly_files{$file_name} = 'locked';
                   7742:                             }
                   7743:                         }
1.745     raeburn  7744:                     }
1.750     banghart 7745:                 } 
1.577     banghart 7746:             }
                   7747:         } 
                   7748:     }
                   7749:     return %readonly_files;
                   7750: }
1.559     banghart 7751: # ------------------------------------------------------------ Unmark as Read Only
                   7752: 
                   7753: sub unmark_as_readonly {
1.629     banghart 7754:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7755:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7756:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7757:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7758:     my $symb_crs = $what;
                   7759:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7760:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7761:     my ($tmp)=keys(%current_permissions);
                   7762:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7763:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7764:     foreach my $file (@readonly_files) {
1.759     albertel 7765: 	my $clean_file = &declutter_portfile($file);
                   7766: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7767: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7768:         my @new_locks;
                   7769:         my @del_keys;
                   7770:         if (ref($current_locks) eq "ARRAY"){
                   7771:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7772:                 my $compare=$locker;
1.749     raeburn  7773:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7774:                     $compare=join('',@{$locker});
1.746     raeburn  7775:                     if ($compare ne $symb_crs) {
                   7776:                         push(@new_locks, $locker);
                   7777:                     }
1.563     banghart 7778:                 }
                   7779:             }
1.650     albertel 7780:             if (scalar(@new_locks) > 0) {
1.563     banghart 7781:                 $current_permissions{$file} = \@new_locks;
                   7782:             } else {
                   7783:                 push(@del_keys, $file);
1.613     albertel 7784:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7785:                 delete($current_permissions{$file});
1.563     banghart 7786:             }
                   7787:         }
1.561     banghart 7788:     }
1.613     albertel 7789:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7790:     return;
                   7791: }
1.512     banghart 7792: 
1.17      www      7793: # ------------------------------------------------------------ Directory lister
                   7794: 
                   7795: sub dirlist {
1.955     raeburn  7796:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7797:     $uri=~s/^\///;
                   7798:     $uri=~s/\/$//;
1.253     stredwic 7799:     my ($udom, $uname);
1.955     raeburn  7800:     if ($getuserdir) {
1.253     stredwic 7801:         $udom = $userdomain;
                   7802:         $uname = $username;
1.955     raeburn  7803:     } else {
                   7804:         (undef,$udom,$uname)=split(/\//,$uri);
                   7805:         if(defined($userdomain)) {
                   7806:             $udom = $userdomain;
                   7807:         }
                   7808:         if(defined($username)) {
                   7809:             $uname = $username;
                   7810:         }
1.253     stredwic 7811:     }
1.955     raeburn  7812:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7813: 
1.955     raeburn  7814:     $dirRoot = $perlvar{'lonDocRoot'};
                   7815:     if (defined($getpropath)) {
                   7816:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7817:         $dirRoot =~ s/\/$//;
1.955     raeburn  7818:     } elsif (defined($getuserdir)) {
                   7819:         my $subdir=$uname.'__';
                   7820:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7821:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7822:                    ."/$udom/$subdir/$uname";
                   7823:     } elsif (defined($alternateRoot)) {
                   7824:         $dirRoot = $alternateRoot;
1.751     banghart 7825:     }
1.253     stredwic 7826: 
                   7827:     if($udom) {
                   7828:         if($uname) {
1.955     raeburn  7829:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7830:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7831:                               .':'.&escape($uname).':'.&escape($udom),
                   7832:                               &homeserver($uname,$udom));
                   7833:             if ($listing eq 'unknown_cmd') {
                   7834:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7835:                                   &homeserver($uname,$udom));
                   7836:             } else {
                   7837:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7838:             }
1.605     matthew  7839:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7840:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7841: 				  &homeserver($uname,$udom));
1.605     matthew  7842:                 @listing_results = split(/:/,$listing);
                   7843:             } else {
                   7844:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7845:             }
                   7846:             return @listing_results;
1.955     raeburn  7847:         } elsif(!$alternateRoot) {
1.800     albertel 7848:             my %allusers;
1.841     albertel 7849: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7850:  	    foreach my $tryserver (keys(%servers)) {
                   7851:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7852:                                   &escape($udom),$tryserver);
                   7853:                 if ($listing eq 'unknown_cmd') {
                   7854: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7855: 				      $udom, $tryserver);
                   7856:                 } else {
                   7857:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7858:                 }
1.841     albertel 7859: 		if ($listing eq 'unknown_cmd') {
                   7860: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7861: 				      $udom, $tryserver);
                   7862: 		    @listing_results = split(/:/,$listing);
                   7863: 		} else {
                   7864: 		    @listing_results =
                   7865: 			map { &unescape($_); } split(/:/,$listing);
                   7866: 		}
                   7867: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7868: 		    $listing_results[0] ne 'empty'       &&
                   7869: 		    $listing_results[0] ne 'con_lost') {
                   7870: 		    foreach my $line (@listing_results) {
                   7871: 			my ($entry) = split(/&/,$line,2);
                   7872: 			$allusers{$entry} = 1;
                   7873: 		    }
                   7874: 		}
1.253     stredwic 7875:             }
                   7876:             my $alluserstr='';
1.800     albertel 7877:             foreach my $user (sort(keys(%allusers))) {
                   7878:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7879:             }
                   7880:             $alluserstr=~s/:$//;
                   7881:             return split(/:/,$alluserstr);
                   7882:         } else {
1.800     albertel 7883:             return ('missing user name');
1.253     stredwic 7884:         }
1.955     raeburn  7885:     } elsif(!defined($getpropath)) {
1.841     albertel 7886:         my @all_domains = sort(&all_domains());
1.955     raeburn  7887:         foreach my $domain (@all_domains) {
                   7888:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7889:         }
                   7890:         return @all_domains;
                   7891:     } else {
1.800     albertel 7892:         return ('missing domain');
1.275     stredwic 7893:     }
                   7894: }
                   7895: 
                   7896: # --------------------------------------------- GetFileTimestamp
                   7897: # This function utilizes dirlist and returns the date stamp for
                   7898: # when it was last modified.  It will also return an error of -1
                   7899: # if an error occurs
                   7900: 
                   7901: sub GetFileTimestamp {
1.955     raeburn  7902:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7903:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7904:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7905:     my ($fileStat) = 
                   7906:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7907:                                  undef,$getuserdir);
1.275     stredwic 7908:     my @stats = split('&', $fileStat);
                   7909:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7910:         # @stats contains first the filename, then the stat output
                   7911:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7912:     } else {
                   7913:         return -1;
1.253     stredwic 7914:     }
1.26      www      7915: }
                   7916: 
1.712     albertel 7917: sub stat_file {
                   7918:     my ($uri) = @_;
1.787     albertel 7919:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7920: 
1.955     raeburn  7921:     my ($udom,$uname,$file);
1.712     albertel 7922:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7923: 	($udom,$uname,$file) =
1.811     albertel 7924: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7925: 	$file = 'userfiles/'.$file;
                   7926:     }
                   7927:     if ($uri =~ m-^/res/-) {
                   7928: 	($udom,$uname) = 
1.807     albertel 7929: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7930: 	$file = $uri;
                   7931:     }
                   7932: 
                   7933:     if (!$udom || !$uname || !$file) {
                   7934: 	# unable to handle the uri
                   7935: 	return ();
                   7936:     }
1.956     raeburn  7937:     my $getpropath;
                   7938:     if ($file =~ /^userfiles\//) {
                   7939:         $getpropath = 1;
                   7940:     }
1.955     raeburn  7941:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7942:     my @stats = split('&', $result);
1.721     banghart 7943:     
1.712     albertel 7944:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7945: 	shift(@stats); #filename is first
                   7946: 	return @stats;
                   7947:     }
                   7948:     return ();
                   7949: }
                   7950: 
1.26      www      7951: # -------------------------------------------------------- Value of a Condition
                   7952: 
1.713     albertel 7953: # gets the value of a specific preevaluated condition
                   7954: #    stored in the string  $env{user.state.<cid>}
                   7955: # or looks up a condition reference in the bighash and if if hasn't
                   7956: # already been evaluated recurses into docondval to get the value of
                   7957: # the condition, then memoizing it to 
                   7958: #   $env{user.state.<cid>.<condition>}
1.40      www      7959: sub directcondval {
                   7960:     my $number=shift;
1.620     albertel 7961:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7962: 	&Apache::lonuserstate::evalstate();
                   7963:     }
1.713     albertel 7964:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7965: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7966:     } elsif ($number =~ /^_/) {
                   7967: 	my $sub_condition;
                   7968: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7969: 		&GDBM_READER(),0640)) {
                   7970: 	    $sub_condition=$bighash{'conditions'.$number};
                   7971: 	    untie(%bighash);
                   7972: 	}
                   7973: 	my $value = &docondval($sub_condition);
1.949     raeburn  7974: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7975: 	return $value;
                   7976:     }
1.620     albertel 7977:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7978:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7979:     } else {
                   7980:        return 2;
                   7981:     }
                   7982: }
                   7983: 
1.713     albertel 7984: # get the collection of conditions for this resource
1.26      www      7985: sub condval {
                   7986:     my $condidx=shift;
1.54      www      7987:     my $allpathcond='';
1.713     albertel 7988:     foreach my $cond (split(/\|/,$condidx)) {
                   7989: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7990: 	    $allpathcond.=
                   7991: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7992: 	}
1.191     harris41 7993:     }
1.54      www      7994:     $allpathcond=~s/\|$//;
1.713     albertel 7995:     return &docondval($allpathcond);
                   7996: }
                   7997: 
                   7998: #evaluates an expression of conditions
                   7999: sub docondval {
                   8000:     my ($allpathcond) = @_;
                   8001:     my $result=0;
                   8002:     if ($env{'request.course.id'}
                   8003: 	&& defined($allpathcond)) {
                   8004: 	my $operand='|';
                   8005: 	my @stack;
                   8006: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8007: 	    if ($chunk eq '(') {
                   8008: 		push @stack,($operand,$result);
                   8009: 	    } elsif ($chunk eq ')') {
                   8010: 		my $before=pop @stack;
                   8011: 		if (pop @stack eq '&') {
                   8012: 		    $result=$result>$before?$before:$result;
                   8013: 		} else {
                   8014: 		    $result=$result>$before?$result:$before;
                   8015: 		}
                   8016: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8017: 		$operand=$chunk;
                   8018: 	    } else {
                   8019: 		my $new=directcondval($chunk);
                   8020: 		if ($operand eq '&') {
                   8021: 		    $result=$result>$new?$new:$result;
                   8022: 		} else {
                   8023: 		    $result=$result>$new?$result:$new;
                   8024: 		}
                   8025: 	    }
                   8026: 	}
1.26      www      8027:     }
                   8028:     return $result;
1.421     albertel 8029: }
                   8030: 
                   8031: # ---------------------------------------------------- Devalidate courseresdata
                   8032: 
                   8033: sub devalidatecourseresdata {
                   8034:     my ($coursenum,$coursedomain)=@_;
                   8035:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8036:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8037: }
                   8038: 
1.763     www      8039: 
1.200     www      8040: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8041: #
                   8042: #  Parameters:
                   8043: #      $coursenum    - Number of the course.
                   8044: #      $coursedomain - Domain at which the course was created.
                   8045: #  Returns:
                   8046: #     A hash of the course parameters along (I think) with timestamps
                   8047: #     and version info.
1.877     foxr     8048: 
1.624     albertel 8049: sub get_courseresdata {
                   8050:     my ($coursenum,$coursedomain)=@_;
1.200     www      8051:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8052:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8053:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8054:     my %dumpreply;
1.417     albertel 8055:     unless (defined($cached)) {
1.624     albertel 8056: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8057: 	$result=\%dumpreply;
1.251     albertel 8058: 	my ($tmp) = keys(%dumpreply);
                   8059: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8060: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8061: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8062: 	    return $tmp;
1.416     albertel 8063: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8064: 	    $result=undef;
1.599     albertel 8065: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8066: 	}
                   8067:     }
1.624     albertel 8068:     return $result;
                   8069: }
                   8070: 
1.633     albertel 8071: sub devalidateuserresdata {
                   8072:     my ($uname,$udom)=@_;
                   8073:     my $hashid="$udom:$uname";
                   8074:     &devalidate_cache_new('userres',$hashid);
                   8075: }
                   8076: 
1.624     albertel 8077: sub get_userresdata {
                   8078:     my ($uname,$udom)=@_;
                   8079:     #most student don\'t have any data set, check if there is some data
                   8080:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8081: 
                   8082:     my $hashid="$udom:$uname";
                   8083:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8084:     if (!defined($cached)) {
                   8085: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8086: 	$result=\%resourcedata;
                   8087: 	&do_cache_new('userres',$hashid,$result,600);
                   8088:     }
                   8089:     my ($tmp)=keys(%$result);
                   8090:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8091: 	return $result;
                   8092:     }
                   8093:     #error 2 occurs when the .db doesn't exist
                   8094:     if ($tmp!~/error: 2 /) {
1.672     albertel 8095: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8096: 		 " Trying to get resource data for ".
                   8097: 		 $uname." at ".$udom.": ".
                   8098: 		 $tmp."</font>");
                   8099:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8100: 	#&EXT_cache_set($udom,$uname);
                   8101: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8102: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8103:     }
                   8104:     return $tmp;
                   8105: }
1.879     foxr     8106: #----------------------------------------------- resdata - return resource data
                   8107: #  Purpose:
                   8108: #    Return resource data for either users or for a course.
                   8109: #  Parameters:
                   8110: #     $name      - Course/user name.
                   8111: #     $domain    - Name of the domain the user/course is registered on.
                   8112: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8113: #     @which     - Array of names of resources desired.
                   8114: #  Returns:
                   8115: #     The value of the first reasource in @which that is found in the
                   8116: #     resource hash.
                   8117: #  Exceptional Conditions:
                   8118: #     If the $type passed in is not valid (not the string 'course' or 
                   8119: #     'user', an undefined  reference is returned.
                   8120: #     If none of the resources are found, an undef is returned
1.624     albertel 8121: sub resdata {
                   8122:     my ($name,$domain,$type,@which)=@_;
                   8123:     my $result;
                   8124:     if ($type eq 'course') {
                   8125: 	$result=&get_courseresdata($name,$domain);
                   8126:     } elsif ($type eq 'user') {
                   8127: 	$result=&get_userresdata($name,$domain);
                   8128:     }
                   8129:     if (!ref($result)) { return $result; }    
1.251     albertel 8130:     foreach my $item (@which) {
1.927     albertel 8131: 	if (defined($result->{$item->[0]})) {
                   8132: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8133: 	}
1.250     albertel 8134:     }
1.291     albertel 8135:     return undef;
1.200     www      8136: }
                   8137: 
1.379     matthew  8138: #
                   8139: # EXT resource caching routines
                   8140: #
                   8141: 
                   8142: sub clear_EXT_cache_status {
1.383     albertel 8143:     &delenv('cache.EXT.');
1.379     matthew  8144: }
                   8145: 
                   8146: sub EXT_cache_status {
                   8147:     my ($target_domain,$target_user) = @_;
1.383     albertel 8148:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8149:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8150:         # We know already the user has no data
                   8151:         return 1;
                   8152:     } else {
                   8153:         return 0;
                   8154:     }
                   8155: }
                   8156: 
                   8157: sub EXT_cache_set {
                   8158:     my ($target_domain,$target_user) = @_;
1.383     albertel 8159:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8160:     #&appenv({$cachename => time});
1.379     matthew  8161: }
                   8162: 
1.28      www      8163: # --------------------------------------------------------- Value of a Variable
1.58      www      8164: sub EXT {
1.715     albertel 8165: 
1.395     albertel 8166:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8167:     unless ($varname) { return ''; }
1.218     albertel 8168:     #get real user name/domain, courseid and symb
                   8169:     my $courseid;
1.359     albertel 8170:     my $publicuser;
1.427     www      8171:     if ($symbparm) {
                   8172: 	$symbparm=&get_symb_from_alias($symbparm);
                   8173:     }
1.218     albertel 8174:     if (!($uname && $udom)) {
1.790     albertel 8175:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8176:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8177:     } else {
1.620     albertel 8178: 	$courseid=$env{'request.course.id'};
1.218     albertel 8179:     }
1.48      www      8180:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8181:     my $rest;
1.320     albertel 8182:     if (defined($therest[0])) {
1.48      www      8183:        $rest=join('.',@therest);
                   8184:     } else {
                   8185:        $rest='';
                   8186:     }
1.320     albertel 8187: 
1.57      www      8188:     my $qualifierrest=$qualifier;
                   8189:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8190:     my $spacequalifierrest=$space;
                   8191:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8192:     if ($realm eq 'user') {
1.48      www      8193: # --------------------------------------------------------------- user.resource
                   8194: 	if ($space eq 'resource') {
1.651     albertel 8195: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8196: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8197: 		 &&
1.744     albertel 8198: 		 ($symbparm eq &symbread()) ) {	
                   8199: 		# if we are in the middle of processing the resource the
                   8200: 		# get the value we are planning on committing
                   8201:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8202:                     return $Apache::lonhomework::results{$qualifierrest};
                   8203:                 } else {
                   8204:                     return $Apache::lonhomework::history{$qualifierrest};
                   8205:                 }
1.335     albertel 8206: 	    } else {
1.359     albertel 8207: 		my %restored;
1.620     albertel 8208: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8209: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8210: 		} else {
                   8211: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8212: 		}
1.335     albertel 8213: 		return $restored{$qualifierrest};
                   8214: 	    }
1.48      www      8215: # ----------------------------------------------------------------- user.access
                   8216:         } elsif ($space eq 'access') {
1.218     albertel 8217: 	    # FIXME - not supporting calls for a specific user
1.48      www      8218:             return &allowed($qualifier,$rest);
                   8219: # ------------------------------------------ user.preferences, user.environment
                   8220:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8221: 	    if (($uname eq $env{'user.name'}) &&
                   8222: 		($udom eq $env{'user.domain'})) {
                   8223: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8224: 	    } else {
1.359     albertel 8225: 		my %returnhash;
                   8226: 		if (!$publicuser) {
                   8227: 		    %returnhash=&userenvironment($udom,$uname,
                   8228: 						 $qualifierrest);
                   8229: 		}
1.218     albertel 8230: 		return $returnhash{$qualifierrest};
                   8231: 	    }
1.48      www      8232: # ----------------------------------------------------------------- user.course
                   8233:         } elsif ($space eq 'course') {
1.218     albertel 8234: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8235:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8236: # ------------------------------------------------------------------- user.role
                   8237:         } elsif ($space eq 'role') {
1.218     albertel 8238: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8239:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8240:             if ($qualifier eq 'value') {
                   8241: 		return $role;
                   8242:             } elsif ($qualifier eq 'extent') {
                   8243:                 return $where;
                   8244:             }
                   8245: # ----------------------------------------------------------------- user.domain
                   8246:         } elsif ($space eq 'domain') {
1.218     albertel 8247:             return $udom;
1.48      www      8248: # ------------------------------------------------------------------- user.name
                   8249:         } elsif ($space eq 'name') {
1.218     albertel 8250:             return $uname;
1.48      www      8251: # ---------------------------------------------------- Any other user namespace
1.29      www      8252:         } else {
1.359     albertel 8253: 	    my %reply;
                   8254: 	    if (!$publicuser) {
                   8255: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8256: 	    }
                   8257: 	    return $reply{$qualifierrest};
1.48      www      8258:         }
1.236     www      8259:     } elsif ($realm eq 'query') {
                   8260: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8261:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8262: 						[$spacequalifierrest]);
1.620     albertel 8263: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8264:    } elsif ($realm eq 'request') {
1.48      www      8265: # ------------------------------------------------------------- request.browser
                   8266:         if ($space eq 'browser') {
1.430     www      8267: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8268: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8269: 		    return 1;
                   8270: 		} else {
                   8271: 		    return 0;
                   8272: 		}
                   8273: 	    } else {
1.620     albertel 8274: 		return $env{'browser.'.$qualifier};
1.430     www      8275: 	    }
1.57      www      8276: # ------------------------------------------------------------ request.filename
                   8277:         } else {
1.620     albertel 8278:             return $env{'request.'.$spacequalifierrest};
1.29      www      8279:         }
1.28      www      8280:     } elsif ($realm eq 'course') {
1.48      www      8281: # ---------------------------------------------------------- course.description
1.620     albertel 8282:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8283:     } elsif ($realm eq 'resource') {
1.165     www      8284: 
1.620     albertel 8285: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8286: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8287: 	}
1.693     albertel 8288: 
                   8289: 	if ($space eq 'title') {
                   8290: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8291: 	    return &gettitle($symbparm);
                   8292: 	}
                   8293: 	
                   8294: 	if ($space eq 'map') {
                   8295: 	    my ($map) = &decode_symb($symbparm);
                   8296: 	    return &symbread($map);
                   8297: 	}
1.905     albertel 8298: 	if ($space eq 'filename') {
                   8299: 	    if ($symbparm) {
                   8300: 		return &clutter((&decode_symb($symbparm))[2]);
                   8301: 	    }
                   8302: 	    return &hreflocation('',$env{'request.filename'});
                   8303: 	}
1.693     albertel 8304: 
                   8305: 	my ($section, $group, @groups);
1.593     albertel 8306: 	my ($courselevelm,$courselevel);
1.539     albertel 8307: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8308: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8309: 
1.218     albertel 8310: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8311: 
1.60      www      8312: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8313: 	    my $symbp=$symbparm;
1.735     albertel 8314: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8315: 
                   8316: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8317: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8318: 
1.620     albertel 8319: 	    if (($env{'user.name'} eq $uname) &&
                   8320: 		($env{'user.domain'} eq $udom)) {
                   8321: 		$section=$env{'request.course.sec'};
1.733     raeburn  8322:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8323:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8324: 	    } else {
1.539     albertel 8325: 		if (! defined($usection)) {
1.551     albertel 8326: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8327: 		} else {
                   8328: 		    $section = $usection;
                   8329: 		}
1.733     raeburn  8330:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8331: 	    }
                   8332: 
                   8333: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8334: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8335: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8336: 
1.593     albertel 8337: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8338: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8339: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8340: 
1.60      www      8341: # ----------------------------------------------------------- first, check user
1.624     albertel 8342: 
                   8343: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8344: 				       ([$courselevelr,'resource'],
                   8345: 					[$courselevelm,'map'     ],
                   8346: 					[$courselevel, 'course'  ]));
1.931     albertel 8347: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8348: 
1.594     albertel 8349: # ------------------------------------------------ second, check some of course
1.684     raeburn  8350:             my $coursereply;
1.691     raeburn  8351:             if (@groups > 0) {
                   8352:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8353:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8354:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8355:             }
1.96      www      8356: 
1.684     raeburn  8357: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8358: 				  $env{'course.'.$courseid.'.domain'},
                   8359: 				  'course',
                   8360: 				  ([$seclevelr,   'resource'],
                   8361: 				   [$seclevelm,   'map'     ],
                   8362: 				   [$seclevel,    'course'  ],
                   8363: 				   [$courselevelr,'resource']));
                   8364: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8365: 
1.60      www      8366: # ------------------------------------------------------ third, check map parms
1.218     albertel 8367: 	    my %parmhash=();
                   8368: 	    my $thisparm='';
                   8369: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8370: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8371: 		    &GDBM_READER(),0640)) {
1.218     albertel 8372: 		$thisparm=$parmhash{$symbparm};
                   8373: 		untie(%parmhash);
                   8374: 	    }
1.927     albertel 8375: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8376: 	}
1.594     albertel 8377: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8378: 
1.218     albertel 8379: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8380: 	my $filename;
                   8381: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8382: 	if ($symbparm) {
1.409     www      8383: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8384: 	} else {
1.620     albertel 8385: 	    $filename=$env{'request.filename'};
1.282     albertel 8386: 	}
                   8387: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8388: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8389: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8390: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8391: 
1.927     albertel 8392: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8393: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8394: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8395: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8396: 				     $env{'course.'.$courseid.'.domain'},
                   8397: 				     'course',
1.927     albertel 8398: 				     ([$courselevelm,'map'   ],
                   8399: 				      [$courselevel, 'course']));
                   8400: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8401: 	}
1.145     www      8402: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8403: 	unless ($space eq '0') {
1.336     albertel 8404: 	    my @parts=split(/_/,$space);
                   8405: 	    my $id=pop(@parts);
                   8406: 	    my $part=join('_',@parts);
                   8407: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8408: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8409: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8410: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8411: 	}
1.395     albertel 8412: 	if ($recurse) { return undef; }
                   8413: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8414: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8415: # ---------------------------------------------------- Any other user namespace
                   8416:     } elsif ($realm eq 'environment') {
                   8417: # ----------------------------------------------------------------- environment
1.620     albertel 8418: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8419: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8420: 	} else {
1.770     albertel 8421: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8422: 		return '';
                   8423: 	    }
1.219     albertel 8424: 	    my %returnhash=&userenvironment($udom,$uname,
                   8425: 					    $spacequalifierrest);
                   8426: 	    return $returnhash{$spacequalifierrest};
                   8427: 	}
1.28      www      8428:     } elsif ($realm eq 'system') {
1.48      www      8429: # ----------------------------------------------------------------- system.time
                   8430: 	if ($space eq 'time') {
                   8431: 	    return time;
                   8432:         }
1.696     albertel 8433:     } elsif ($realm eq 'server') {
                   8434: # ----------------------------------------------------------------- system.time
                   8435: 	if ($space eq 'name') {
                   8436: 	    return $ENV{'SERVER_NAME'};
                   8437:         }
1.28      www      8438:     }
1.48      www      8439:     return '';
1.61      www      8440: }
                   8441: 
1.927     albertel 8442: sub get_reply {
                   8443:     my ($reply_value) = @_;
1.940     raeburn  8444:     if (ref($reply_value) eq 'ARRAY') {
                   8445:         if (wantarray) {
                   8446: 	    return @$reply_value;
                   8447:         }
                   8448:         return $reply_value->[0];
                   8449:     } else {
                   8450:         return $reply_value;
1.927     albertel 8451:     }
                   8452: }
                   8453: 
1.691     raeburn  8454: sub check_group_parms {
                   8455:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8456:     my @groupitems = ();
                   8457:     my $resultitem;
1.927     albertel 8458:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8459:     foreach my $group (@{$groups}) {
                   8460:         foreach my $level (@levels) {
1.927     albertel 8461:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8462:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8463:         }
                   8464:     }
                   8465:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8466:                             $env{'course.'.$courseid.'.domain'},
                   8467:                                      'course',@groupitems);
                   8468:     return $coursereply;
                   8469: }
                   8470: 
                   8471: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8472:     my ($courseid,@groups) = @_;
                   8473:     @groups = sort(@groups);
1.691     raeburn  8474:     return @groups;
                   8475: }
                   8476: 
1.395     albertel 8477: sub packages_tab_default {
                   8478:     my ($uri,$varname)=@_;
                   8479:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8480: 
                   8481:     my (@extension,@specifics,$do_default);
                   8482:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8483: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8484: 	if ($pack_type eq 'default') {
                   8485: 	    $do_default=1;
                   8486: 	} elsif ($pack_type eq 'extension') {
                   8487: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8488: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8489: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8490: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8491: 	}
                   8492:     }
                   8493:     # first look for a package that matches the requested part id
                   8494:     foreach my $package (@specifics) {
                   8495: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8496: 	next if ($pack_part ne $part);
                   8497: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8498: 	    return $packagetab{"$pack_type&$name&default"};
                   8499: 	}
                   8500:     }
                   8501:     # look for any possible matching non extension_ package
                   8502:     foreach my $package (@specifics) {
                   8503: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8504: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8505: 	    return $packagetab{"$pack_type&$name&default"};
                   8506: 	}
1.585     albertel 8507: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8508: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8509: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8510: 	}
                   8511:     }
1.738     albertel 8512:     # look for any posible extension_ match
                   8513:     foreach my $package (@extension) {
                   8514: 	my ($package,$pack_type)=@{$package};
                   8515: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8516: 	    return $packagetab{"$pack_type&$name&default"};
                   8517: 	}
                   8518: 	if (defined($packagetab{$package."&$name&default"})) {
                   8519: 	    return $packagetab{$package."&$name&default"};
                   8520: 	}
                   8521:     }
                   8522:     # look for a global default setting
                   8523:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8524: 	return $packagetab{"default&$name&default"};
                   8525:     }
1.395     albertel 8526:     return undef;
                   8527: }
                   8528: 
1.334     albertel 8529: sub add_prefix_and_part {
                   8530:     my ($prefix,$part)=@_;
                   8531:     my $keyroot;
                   8532:     if (defined($prefix) && $prefix !~ /^__/) {
                   8533: 	# prefix that has a part already
                   8534: 	$keyroot=$prefix;
                   8535:     } elsif (defined($prefix)) {
                   8536: 	# prefix that is missing a part
                   8537: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8538:     } else {
                   8539: 	# no prefix at all
                   8540: 	if (defined($part)) { $keyroot='_'.$part; }
                   8541:     }
                   8542:     return $keyroot;
                   8543: }
                   8544: 
1.71      www      8545: # ---------------------------------------------------------------- Get metadata
                   8546: 
1.599     albertel 8547: my %metaentry;
1.1070    www      8548: my %importedpartids;
1.71      www      8549: sub metadata {
1.176     www      8550:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8551:     $uri=&declutter($uri);
1.288     albertel 8552:     # if it is a non metadata possible uri return quickly
1.529     albertel 8553:     if (($uri eq '') || 
                   8554: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8555: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8556:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8557: 	return undef;
                   8558:     }
                   8559:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8560: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8561: 	return undef;
1.288     albertel 8562:     }
1.73      www      8563:     my $filename=$uri;
                   8564:     $uri=~s/\.meta$//;
1.172     www      8565: #
                   8566: # Is the metadata already cached?
1.177     www      8567: # Look at timestamp of caching
1.172     www      8568: # Everything is cached by the main uri, libraries are never directly cached
                   8569: #
1.428     albertel 8570:     if (!defined($liburi)) {
1.599     albertel 8571: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8572: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8573:     }
                   8574:     {
1.1069    www      8575: # Imported parts would go here
1.1070    www      8576:         my %importedids=();
                   8577:         my @origfileimportpartids=();
1.1069    www      8578:         my $importedparts=0;
1.172     www      8579: #
                   8580: # Is this a recursive call for a library?
                   8581: #
1.599     albertel 8582: #	if (! exists($metacache{$uri})) {
                   8583: #	    $metacache{$uri}={};
                   8584: #	}
1.924     albertel 8585: 	my $cachetime = 60*60;
1.171     www      8586:         if ($liburi) {
                   8587: 	    $liburi=&declutter($liburi);
                   8588:             $filename=$liburi;
1.401     bowersj2 8589:         } else {
1.599     albertel 8590: 	    &devalidate_cache_new('meta',$uri);
                   8591: 	    undef(%metaentry);
1.401     bowersj2 8592: 	}
1.140     www      8593:         my %metathesekeys=();
1.73      www      8594:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8595: 	my $metastring;
1.924     albertel 8596: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8597: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8598: 	    $metastring = 
1.929     albertel 8599: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8600: 					  ('grade_target' => 'meta'));
                   8601: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  8602: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8603:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8604: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8605: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8606: 	    $metastring=&getfile($file);
1.489     albertel 8607: 	}
1.208     albertel 8608:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8609:         my $token;
1.140     www      8610:         undef %metathesekeys;
1.71      www      8611:         while ($token=$parser->get_token) {
1.339     albertel 8612: 	    if ($token->[0] eq 'S') {
                   8613: 		if (defined($token->[2]->{'package'})) {
1.172     www      8614: #
                   8615: # This is a package - get package info
                   8616: #
1.339     albertel 8617: 		    my $package=$token->[2]->{'package'};
                   8618: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8619: 		    if (defined($token->[2]->{'id'})) { 
                   8620: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8621: 		    }
1.599     albertel 8622: 		    if ($metaentry{':packages'}) {
                   8623: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8624: 		    } else {
1.599     albertel 8625: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8626: 		    }
1.736     albertel 8627: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8628: 			my $part=$keyroot;
                   8629: 			$part=~s/^\_//;
1.736     albertel 8630: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8631: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8632: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8633: 			    # ignore package.tab specified default values
                   8634:                             # here &package_tab_default() will fetch those
                   8635: 			    if ($subp eq 'default') { next; }
1.736     albertel 8636: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8637: 			    my $unikey;
                   8638: 			    if ($pack =~ /_0$/) {
                   8639: 				$unikey='parameter_0_'.$name;
                   8640: 				$part=0;
                   8641: 			    } else {
                   8642: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8643: 			    }
1.339     albertel 8644: 			    if ($subp eq 'display') {
                   8645: 				$value.=' [Part: '.$part.']';
                   8646: 			    }
1.599     albertel 8647: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8648: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8649: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8650: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8651: 			    }
1.599     albertel 8652: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8653: 				$metaentry{':'.$unikey}=
                   8654: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8655: 			    }
1.339     albertel 8656: 			}
                   8657: 		    }
                   8658: 		} else {
1.172     www      8659: #
                   8660: # This is not a package - some other kind of start tag
1.339     albertel 8661: #
                   8662: 		    my $entry=$token->[1];
1.1068    www      8663: 		    my $unikey='';
1.175     www      8664: 
1.339     albertel 8665: 		    if ($entry eq 'import') {
1.175     www      8666: #
                   8667: # Importing a library here
1.339     albertel 8668: #
1.1067    www      8669:                         my $location=$parser->get_text('/import');
                   8670:                         my $dir=$filename;
                   8671:                         $dir=~s|[^/]*$||;
                   8672:                         $location=&filelocation($dir,$location);
1.1069    www      8673:                        
1.1068    www      8674:                         my $importmode=$token->[2]->{'importmode'};
                   8675:                         if ($importmode eq 'problem') {
1.1069    www      8676: # Import as problem/response
1.1068    www      8677:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8678:                         } elsif ($importmode eq 'part') {
                   8679: # Import as part(s)
1.1069    www      8680:                            $importedparts=1;
                   8681: # We need to get the original file and the imported file to get the part order correct
                   8682: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8683: # Load and inspect original file
1.1070    www      8684:                            if ($#origfileimportpartids<0) {
                   8685:                               undef(%importedpartids);
                   8686:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8687:                               my $origfile=&getfile($origfilelocation);
                   8688:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8689:                            }
                   8690: 
1.1069    www      8691: # Load and inspect imported file
                   8692:                            my $impfile=&getfile($location);
                   8693:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8694:                            if ($#impfilepartids>=0) {
                   8695: # This problem had parts
1.1070    www      8696:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8697:                            } else {
                   8698: # Importing by turning a single problem into a problem part
                   8699: # It gets the import-tags ID as part-ID
                   8700:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8701:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8702:                            }
1.1068    www      8703:                         } else {
                   8704: # Normal import
                   8705:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8706:                            if (defined($token->[2]->{'id'})) {
                   8707:                               $unikey.='_'.$token->[2]->{'id'};
                   8708:                            }
1.1067    www      8709:                         }
                   8710: 
1.339     albertel 8711: 			if ($depthcount<20) {
1.736     albertel 8712: 			    my $metadata = 
                   8713: 				&metadata($uri,'keys', $location,$unikey,
                   8714: 					  $depthcount+1);
                   8715: 			    foreach my $meta (split(',',$metadata)) {
                   8716: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8717: 				$metathesekeys{$meta}=1;
1.339     albertel 8718: 			    }
1.1068    www      8719: 			
                   8720:                         }
1.1067    www      8721: 		    } else {
                   8722: #
                   8723: # Not importing, some other kind of non-package, non-library start tag
                   8724: # 
                   8725:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8726:                         if (defined($token->[2]->{'id'})) {
                   8727:                             $unikey.='_'.$token->[2]->{'id'};
                   8728:                         }
1.339     albertel 8729: 			if (defined($token->[2]->{'name'})) { 
                   8730: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8731: 			}
                   8732: 			$metathesekeys{$unikey}=1;
1.736     albertel 8733: 			foreach my $param (@{$token->[3]}) {
                   8734: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8735: 				$token->[2]->{$param};
1.339     albertel 8736: 			}
                   8737: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8738: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8739: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8740: 		 # only ws inside the tag, and not in default, so use default
                   8741: 		 # as value
1.599     albertel 8742: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8743: 			} elsif ( $internaltext =~ /\S/ ) {
                   8744: 		  # something interesting inside the tag
                   8745: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8746: 			} else {
1.908     albertel 8747: 		  # no interesting values, don't set a default
1.339     albertel 8748: 			}
1.172     www      8749: # end of not-a-package not-a-library import
1.339     albertel 8750: 		    }
1.172     www      8751: # end of not-a-package start tag
1.339     albertel 8752: 		}
1.172     www      8753: # the next is the end of "start tag"
1.339     albertel 8754: 	    }
                   8755: 	}
1.483     albertel 8756: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8757: 	$extension = lc($extension);
                   8758: 	if ($extension eq 'htm') { $extension='html'; }
                   8759: 
1.737     albertel 8760: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8761: 	    #no specific packages #how's our extension
                   8762: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8763: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8764: 					 \%metathesekeys);
                   8765: 	}
1.883     albertel 8766: 
                   8767: 	if (!exists($metaentry{':packages'})
                   8768: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8769: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8770: 		#no specific packages well let's get default then
                   8771: 		if ($key!~/^default&/) { next; }
1.488     albertel 8772: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8773: 					     \%metathesekeys);
                   8774: 	    }
                   8775: 	}
1.338     www      8776: # are there custom rights to evaluate
1.599     albertel 8777: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8778: 
1.338     www      8779:     #
                   8780:     # Importing a rights file here
1.339     albertel 8781:     #
                   8782: 	    unless ($depthcount) {
1.599     albertel 8783: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8784: 		my $dir=$filename;
                   8785: 		$dir=~s|[^/]*$||;
                   8786: 		$location=&filelocation($dir,$location);
1.736     albertel 8787: 		my $rights_metadata =
                   8788: 		    &metadata($uri,'keys',$location,'_rights',
                   8789: 			      $depthcount+1);
                   8790: 		foreach my $rights (split(',',$rights_metadata)) {
                   8791: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8792: 		    $metathesekeys{$rights}=1;
1.339     albertel 8793: 		}
                   8794: 	    }
                   8795: 	}
1.737     albertel 8796: 	# uniqifiy package listing
                   8797: 	my %seen;
                   8798: 	my @uniq_packages =
                   8799: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8800: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8801: 
1.1070    www      8802:         if ($importedparts) {
                   8803: # We had imported parts and need to rebuild partorder
                   8804:            $metaentry{':partorder'}='';
                   8805:            $metathesekeys{'partorder'}=1;
                   8806:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8807:                if ($origfileimportpartids[$index] eq 'part') {
                   8808: # original part, part of the problem
                   8809:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8810:                } else {
                   8811: # we have imported parts at this position
                   8812:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8813:                }
                   8814:            }
                   8815:            $metaentry{':partorder'}=~s/^\,//;
                   8816:         }
                   8817: 
1.737     albertel 8818: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8819: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8820: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8821: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8822: # this is the end of "was not already recently cached
1.71      www      8823:     }
1.599     albertel 8824:     return $metaentry{':'.$what};
1.261     albertel 8825: }
                   8826: 
1.488     albertel 8827: sub metadata_create_package_def {
1.483     albertel 8828:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8829:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8830:     if ($subp eq 'default') { next; }
                   8831:     
1.599     albertel 8832:     if (defined($metaentry{':packages'})) {
                   8833: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8834:     } else {
1.599     albertel 8835: 	$metaentry{':packages'}=$package;
1.483     albertel 8836:     }
                   8837:     my $value=$packagetab{$key};
                   8838:     my $unikey;
                   8839:     $unikey='parameter_0_'.$name;
1.599     albertel 8840:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8841:     $$metathesekeys{$unikey}=1;
1.599     albertel 8842:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8843: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8844:     }
1.599     albertel 8845:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8846: 	$metaentry{':'.$unikey}=
                   8847: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8848:     }
                   8849: }
                   8850: 
1.261     albertel 8851: sub metadata_generate_part0 {
                   8852:     my ($metadata,$metacache,$uri) = @_;
                   8853:     my %allnames;
1.737     albertel 8854:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8855: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8856: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8857: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8858: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8859: 	    $allnames{$name}=$part;
                   8860: 	  }
                   8861: 	}
                   8862:     }
                   8863:     foreach my $name (keys(%allnames)) {
                   8864:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8865:       my $key=":parameter_0_$name";
1.261     albertel 8866:       $$metacache{"$key.part"}='0';
                   8867:       $$metacache{"$key.name"}=$name;
1.428     albertel 8868:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8869: 					   $allnames{$name}.'_'.$name.
                   8870: 					   '.type'};
1.428     albertel 8871:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8872: 			     '.display'};
1.644     www      8873:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8874:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8875:       $$metacache{"$key.display"}=$olddis;
                   8876:     }
1.71      www      8877: }
                   8878: 
1.764     albertel 8879: # ------------------------------------------------------ Devalidate title cache
                   8880: 
                   8881: sub devalidate_title_cache {
                   8882:     my ($url)=@_;
                   8883:     if (!$env{'request.course.id'}) { return; }
                   8884:     my $symb=&symbread($url);
                   8885:     if (!$symb) { return; }
                   8886:     my $key=$env{'request.course.id'}."\0".$symb;
                   8887:     &devalidate_cache_new('title',$key);
                   8888: }
                   8889: 
1.1014    droeschl 8890: # ------------------------------------------------- Get the title of a course
                   8891: 
                   8892: sub current_course_title {
                   8893:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8894: }
1.301     www      8895: # ------------------------------------------------- Get the title of a resource
                   8896: 
                   8897: sub gettitle {
                   8898:     my $urlsymb=shift;
                   8899:     my $symb=&symbread($urlsymb);
1.534     albertel 8900:     if ($symb) {
1.620     albertel 8901: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8902: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8903: 	if (defined($cached)) { 
                   8904: 	    return $result;
                   8905: 	}
1.534     albertel 8906: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8907: 	my $title='';
1.907     albertel 8908: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8909: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8910: 	} else {
                   8911: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8912: 		    &GDBM_READER(),0640)) {
                   8913: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8914: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8915: 		untie(%bighash);
                   8916: 	    }
1.534     albertel 8917: 	}
                   8918: 	$title=~s/\&colon\;/\:/gs;
                   8919: 	if ($title) {
1.599     albertel 8920: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8921: 	}
                   8922: 	$urlsymb=$url;
                   8923:     }
                   8924:     my $title=&metadata($urlsymb,'title');
                   8925:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8926:     return $title;
1.301     www      8927: }
1.613     albertel 8928: 
1.614     albertel 8929: sub get_slot {
                   8930:     my ($which,$cnum,$cdom)=@_;
                   8931:     if (!$cnum || !$cdom) {
1.790     albertel 8932: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8933: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8934: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8935:     }
1.703     albertel 8936:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8937:     my %slotinfo;
                   8938:     if (exists($remembered{$key})) {
                   8939: 	$slotinfo{$which} = $remembered{$key};
                   8940:     } else {
                   8941: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8942: 	&Apache::lonhomework::showhash(%slotinfo);
                   8943: 	my ($tmp)=keys(%slotinfo);
                   8944: 	if ($tmp=~/^error:/) { return (); }
                   8945: 	$remembered{$key} = $slotinfo{$which};
                   8946:     }
1.616     albertel 8947:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8948: 	return %{$slotinfo{$which}};
                   8949:     }
                   8950:     return $slotinfo{$which};
1.614     albertel 8951: }
1.31      www      8952: # ------------------------------------------------- Update symbolic store links
                   8953: 
                   8954: sub symblist {
                   8955:     my ($mapname,%newhash)=@_;
1.438     www      8956:     $mapname=&deversion(&declutter($mapname));
1.31      www      8957:     my %hash;
1.620     albertel 8958:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8959:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8960:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8961: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8962: 		next if ($url eq 'last_known'
                   8963: 			 && $env{'form.no_update_last_known'});
                   8964: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8965: 						    $newhash{$url}->[1],
                   8966: 						    $newhash{$url}->[0]);
1.191     harris41 8967:             }
1.31      www      8968:             if (untie(%hash)) {
                   8969: 		return 'ok';
                   8970:             }
                   8971:         }
                   8972:     }
                   8973:     return 'error';
1.212     www      8974: }
                   8975: 
                   8976: # --------------------------------------------------------------- Verify a symb
                   8977: 
                   8978: sub symbverify {
1.510     www      8979:     my ($symb,$thisurl)=@_;
                   8980:     my $thisfn=$thisurl;
1.439     www      8981:     $thisfn=&declutter($thisfn);
1.215     www      8982: # direct jump to resource in page or to a sequence - will construct own symbs
                   8983:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8984: # check URL part
1.409     www      8985:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8986: 
1.431     www      8987:     unless ($url eq $thisfn) { return 0; }
1.213     www      8988: 
1.216     www      8989:     $symb=&symbclean($symb);
1.510     www      8990:     $thisurl=&deversion($thisurl);
1.439     www      8991:     $thisfn=&deversion($thisfn);
1.213     www      8992: 
                   8993:     my %bighash;
                   8994:     my $okay=0;
1.431     www      8995: 
1.620     albertel 8996:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8997:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8998:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8999:             $thisurl =~ s/\?.+$//;
                   9000:         }
1.510     www      9001:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9002:         unless ($ids) {
                   9003:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9004:             $ids=$bighash{$idkey};
1.216     www      9005:         }
                   9006:         if ($ids) {
                   9007: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9008: 	    foreach my $id (split(/\,/,$ids)) {
                   9009: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9010:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9011:                    $symb =~ s/\?.+$//;
                   9012:                }
1.216     www      9013:                if (
                   9014:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9015:    eq $symb) { 
1.620     albertel 9016: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9017: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9018:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9019: 		       $okay=1; 
                   9020: 		   }
                   9021: 	       }
1.216     www      9022: 	   }
                   9023:         }
1.213     www      9024: 	untie(%bighash);
                   9025:     }
                   9026:     return $okay;
1.31      www      9027: }
                   9028: 
1.210     www      9029: # --------------------------------------------------------------- Clean-up symb
                   9030: 
                   9031: sub symbclean {
                   9032:     my $symb=shift;
1.568     albertel 9033:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9034: # remove version from map
                   9035:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9036: 
1.210     www      9037: # remove version from URL
                   9038:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9039: 
1.507     www      9040: # remove wrapper
                   9041: 
1.510     www      9042:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9043:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9044:     return $symb;
1.409     www      9045: }
                   9046: 
                   9047: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9048: 
                   9049: sub encode_symb {
                   9050:     my ($map,$resid,$url)=@_;
                   9051:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9052: }
1.409     www      9053: 
                   9054: sub decode_symb {
1.568     albertel 9055:     my $symb=shift;
                   9056:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9057:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9058:     return (&fixversion($map),$resid,&fixversion($url));
                   9059: }
                   9060: 
                   9061: sub fixversion {
                   9062:     my $fn=shift;
1.609     banghart 9063:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9064:     my %bighash;
                   9065:     my $uri=&clutter($fn);
1.620     albertel 9066:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9067: # is this cached?
1.599     albertel 9068:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9069:     if (defined($cached)) { return $result; }
                   9070: # unfortunately not cached, or expired
1.620     albertel 9071:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9072: 	    &GDBM_READER(),0640)) {
                   9073:  	if ($bighash{'version_'.$uri}) {
                   9074:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9075:  	    unless (($version eq 'mostrecent') || 
                   9076: 		    ($version==&getversion($uri))) {
1.440     www      9077:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9078:  	    }
                   9079:  	}
                   9080:  	untie %bighash;
1.413     www      9081:     }
1.599     albertel 9082:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9083: }
                   9084: 
                   9085: sub deversion {
                   9086:     my $url=shift;
                   9087:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9088:     return $url;
1.210     www      9089: }
                   9090: 
1.31      www      9091: # ------------------------------------------------------ Return symb list entry
                   9092: 
                   9093: sub symbread {
1.249     www      9094:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9095:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9096:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9097: # no filename provided? try from environment
1.44      www      9098:     unless ($thisfn) {
1.620     albertel 9099:         if ($env{'request.symb'}) {
                   9100: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9101: 	}
1.620     albertel 9102: 	$thisfn=$env{'request.filename'};
1.44      www      9103:     }
1.569     albertel 9104:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9105: # is that filename actually a symb? Verify, clean, and return
                   9106:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9107: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9108: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9109: 	}
1.242     www      9110:     }
1.44      www      9111:     $thisfn=declutter($thisfn);
1.31      www      9112:     my %hash;
1.37      www      9113:     my %bighash;
                   9114:     my $syval='';
1.620     albertel 9115:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9116:         my $targetfn = $thisfn;
1.609     banghart 9117:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9118:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9119:         }
1.687     albertel 9120: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9121: 	    $targetfn=$1;
                   9122: 	}
1.620     albertel 9123:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9124:                       &GDBM_READER(),0640)) {
1.481     raeburn  9125: 	    $syval=$hash{$targetfn};
1.37      www      9126:             untie(%hash);
                   9127:         }
                   9128: # ---------------------------------------------------------- There was an entry
                   9129:         if ($syval) {
1.601     albertel 9130: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9131: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9132: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9133: 		    #return $env{$cache_str}='';
1.601     albertel 9134: 		#}    
                   9135: 		#$syval.=$1;
                   9136: 	    #}
1.37      www      9137:         } else {
                   9138: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9139:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9140:                             &GDBM_READER(),0640)) {
1.37      www      9141: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9142:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9143:               unless ($ids) { 
                   9144:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9145:               }
                   9146:               unless ($ids) {
                   9147: # alias?
                   9148: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9149:               }
1.37      www      9150:               if ($ids) {
                   9151: # ------------------------------------------------------------------- Has ID(s)
                   9152:                  my @possibilities=split(/\,/,$ids);
1.39      www      9153:                  if ($#possibilities==0) {
                   9154: # ----------------------------------------------- There is only one possibility
1.37      www      9155: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9156: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9157: 						    $resid,$thisfn);
1.249     www      9158:                  } elsif (!$donotrecurse) {
1.39      www      9159: # ------------------------------------------ There is more than one possibility
                   9160:                      my $realpossible=0;
1.800     albertel 9161:                      foreach my $id (@possibilities) {
                   9162: 			 my $file=$bighash{'src_'.$id};
1.39      www      9163:                          if (&allowed('bre',$file)) {
1.800     albertel 9164:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9165:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9166: 				$realpossible++;
1.626     albertel 9167:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9168: 						    $resid,$thisfn);
1.39      www      9169:                             }
                   9170: 			 }
1.191     harris41 9171:                      }
1.39      www      9172: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9173:                  } else {
                   9174:                      $syval='';
1.37      www      9175:                  }
                   9176: 	      }
                   9177:               untie(%bighash)
1.481     raeburn  9178:            }
1.31      www      9179:         }
1.62      www      9180:         if ($syval) {
1.620     albertel 9181: 	    return $env{$cache_str}=$syval;
1.62      www      9182:         }
1.31      www      9183:     }
1.949     raeburn  9184:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9185:     return $env{$cache_str}='';
1.31      www      9186: }
                   9187: 
                   9188: # ---------------------------------------------------------- Return random seed
                   9189: 
1.32      www      9190: sub numval {
                   9191:     my $txt=shift;
                   9192:     $txt=~tr/A-J/0-9/;
                   9193:     $txt=~tr/a-j/0-9/;
                   9194:     $txt=~tr/K-T/0-9/;
                   9195:     $txt=~tr/k-t/0-9/;
                   9196:     $txt=~tr/U-Z/0-5/;
                   9197:     $txt=~tr/u-z/0-5/;
                   9198:     $txt=~s/\D//g;
1.564     albertel 9199:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9200:     return int($txt);
1.368     albertel 9201: }
                   9202: 
1.484     albertel 9203: sub numval2 {
                   9204:     my $txt=shift;
                   9205:     $txt=~tr/A-J/0-9/;
                   9206:     $txt=~tr/a-j/0-9/;
                   9207:     $txt=~tr/K-T/0-9/;
                   9208:     $txt=~tr/k-t/0-9/;
                   9209:     $txt=~tr/U-Z/0-5/;
                   9210:     $txt=~tr/u-z/0-5/;
                   9211:     $txt=~s/\D//g;
                   9212:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9213:     my $total;
                   9214:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9215:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9216:     return int($total);
                   9217: }
                   9218: 
1.575     albertel 9219: sub numval3 {
                   9220:     use integer;
                   9221:     my $txt=shift;
                   9222:     $txt=~tr/A-J/0-9/;
                   9223:     $txt=~tr/a-j/0-9/;
                   9224:     $txt=~tr/K-T/0-9/;
                   9225:     $txt=~tr/k-t/0-9/;
                   9226:     $txt=~tr/U-Z/0-5/;
                   9227:     $txt=~tr/u-z/0-5/;
                   9228:     $txt=~s/\D//g;
                   9229:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9230:     my $total;
                   9231:     foreach my $val (@txts) { $total+=$val; }
                   9232:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9233:     return $total;
                   9234: }
                   9235: 
1.675     albertel 9236: sub digest {
                   9237:     my ($data)=@_;
                   9238:     my $digest=&Digest::MD5::md5($data);
                   9239:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9240:     my ($e,$f);
                   9241:     {
                   9242:         use integer;
                   9243:         $e=($a+$b);
                   9244:         $f=($c+$d);
                   9245:         if ($_64bit) {
                   9246:             $e=(($e<<32)>>32);
                   9247:             $f=(($f<<32)>>32);
                   9248:         }
                   9249:     }
                   9250:     if (wantarray) {
                   9251: 	return ($e,$f);
                   9252:     } else {
                   9253: 	my $g;
                   9254: 	{
                   9255: 	    use integer;
                   9256: 	    $g=($e+$f);
                   9257: 	    if ($_64bit) {
                   9258: 		$g=(($g<<32)>>32);
                   9259: 	    }
                   9260: 	}
                   9261: 	return $g;
                   9262:     }
                   9263: }
                   9264: 
1.368     albertel 9265: sub latest_rnd_algorithm_id {
1.675     albertel 9266:     return '64bit5';
1.366     albertel 9267: }
1.32      www      9268: 
1.503     albertel 9269: sub get_rand_alg {
                   9270:     my ($courseid)=@_;
1.790     albertel 9271:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9272:     if ($courseid) {
1.620     albertel 9273: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9274:     }
                   9275:     return &latest_rnd_algorithm_id();
                   9276: }
                   9277: 
1.562     albertel 9278: sub validCODE {
                   9279:     my ($CODE)=@_;
                   9280:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9281:     return 0;
                   9282: }
                   9283: 
1.491     albertel 9284: sub getCODE {
1.620     albertel 9285:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9286:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9287: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9288: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9289: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9290:     }
                   9291:     return undef;
                   9292: }
                   9293: 
1.31      www      9294: sub rndseed {
1.155     albertel 9295:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9296:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9297:     if (!defined($symb)) {
1.366     albertel 9298: 	unless ($symb=$wsymb) { return time; }
                   9299:     }
                   9300:     if (!$courseid) { $courseid=$wcourseid; }
                   9301:     if (!$domain) { $domain=$wdomain; }
                   9302:     if (!$username) { $username=$wusername }
1.503     albertel 9303:     my $which=&get_rand_alg();
1.1110    www      9304: 
1.491     albertel 9305:     if (defined(&getCODE())) {
1.675     albertel 9306: 	if ($which eq '64bit5') {
                   9307: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9308: 	} elsif ($which eq '64bit4') {
1.575     albertel 9309: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9310: 	} else {
                   9311: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9312: 	}
1.675     albertel 9313:     } elsif ($which eq '64bit5') {
                   9314: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9315:     } elsif ($which eq '64bit4') {
                   9316: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9317:     } elsif ($which eq '64bit3') {
                   9318: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9319:     } elsif ($which eq '64bit2') {
                   9320: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9321:     } elsif ($which eq '64bit') {
                   9322: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9323:     }
                   9324:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9325: }
                   9326: 
                   9327: sub rndseed_32bit {
                   9328:     my ($symb,$courseid,$domain,$username)=@_;
                   9329:     {
                   9330: 	use integer;
                   9331: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9332: 	my $symbseed=numval($symb) << 22;
                   9333: 	my $namechck=unpack("%32C*",$username) << 17;
                   9334: 	my $nameseed=numval($username) << 12;
                   9335: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9336: 	my $courseseed=unpack("%32C*",$courseid);
                   9337: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9338: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9339: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9340: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9341: 	return $num;
                   9342:     }
                   9343: }
                   9344: 
                   9345: sub rndseed_64bit {
                   9346:     my ($symb,$courseid,$domain,$username)=@_;
                   9347:     {
                   9348: 	use integer;
                   9349: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9350: 	my $symbseed=numval($symb) << 10;
                   9351: 	my $namechck=unpack("%32S*",$username);
                   9352: 	
                   9353: 	my $nameseed=numval($username) << 21;
                   9354: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9355: 	my $courseseed=unpack("%32S*",$courseid);
                   9356: 	
                   9357: 	my $num1=$symbchck+$symbseed+$namechck;
                   9358: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9359: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9360: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9361: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9362: 	return "$num1,$num2";
1.155     albertel 9363:     }
1.366     albertel 9364: }
                   9365: 
1.443     albertel 9366: sub rndseed_64bit2 {
                   9367:     my ($symb,$courseid,$domain,$username)=@_;
                   9368:     {
                   9369: 	use integer;
                   9370: 	# strings need to be an even # of cahracters long, it it is odd the
                   9371:         # last characters gets thrown away
                   9372: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9373: 	my $symbseed=numval($symb) << 10;
                   9374: 	my $namechck=unpack("%32S*",$username.' ');
                   9375: 	
                   9376: 	my $nameseed=numval($username) << 21;
1.501     albertel 9377: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9378: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9379: 	
                   9380: 	my $num1=$symbchck+$symbseed+$namechck;
                   9381: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9382: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9383: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9384: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9385: 	return "$num1,$num2";
                   9386:     }
                   9387: }
                   9388: 
                   9389: sub rndseed_64bit3 {
                   9390:     my ($symb,$courseid,$domain,$username)=@_;
                   9391:     {
                   9392: 	use integer;
                   9393: 	# strings need to be an even # of cahracters long, it it is odd the
                   9394:         # last characters gets thrown away
                   9395: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9396: 	my $symbseed=numval2($symb) << 10;
                   9397: 	my $namechck=unpack("%32S*",$username.' ');
                   9398: 	
                   9399: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9400: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9401: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9402: 	
                   9403: 	my $num1=$symbchck+$symbseed+$namechck;
                   9404: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9405: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9406: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9407: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9408: 	
1.503     albertel 9409: 	return "$num1:$num2";
1.443     albertel 9410:     }
                   9411: }
                   9412: 
1.575     albertel 9413: sub rndseed_64bit4 {
                   9414:     my ($symb,$courseid,$domain,$username)=@_;
                   9415:     {
                   9416: 	use integer;
                   9417: 	# strings need to be an even # of cahracters long, it it is odd the
                   9418:         # last characters gets thrown away
                   9419: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9420: 	my $symbseed=numval3($symb) << 10;
                   9421: 	my $namechck=unpack("%32S*",$username.' ');
                   9422: 	
                   9423: 	my $nameseed=numval3($username) << 21;
                   9424: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9425: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9426: 	
                   9427: 	my $num1=$symbchck+$symbseed+$namechck;
                   9428: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9429: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9430: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9431: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9432: 	
1.575     albertel 9433: 	return "$num1:$num2";
                   9434:     }
                   9435: }
                   9436: 
1.675     albertel 9437: sub rndseed_64bit5 {
                   9438:     my ($symb,$courseid,$domain,$username)=@_;
                   9439:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9440:     return "$num1:$num2";
                   9441: }
                   9442: 
1.366     albertel 9443: sub rndseed_CODE_64bit {
                   9444:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9445:     {
1.366     albertel 9446: 	use integer;
1.443     albertel 9447: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9448: 	my $symbseed=numval2($symb);
1.491     albertel 9449: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9450: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9451: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9452: 	my $num1=$symbseed+$CODEchck;
                   9453: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9454: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9455: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9456: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9457: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9458: 	return "$num1:$num2";
1.366     albertel 9459:     }
                   9460: }
                   9461: 
1.575     albertel 9462: sub rndseed_CODE_64bit4 {
                   9463:     my ($symb,$courseid,$domain,$username)=@_;
                   9464:     {
                   9465: 	use integer;
                   9466: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9467: 	my $symbseed=numval3($symb);
                   9468: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9469: 	my $CODEseed=numval3(&getCODE());
                   9470: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9471: 	my $num1=$symbseed+$CODEchck;
                   9472: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9473: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9474: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9475: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9476: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9477: 	return "$num1:$num2";
                   9478:     }
                   9479: }
                   9480: 
1.675     albertel 9481: sub rndseed_CODE_64bit5 {
                   9482:     my ($symb,$courseid,$domain,$username)=@_;
                   9483:     my $code = &getCODE();
                   9484:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9485:     return "$num1:$num2";
                   9486: }
                   9487: 
1.366     albertel 9488: sub setup_random_from_rndseed {
                   9489:     my ($rndseed)=@_;
1.503     albertel 9490:     if ($rndseed =~/([,:])/) {
                   9491: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9492: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9493:     } else {
                   9494: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9495:     }
1.36      albertel 9496: }
                   9497: 
1.474     albertel 9498: sub latest_receipt_algorithm_id {
1.835     albertel 9499:     return 'receipt3';
1.474     albertel 9500: }
                   9501: 
1.480     www      9502: sub recunique {
                   9503:     my $fucourseid=shift;
                   9504:     my $unique;
1.835     albertel 9505:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9506: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9507: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9508:     } else {
                   9509: 	$unique=$perlvar{'lonReceipt'};
                   9510:     }
                   9511:     return unpack("%32C*",$unique);
                   9512: }
                   9513: 
                   9514: sub recprefix {
                   9515:     my $fucourseid=shift;
                   9516:     my $prefix;
1.835     albertel 9517:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9518: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9519: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9520:     } else {
                   9521: 	$prefix=$perlvar{'lonHostID'};
                   9522:     }
                   9523:     return unpack("%32C*",$prefix);
                   9524: }
                   9525: 
1.76      www      9526: sub ireceipt {
1.474     albertel 9527:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9528: 
                   9529:     my $return =&recprefix($fucourseid).'-';
                   9530: 
                   9531:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9532: 	$env{'request.state'} eq 'construct') {
                   9533: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9534: 	return $return;
                   9535:     }
                   9536: 
1.76      www      9537:     my $cuname=unpack("%32C*",$funame);
                   9538:     my $cudom=unpack("%32C*",$fudom);
                   9539:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9540:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9541:     my $cunique=&recunique($fucourseid);
1.474     albertel 9542:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9543:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9544: 
1.790     albertel 9545: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9546: 			       
                   9547: 	$return.= ($cunique%$cuname+
                   9548: 		   $cunique%$cudom+
                   9549: 		   $cusymb%$cuname+
                   9550: 		   $cusymb%$cudom+
                   9551: 		   $cucourseid%$cuname+
                   9552: 		   $cucourseid%$cudom+
                   9553: 		   $cpart%$cuname+
                   9554: 		   $cpart%$cudom);
                   9555:     } else {
                   9556: 	$return.= ($cunique%$cuname+
                   9557: 		   $cunique%$cudom+
                   9558: 		   $cusymb%$cuname+
                   9559: 		   $cusymb%$cudom+
                   9560: 		   $cucourseid%$cuname+
                   9561: 		   $cucourseid%$cudom);
                   9562:     }
                   9563:     return $return;
1.76      www      9564: }
                   9565: 
                   9566: sub receipt {
1.474     albertel 9567:     my ($part)=@_;
1.790     albertel 9568:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9569:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9570: }
1.260     ng       9571: 
1.790     albertel 9572: sub whichuser {
                   9573:     my ($passedsymb)=@_;
                   9574:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9575:     if (defined($env{'form.grade_symb'})) {
                   9576: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9577: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9578: 	if (!$allowed &&
                   9579: 	    exists($env{'request.course.sec'}) &&
                   9580: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9581: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9582: 			      '/'.$env{'request.course.sec'});
                   9583: 	}
                   9584: 	if ($allowed) {
                   9585: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9586: 	    $courseid=$tmp_courseid;
                   9587: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9588: 	    ($name)=&get_env_multiple('form.grade_username');
                   9589: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9590: 	}
                   9591:     }
                   9592:     if (!$passedsymb) {
                   9593: 	$symb=&symbread();
                   9594:     } else {
                   9595: 	$symb=$passedsymb;
                   9596:     }
                   9597:     $courseid=$env{'request.course.id'};
                   9598:     $domain=$env{'user.domain'};
                   9599:     $name=$env{'user.name'};
                   9600:     if ($name eq 'public' && $domain eq 'public') {
                   9601: 	if (!defined($env{'form.username'})) {
                   9602: 	    $env{'form.username'}.=time.rand(10000000);
                   9603: 	}
                   9604: 	$name.=$env{'form.username'};
                   9605:     }
                   9606:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9607: 
                   9608: }
                   9609: 
1.36      albertel 9610: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9611: # returns either the contents of the file or 
                   9612: # -1 if the file doesn't exist
1.481     raeburn  9613: #
                   9614: # if the target is a file that was uploaded via DOCS, 
                   9615: # a check will be made to see if a current copy exists on the local server,
                   9616: # if it does this will be served, otherwise a copy will be retrieved from
                   9617: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9618: # the local server.   
1.472     albertel 9619: 
1.36      albertel 9620: sub getfile {
1.538     albertel 9621:     my ($file) = @_;
1.609     banghart 9622:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9623:     &repcopy($file);
                   9624:     return &readfile($file);
                   9625: }
                   9626: 
                   9627: sub repcopy_userfile {
                   9628:     my ($file)=@_;
1.609     banghart 9629:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9630:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9631:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9632: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9633:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9634:     if (-e "$file") {
1.828     www      9635: # we already have a local copy, check it out
1.538     albertel 9636: 	my @fileinfo = stat($file);
1.828     www      9637: 	my $rtncode;
                   9638: 	my $info;
1.538     albertel 9639: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9640: 	if ($lwpresp ne 'ok') {
1.828     www      9641: # there is no such file anymore, even though we had a local copy
1.482     albertel 9642: 	    if ($rtncode eq '404') {
1.538     albertel 9643: 		unlink($file);
1.482     albertel 9644: 	    }
                   9645: 	    return -1;
                   9646: 	}
                   9647: 	if ($info < $fileinfo[9]) {
1.828     www      9648: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9649: 	    return 'ok';
1.828     www      9650: 	} else {
                   9651: # the file is outdated, get rid of it
                   9652: 	    unlink($file);
1.482     albertel 9653: 	}
1.828     www      9654:     }
                   9655: # one way or the other, at this point, we don't have the file
                   9656: # construct the correct path for the file
                   9657:     my @parts = ($cdom,$cnum); 
                   9658:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9659: 	push @parts, split(/\//,$1);
                   9660:     }
                   9661:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9662:     foreach my $part (@parts) {
                   9663: 	$path .= '/'.$part;
                   9664: 	if (!-e $path) {
                   9665: 	    mkdir($path,0770);
1.482     albertel 9666: 	}
                   9667:     }
1.828     www      9668: # now the path exists for sure
                   9669: # get a user agent
                   9670:     my $ua=new LWP::UserAgent;
                   9671:     my $transferfile=$file.'.in.transfer';
                   9672: # FIXME: this should flock
                   9673:     if (-e $transferfile) { return 'ok'; }
                   9674:     my $request;
                   9675:     $uri=~s/^\///;
1.980     raeburn  9676:     my $homeserver = &homeserver($cnum,$cdom);
                   9677:     my $protocol = $protocol{$homeserver};
                   9678:     $protocol = 'http' if ($protocol ne 'https');
                   9679:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9680:     my $response=$ua->request($request,$transferfile);
                   9681: # did it work?
                   9682:     if ($response->is_error()) {
                   9683: 	unlink($transferfile);
                   9684: 	&logthis("Userfile repcopy failed for $uri");
                   9685: 	return -1;
                   9686:     }
                   9687: # worked, rename the transfer file
                   9688:     rename($transferfile,$file);
1.607     raeburn  9689:     return 'ok';
1.481     raeburn  9690: }
                   9691: 
1.517     albertel 9692: sub tokenwrapper {
                   9693:     my $uri=shift;
1.980     raeburn  9694:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9695:     $uri=~s|^/||;
1.620     albertel 9696:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9697:     my $token=$1;
1.552     albertel 9698:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9699:     if ($udom && $uname && $file) {
                   9700: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9701:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9702:         my $homeserver = &homeserver($uname,$udom);
                   9703:         my $protocol = $protocol{$homeserver};
                   9704:         $protocol = 'http' if ($protocol ne 'https');
                   9705:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9706:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9707:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9708:     } else {
                   9709:         return '/adm/notfound.html';
                   9710:     }
                   9711: }
                   9712: 
1.828     www      9713: # call with reqtype HEAD: get last modification time
                   9714: # call with reqtype GET: get the file contents
                   9715: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9716: #
1.481     raeburn  9717: sub getuploaded {
                   9718:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9719:     $uri=~s/^\///;
1.980     raeburn  9720:     my $homeserver = &homeserver($cnum,$cdom);
                   9721:     my $protocol = $protocol{$homeserver};
                   9722:     $protocol = 'http' if ($protocol ne 'https');
                   9723:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9724:     my $ua=new LWP::UserAgent;
                   9725:     my $request=new HTTP::Request($reqtype,$uri);
                   9726:     my $response=$ua->request($request);
                   9727:     $$rtncode = $response->code;
1.482     albertel 9728:     if (! $response->is_success()) {
                   9729: 	return 'failed';
                   9730:     }      
                   9731:     if ($reqtype eq 'HEAD') {
1.486     www      9732: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9733:     } elsif ($reqtype eq 'GET') {
                   9734: 	$$info = $response->content;
1.472     albertel 9735:     }
1.482     albertel 9736:     return 'ok';
1.36      albertel 9737: }
                   9738: 
1.481     raeburn  9739: sub readfile {
                   9740:     my $file = shift;
                   9741:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9742:     my $fh;
                   9743:     open($fh,"<$file");
                   9744:     my $a='';
1.800     albertel 9745:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9746:     return $a;
                   9747: }
                   9748: 
1.36      albertel 9749: sub filelocation {
1.590     banghart 9750:     my ($dir,$file) = @_;
                   9751:     my $location;
                   9752:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9753: 
                   9754:     if ($file =~ m-^/adm/-) {
                   9755: 	$file=~s-^/adm/wrapper/-/-;
                   9756: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9757:     }
1.882     albertel 9758: 
1.590     banghart 9759:     if ($file=~m:^/~:) { # is a contruction space reference
                   9760:         $location = $file;
                   9761:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9762:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9763: 	# is a correct contruction space reference
                   9764:         $location = $file;
1.956     raeburn  9765:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9766:         $location = $file;
1.609     banghart 9767:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9768:         my ($udom,$uname,$filename)=
1.811     albertel 9769:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9770:         my $home=&homeserver($uname,$udom);
                   9771:         my $is_me=0;
                   9772:         my @ids=&current_machine_ids();
                   9773:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9774:         if ($is_me) {
1.955     raeburn  9775:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9776:         } else {
                   9777:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9778:   	      $udom.'/'.$uname.'/'.$filename;
                   9779:         }
1.882     albertel 9780:     } elsif ($file =~ m-^/adm/-) {
                   9781: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9782:     } else {
                   9783:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9784:         $file=~s:^/res/:/:;
                   9785:         if ( !( $file =~ m:^/:) ) {
                   9786:             $location = $dir. '/'.$file;
                   9787:         } else {
                   9788:             $location = '/home/httpd/html/res'.$file;
                   9789:         }
1.59      albertel 9790:     }
1.590     banghart 9791:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9792:     while ($location=~m{/\.\./}) {
                   9793: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9794: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9795: 	} else {
                   9796: 	    $location=~ s{/\.\./}{/}g;
                   9797: 	}
                   9798:     } #remove dir/..
1.590     banghart 9799:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9800:     return $location;
1.46      www      9801: }
1.36      albertel 9802: 
1.46      www      9803: sub hreflocation {
                   9804:     my ($dir,$file)=@_;
1.980     raeburn  9805:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9806: 	$file=filelocation($dir,$file);
1.700     albertel 9807:     } elsif ($file=~m-^/adm/-) {
                   9808: 	$file=~s-^/adm/wrapper/-/-;
                   9809: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9810:     }
                   9811:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9812: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9813:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9814: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9815:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9816: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9817: 	    -/uploaded/$1/$2/-x;
1.46      www      9818:     }
1.913     albertel 9819:     if ($file=~ m{^/userfiles/}) {
                   9820: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9821:     }
1.462     albertel 9822:     return $file;
1.465     albertel 9823: }
                   9824: 
                   9825: sub current_machine_domains {
1.853     albertel 9826:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9827: }
                   9828: 
                   9829: sub machine_domains {
                   9830:     my ($hostname) = @_;
1.465     albertel 9831:     my @domains;
1.838     albertel 9832:     my %hostname = &all_hostnames();
1.465     albertel 9833:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9834: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9835: 	if ($hostname eq $name) {
1.844     albertel 9836: 	    push(@domains,&host_domain($id));
1.465     albertel 9837: 	}
                   9838:     }
                   9839:     return @domains;
                   9840: }
                   9841: 
                   9842: sub current_machine_ids {
1.853     albertel 9843:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9844: }
                   9845: 
                   9846: sub machine_ids {
                   9847:     my ($hostname) = @_;
                   9848:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9849:     my @ids;
1.888     albertel 9850:     my %name_to_host = &all_names();
1.889     albertel 9851:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9852: 	return @{ $name_to_host{$hostname} };
                   9853:     }
                   9854:     return;
1.31      www      9855: }
                   9856: 
1.824     raeburn  9857: sub additional_machine_domains {
                   9858:     my @domains;
                   9859:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9860:     while( my $line = <$fh>) {
                   9861:         $line =~ s/\s//g;
                   9862:         push(@domains,$line);
                   9863:     }
                   9864:     return @domains;
                   9865: }
                   9866: 
                   9867: sub default_login_domain {
                   9868:     my $domain = $perlvar{'lonDefDomain'};
                   9869:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9870:     foreach my $posdom (&current_machine_domains(),
                   9871:                         &additional_machine_domains()) {
                   9872:         if (lc($posdom) eq lc($testdomain)) {
                   9873:             $domain=$posdom;
                   9874:             last;
                   9875:         }
                   9876:     }
                   9877:     return $domain;
                   9878: }
                   9879: 
1.31      www      9880: # ------------------------------------------------------------- Declutters URLs
                   9881: 
                   9882: sub declutter {
                   9883:     my $thisfn=shift;
1.569     albertel 9884:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9885:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9886:     $thisfn=~s/^\///;
1.697     albertel 9887:     $thisfn=~s|^adm/wrapper/||;
                   9888:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9889:     $thisfn=~s/^res\///;
1.1032    raeburn  9890:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9891:         $thisfn=~s/\?.+$//;
                   9892:     }
1.268     www      9893:     return $thisfn;
                   9894: }
                   9895: 
                   9896: # ------------------------------------------------------------- Clutter up URLs
                   9897: 
                   9898: sub clutter {
                   9899:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9900:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9901: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9902:        $thisfn='/res'.$thisfn; 
                   9903:     }
1.1031    raeburn  9904:     if ($thisfn !~m|^/adm|) {
                   9905: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9906: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9907: 	} else {
                   9908: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9909: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9910: 	    if ($embstyle eq 'ssi'
                   9911: 		|| ($embstyle eq 'hdn')
                   9912: 		|| ($embstyle eq 'rat')
                   9913: 		|| ($embstyle eq 'prv')
                   9914: 		|| ($embstyle eq 'ign')) {
                   9915: 		#do nothing with these
                   9916: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9917: 		|| ($embstyle eq 'emb')
                   9918: 		|| ($embstyle eq 'wrp')) {
                   9919: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9920: 	    } elsif ($embstyle eq 'unk'
                   9921: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9922: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9923: 	    } else {
1.718     www      9924: #		&logthis("Got a blank emb style");
1.695     albertel 9925: 	    }
1.694     albertel 9926: 	}
                   9927:     }
1.31      www      9928:     return $thisfn;
1.12      www      9929: }
                   9930: 
1.787     albertel 9931: sub clutter_with_no_wrapper {
                   9932:     my $uri = &clutter(shift);
                   9933:     if ($uri =~ m-^/adm/-) {
                   9934: 	$uri =~ s-^/adm/wrapper/-/-;
                   9935: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9936:     }
                   9937:     return $uri;
                   9938: }
                   9939: 
1.557     albertel 9940: sub freeze_escape {
                   9941:     my ($value)=@_;
                   9942:     if (ref($value)) {
                   9943: 	$value=&nfreeze($value);
                   9944: 	return '__FROZEN__'.&escape($value);
                   9945:     }
                   9946:     return &escape($value);
                   9947: }
                   9948: 
1.11      www      9949: 
1.557     albertel 9950: sub thaw_unescape {
                   9951:     my ($value)=@_;
                   9952:     if ($value =~ /^__FROZEN__/) {
                   9953: 	substr($value,0,10,undef);
                   9954: 	$value=&unescape($value);
                   9955: 	return &thaw($value);
                   9956:     }
                   9957:     return &unescape($value);
                   9958: }
                   9959: 
1.436     albertel 9960: sub correct_line_ends {
                   9961:     my ($result)=@_;
                   9962:     $$result =~s/\r\n/\n/mg;
                   9963:     $$result =~s/\r/\n/mg;
1.415     albertel 9964: }
1.1       albertel 9965: # ================================================================ Main Program
                   9966: 
1.184     www      9967: sub goodbye {
1.204     albertel 9968:    &logthis("Starting Shut down");
1.443     albertel 9969: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9970:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9971: #converted
1.599     albertel 9972: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9973:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9974: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9975: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9976: #1.1 only
1.870     albertel 9977: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9978: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9979: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9980: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9981:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9982:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9983:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9984:    &flushcourselogs();
                   9985:    &logthis("Shutting down");
                   9986: }
                   9987: 
1.852     albertel 9988: sub get_dns {
1.869     albertel 9989:     my ($url,$func,$ignore_cache) = @_;
                   9990:     if (!$ignore_cache) {
                   9991: 	my ($content,$cached)=
                   9992: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9993: 	if ($cached) {
                   9994: 	    &$func($content);
                   9995: 	    return;
                   9996: 	}
                   9997:     }
                   9998: 
                   9999:     my %alldns;
1.852     albertel 10000:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10001:     foreach my $dns (<$config>) {
                   10002: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10003:         my $line = $1;
                   10004:         my ($host,$protocol) = split(/:/,$line);
                   10005:         if ($protocol ne 'https') {
                   10006:             $protocol = 'http';
                   10007:         }
                   10008: 	$alldns{$host} = $protocol;
1.869     albertel 10009:     }
                   10010:     while (%alldns) {
                   10011: 	my ($dns) = keys(%alldns);
1.852     albertel 10012: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10013: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10014: 	my $response=$ua->request($request);
1.979     raeburn  10015:         delete($alldns{$dns});
1.852     albertel 10016: 	next if ($response->is_error());
                   10017: 	my @content = split("\n",$response->content);
1.869     albertel 10018: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10019: 	&$func(\@content);
1.869     albertel 10020: 	return;
1.852     albertel 10021:     }
                   10022:     close($config);
1.871     albertel 10023:     my $which = (split('/',$url))[3];
                   10024:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10025:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10026:     my @content = <$config>;
                   10027:     &$func(\@content);
                   10028:     return;
1.852     albertel 10029: }
1.327     albertel 10030: # ------------------------------------------------------------ Read domain file
                   10031: {
1.852     albertel 10032:     my $loaded;
1.846     albertel 10033:     my %domain;
                   10034: 
1.852     albertel 10035:     sub parse_domain_tab {
                   10036: 	my ($lines) = @_;
                   10037: 	foreach my $line (@$lines) {
                   10038: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10039: 
1.846     albertel 10040: 	    chomp($line);
1.852     albertel 10041: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10042: 	    my %this_domain;
                   10043: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10044: 			       'lang_def', 'city', 'longi', 'lati',
                   10045: 			       'primary') {
                   10046: 		$this_domain{$field} = shift(@elements);
                   10047: 	    }
                   10048: 	    $domain{$name} = \%this_domain;
1.852     albertel 10049: 	}
                   10050:     }
1.864     albertel 10051: 
                   10052:     sub reset_domain_info {
                   10053: 	undef($loaded);
                   10054: 	undef(%domain);
                   10055:     }
                   10056: 
1.852     albertel 10057:     sub load_domain_tab {
1.869     albertel 10058: 	my ($ignore_cache) = @_;
                   10059: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10060: 	my $fh;
                   10061: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10062: 	    my @lines = <$fh>;
                   10063: 	    &parse_domain_tab(\@lines);
1.448     albertel 10064: 	}
1.852     albertel 10065: 	close($fh);
                   10066: 	$loaded = 1;
1.327     albertel 10067:     }
1.846     albertel 10068: 
                   10069:     sub domain {
1.852     albertel 10070: 	&load_domain_tab() if (!$loaded);
                   10071: 
1.846     albertel 10072: 	my ($name,$what) = @_;
                   10073: 	return if ( !exists($domain{$name}) );
                   10074: 
                   10075: 	if (!$what) {
                   10076: 	    return $domain{$name}{'description'};
                   10077: 	}
                   10078: 	return $domain{$name}{$what};
                   10079:     }
1.974     raeburn  10080: 
                   10081:     sub domain_info {
                   10082:         &load_domain_tab() if (!$loaded);
                   10083:         return %domain;
                   10084:     }
                   10085: 
1.327     albertel 10086: }
                   10087: 
                   10088: 
1.1       albertel 10089: # ------------------------------------------------------------- Read hosts file
                   10090: {
1.838     albertel 10091:     my %hostname;
1.844     albertel 10092:     my %hostdom;
1.845     albertel 10093:     my %libserv;
1.852     albertel 10094:     my $loaded;
1.888     albertel 10095:     my %name_to_host;
1.1074    raeburn  10096:     my %internetdom;
1.1107    raeburn  10097:     my %LC_dns_serv;
1.852     albertel 10098: 
                   10099:     sub parse_hosts_tab {
                   10100: 	my ($file) = @_;
                   10101: 	foreach my $configline (@$file) {
                   10102: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10103:             chomp($configline);
                   10104: 	    if ($configline =~ /^\^/) {
                   10105:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10106:                     $LC_dns_serv{$1} = 1;
                   10107:                 }
                   10108:                 next;
                   10109:             }
1.1074    raeburn  10110: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10111: 	    $name=~s/\s//g;
                   10112: 	    if ($id && $domain && $role && $name) {
                   10113: 		$hostname{$id}=$name;
1.888     albertel 10114: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10115: 		$hostdom{$id}=$domain;
                   10116: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10117:                 if (defined($protocol)) {
                   10118:                     if ($protocol eq 'https') {
                   10119:                         $protocol{$id} = $protocol;
                   10120:                     } else {
                   10121:                         $protocol{$id} = 'http'; 
                   10122:                     }
1.968     raeburn  10123:                 } else {
1.969     raeburn  10124:                     $protocol{$id} = 'http';
1.968     raeburn  10125:                 }
1.1074    raeburn  10126:                 if (defined($intdom)) {
                   10127:                     $internetdom{$id} = $intdom;
                   10128:                 }
1.852     albertel 10129: 	    }
                   10130: 	}
                   10131:     }
1.864     albertel 10132:     
                   10133:     sub reset_hosts_info {
1.897     albertel 10134: 	&purge_remembered();
1.864     albertel 10135: 	&reset_domain_info();
                   10136: 	&reset_hosts_ip_info();
1.892     albertel 10137: 	undef(%name_to_host);
1.864     albertel 10138: 	undef(%hostname);
                   10139: 	undef(%hostdom);
                   10140: 	undef(%libserv);
                   10141: 	undef($loaded);
                   10142:     }
1.1       albertel 10143: 
1.852     albertel 10144:     sub load_hosts_tab {
1.869     albertel 10145: 	my ($ignore_cache) = @_;
                   10146: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10147: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10148: 	my @config = <$config>;
                   10149: 	&parse_hosts_tab(\@config);
                   10150: 	close($config);
                   10151: 	$loaded=1;
1.1       albertel 10152:     }
1.852     albertel 10153: 
1.838     albertel 10154:     sub hostname {
1.852     albertel 10155: 	&load_hosts_tab() if (!$loaded);
                   10156: 
1.838     albertel 10157: 	my ($lonid) = @_;
                   10158: 	return $hostname{$lonid};
                   10159:     }
1.845     albertel 10160: 
1.838     albertel 10161:     sub all_hostnames {
1.852     albertel 10162: 	&load_hosts_tab() if (!$loaded);
                   10163: 
1.838     albertel 10164: 	return %hostname;
                   10165:     }
1.845     albertel 10166: 
1.888     albertel 10167:     sub all_names {
                   10168: 	&load_hosts_tab() if (!$loaded);
                   10169: 
                   10170: 	return %name_to_host;
                   10171:     }
                   10172: 
1.974     raeburn  10173:     sub all_host_domain {
                   10174:         &load_hosts_tab() if (!$loaded);
                   10175:         return %hostdom;
                   10176:     }
                   10177: 
1.845     albertel 10178:     sub is_library {
1.852     albertel 10179: 	&load_hosts_tab() if (!$loaded);
                   10180: 
1.845     albertel 10181: 	return exists($libserv{$_[0]});
                   10182:     }
                   10183: 
                   10184:     sub all_library {
1.852     albertel 10185: 	&load_hosts_tab() if (!$loaded);
                   10186: 
1.845     albertel 10187: 	return %libserv;
                   10188:     }
                   10189: 
1.1062    droeschl 10190:     sub unique_library {
                   10191: 	#2x reverse removes all hostnames that appear more than once
                   10192:         my %unique = reverse &all_library();
                   10193:         return reverse %unique;
                   10194:     }
                   10195: 
1.841     albertel 10196:     sub get_servers {
1.852     albertel 10197: 	&load_hosts_tab() if (!$loaded);
                   10198: 
1.841     albertel 10199: 	my ($domain,$type) = @_;
                   10200: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10201: 	                                          : %hostname;
                   10202: 	my %result;
1.842     albertel 10203: 	if (ref($domain) eq 'ARRAY') {
                   10204: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10205: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10206: 		    $result{$host} = $hostname;
                   10207: 		}
                   10208: 	    }
                   10209: 	} else {
                   10210: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10211: 		if ($hostdom{$host} eq $domain) {
                   10212: 		    $result{$host} = $hostname;
                   10213: 		}
1.841     albertel 10214: 	    }
                   10215: 	}
                   10216: 	return %result;
                   10217:     }
1.845     albertel 10218: 
1.1062    droeschl 10219:     sub get_unique_servers {
                   10220:         my %unique = reverse &get_servers(@_);
                   10221: 	return reverse %unique;
                   10222:     }
                   10223: 
1.844     albertel 10224:     sub host_domain {
1.852     albertel 10225: 	&load_hosts_tab() if (!$loaded);
                   10226: 
1.844     albertel 10227: 	my ($lonid) = @_;
                   10228: 	return $hostdom{$lonid};
                   10229:     }
                   10230: 
1.841     albertel 10231:     sub all_domains {
1.852     albertel 10232: 	&load_hosts_tab() if (!$loaded);
                   10233: 
1.841     albertel 10234: 	my %seen;
                   10235: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10236: 	return @uniq;
                   10237:     }
1.1074    raeburn  10238: 
                   10239:     sub internet_dom {
                   10240:         &load_hosts_tab() if (!$loaded);
                   10241: 
                   10242:         my ($lonid) = @_;
                   10243:         return $internetdom{$lonid};
                   10244:     }
1.1107    raeburn  10245: 
                   10246:     sub is_LC_dns {
                   10247:         &load_hosts_tab() if (!$loaded);
                   10248: 
                   10249:         my ($hostname) = @_;
                   10250:         return exists($LC_dns_serv{$hostname});
                   10251:     }
                   10252: 
1.1       albertel 10253: }
                   10254: 
1.847     albertel 10255: { 
                   10256:     my %iphost;
1.856     albertel 10257:     my %name_to_ip;
                   10258:     my %lonid_to_ip;
1.869     albertel 10259: 
1.847     albertel 10260:     sub get_hosts_from_ip {
                   10261: 	my ($ip) = @_;
                   10262: 	my %iphosts = &get_iphost();
                   10263: 	if (ref($iphosts{$ip})) {
                   10264: 	    return @{$iphosts{$ip}};
                   10265: 	}
                   10266: 	return;
1.839     albertel 10267:     }
1.864     albertel 10268:     
                   10269:     sub reset_hosts_ip_info {
                   10270: 	undef(%iphost);
                   10271: 	undef(%name_to_ip);
                   10272: 	undef(%lonid_to_ip);
                   10273:     }
1.856     albertel 10274: 
                   10275:     sub get_host_ip {
                   10276: 	my ($lonid) = @_;
                   10277: 	if (exists($lonid_to_ip{$lonid})) {
                   10278: 	    return $lonid_to_ip{$lonid};
                   10279: 	}
                   10280: 	my $name=&hostname($lonid);
                   10281:    	my $ip = gethostbyname($name);
                   10282: 	return if (!$ip || length($ip) ne 4);
                   10283: 	$ip=inet_ntoa($ip);
                   10284: 	$name_to_ip{$name}   = $ip;
                   10285: 	$lonid_to_ip{$lonid} = $ip;
                   10286: 	return $ip;
                   10287:     }
1.847     albertel 10288:     
                   10289:     sub get_iphost {
1.869     albertel 10290: 	my ($ignore_cache) = @_;
1.894     albertel 10291: 
1.869     albertel 10292: 	if (!$ignore_cache) {
                   10293: 	    if (%iphost) {
                   10294: 		return %iphost;
                   10295: 	    }
                   10296: 	    my ($ip_info,$cached)=
                   10297: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10298: 	    if ($cached) {
                   10299: 		%iphost      = %{$ip_info->[0]};
                   10300: 		%name_to_ip  = %{$ip_info->[1]};
                   10301: 		%lonid_to_ip = %{$ip_info->[2]};
                   10302: 		return %iphost;
                   10303: 	    }
                   10304: 	}
1.894     albertel 10305: 
                   10306: 	# get yesterday's info for fallback
                   10307: 	my %old_name_to_ip;
                   10308: 	my ($ip_info,$cached)=
                   10309: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10310: 	if ($cached) {
                   10311: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10312: 	}
                   10313: 
1.888     albertel 10314: 	my %name_to_host = &all_names();
                   10315: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10316: 	    my $ip;
                   10317: 	    if (!exists($name_to_ip{$name})) {
                   10318: 		$ip = gethostbyname($name);
                   10319: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10320: 		    if (defined($old_name_to_ip{$name})) {
                   10321: 			$ip = $old_name_to_ip{$name};
                   10322: 			&logthis("Can't find $name defaulting to old $ip");
                   10323: 		    } else {
                   10324: 			&logthis("Name $name no IP found");
                   10325: 			next;
                   10326: 		    }
                   10327: 		} else {
                   10328: 		    $ip=inet_ntoa($ip);
1.847     albertel 10329: 		}
                   10330: 		$name_to_ip{$name} = $ip;
                   10331: 	    } else {
                   10332: 		$ip = $name_to_ip{$name};
1.653     albertel 10333: 	    }
1.888     albertel 10334: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10335: 		$lonid_to_ip{$id} = $ip;
                   10336: 	    }
                   10337: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10338: 	}
1.869     albertel 10339: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10340: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10341: 				      48*60*60);
1.869     albertel 10342: 
1.847     albertel 10343: 	return %iphost;
1.598     albertel 10344:     }
                   10345: 
1.992     raeburn  10346:     #
                   10347:     #  Given a DNS returns the loncapa host name for that DNS 
                   10348:     # 
                   10349:     sub host_from_dns {
                   10350:         my ($dns) = @_;
                   10351:         my @hosts;
                   10352:         my $ip;
                   10353: 
1.993     raeburn  10354:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10355:             $ip = $name_to_ip{$dns};
                   10356:         }
                   10357:         if (!$ip) {
                   10358:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10359:             if (length($ip) == 4) { 
                   10360: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10361:             }
                   10362:         }
                   10363:         if ($ip) {
                   10364: 	    @hosts = get_hosts_from_ip($ip);
                   10365: 	    return $hosts[0];
                   10366:         }
                   10367:         return undef;
1.986     foxr     10368:     }
1.992     raeburn  10369: 
1.1074    raeburn  10370:     sub get_internet_names {
                   10371:         my ($lonid) = @_;
                   10372:         return if ($lonid eq '');
                   10373:         my ($idnref,$cached)=
                   10374:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10375:         if ($cached) {
                   10376:             return $idnref;
                   10377:         }
                   10378:         my $ip = &get_host_ip($lonid);
                   10379:         my @hosts = &get_hosts_from_ip($ip);
                   10380:         my %iphost = &get_iphost();
                   10381:         my (@idns,%seen);
                   10382:         foreach my $id (@hosts) {
                   10383:             my $dom = &host_domain($id);
                   10384:             my $prim_id = &domain($dom,'primary');
                   10385:             my $prim_ip = &get_host_ip($prim_id);
                   10386:             next if ($seen{$prim_ip});
                   10387:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10388:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10389:                     my $intdom = &internet_dom($id);
                   10390:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10391:                         push(@idns,$intdom);
                   10392:                     }
                   10393:                 }
                   10394:             }
                   10395:             $seen{$prim_ip} = 1;
                   10396:         }
                   10397:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10398:     }
                   10399: 
1.986     foxr     10400: }
                   10401: 
1.1079    raeburn  10402: sub all_loncaparevs {
                   10403:     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);
                   10404: }
                   10405: 
1.862     albertel 10406: BEGIN {
                   10407: 
                   10408: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10409:     unless ($readit) {
                   10410: {
                   10411:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10412:     %perlvar = (%perlvar,%{$configvars});
                   10413: }
                   10414: 
                   10415: 
1.1       albertel 10416: # ------------------------------------------------------ Read spare server file
                   10417: {
1.448     albertel 10418:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10419: 
                   10420:     while (my $configline=<$config>) {
                   10421:        chomp($configline);
1.284     matthew  10422:        if ($configline) {
1.784     albertel 10423: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10424: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10425: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10426:        }
                   10427:     }
1.448     albertel 10428:     close($config);
1.1       albertel 10429: }
1.11      www      10430: # ------------------------------------------------------------ Read permissions
                   10431: {
1.448     albertel 10432:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10433: 
                   10434:     while (my $configline=<$config>) {
1.448     albertel 10435: 	chomp($configline);
                   10436: 	if ($configline) {
                   10437: 	    my ($role,$perm)=split(/ /,$configline);
                   10438: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10439: 	}
1.11      www      10440:     }
1.448     albertel 10441:     close($config);
1.11      www      10442: }
                   10443: 
                   10444: # -------------------------------------------- Read plain texts for permissions
                   10445: {
1.448     albertel 10446:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10447: 
                   10448:     while (my $configline=<$config>) {
1.448     albertel 10449: 	chomp($configline);
                   10450: 	if ($configline) {
1.742     raeburn  10451: 	    my ($short,@plain)=split(/:/,$configline);
                   10452:             %{$prp{$short}} = ();
                   10453: 	    if (@plain > 0) {
                   10454:                 $prp{$short}{'std'} = $plain[0];
                   10455:                 for (my $i=1; $i<@plain; $i++) {
                   10456:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10457:                 }
                   10458:             }
1.448     albertel 10459: 	}
1.135     www      10460:     }
1.448     albertel 10461:     close($config);
1.135     www      10462: }
                   10463: 
                   10464: # ---------------------------------------------------------- Read package table
                   10465: {
1.448     albertel 10466:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10467: 
                   10468:     while (my $configline=<$config>) {
1.483     albertel 10469: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10470: 	chomp($configline);
                   10471: 	my ($short,$plain)=split(/:/,$configline);
                   10472: 	my ($pack,$name)=split(/\&/,$short);
                   10473: 	if ($plain ne '') {
                   10474: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10475: 	    $packagetab{$short}=$plain; 
                   10476: 	}
1.11      www      10477:     }
1.448     albertel 10478:     close($config);
1.329     matthew  10479: }
                   10480: 
1.1073    raeburn  10481: # ---------------------------------------------------------- Read loncaparev table
                   10482: {
                   10483:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10484:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10485:             while (my $configline=<$config>) {
                   10486:                 chomp($configline);
                   10487:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10488:                 $loncaparevs{$hostid}=$loncaparev;
                   10489:             }
                   10490:             close($config);
                   10491:         }
                   10492:     }
                   10493: }
                   10494: 
1.1074    raeburn  10495: # ---------------------------------------------------------- Read serverhostID table
                   10496: {
                   10497:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10498:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10499:             while (my $configline=<$config>) {
                   10500:                 chomp($configline);
                   10501:                 my ($name,$id)=split(/:/,$configline);
                   10502:                 $serverhomeIDs{$name}=$id;
                   10503:             }
                   10504:             close($config);
                   10505:         }
                   10506:     }
                   10507: }
                   10508: 
1.1079    raeburn  10509: {
                   10510:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10511:     if (-e $file) {
                   10512:         my $parser = HTML::LCParser->new($file);
                   10513:         while (my $token = $parser->get_token()) {
                   10514:             if ($token->[0] eq 'S') {
                   10515:                 my $item = $token->[1];
                   10516:                 my $name = $token->[2]{'name'};
                   10517:                 my $value = $token->[2]{'value'};
                   10518:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10519:                     my $release = $parser->get_text();
                   10520:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10521:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10522:                 }
                   10523:             }
                   10524:         }
                   10525:     }
1.1073    raeburn  10526: }
                   10527: 
1.329     matthew  10528: # ------------- set up temporary directory
                   10529: {
                   10530:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10531: 
1.11      www      10532: }
                   10533: 
1.794     albertel 10534: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10535: 				'compress_threshold'=> 20_000,
                   10536:  			        });
1.185     www      10537: 
1.281     www      10538: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10539: $dumpcount=0;
1.958     www      10540: $locknum=0;
1.22      www      10541: 
1.163     harris41 10542: &logtouch();
1.672     albertel 10543: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10544: $readit=1;
1.564     albertel 10545:     {
                   10546: 	use integer;
                   10547: 	my $test=(2**32)+1;
1.568     albertel 10548: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10549: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10550:     }
1.195     www      10551: }
1.1       albertel 10552: }
1.179     www      10553: 
1.1       albertel 10554: 1;
1.191     harris41 10555: __END__
                   10556: 
1.243     albertel 10557: =pod
                   10558: 
1.191     harris41 10559: =head1 NAME
                   10560: 
1.243     albertel 10561: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10562: 
                   10563: =head1 SYNOPSIS
                   10564: 
1.243     albertel 10565: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10566: 
                   10567:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10568: 
1.243     albertel 10569: Common parameters:
                   10570: 
                   10571: =over 4
                   10572: 
                   10573: =item *
                   10574: 
                   10575: $uname : an internal username (if $cname expecting a course Id specifically)
                   10576: 
                   10577: =item *
                   10578: 
                   10579: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10580: 
                   10581: =item *
                   10582: 
                   10583: $symb : a resource instance identifier
                   10584: 
                   10585: =item *
                   10586: 
                   10587: $namespace : the name of a .db file that contains the data needed or
                   10588: being set.
                   10589: 
                   10590: =back
                   10591: 
1.394     bowersj2 10592: =head1 OVERVIEW
1.191     harris41 10593: 
1.394     bowersj2 10594: lonnet provides subroutines which interact with the
                   10595: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10596: about classes, users, and resources.
1.243     albertel 10597: 
                   10598: For many of these objects you can also use this to store data about
                   10599: them or modify them in various ways.
1.191     harris41 10600: 
1.394     bowersj2 10601: =head2 Symbs
1.191     harris41 10602: 
1.394     bowersj2 10603: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10604: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10605: map, the resource number of the resource in the map, and the URL of
                   10606: the resource itself. The latter is somewhat redundant, but might help
                   10607: if maps change.
                   10608: 
                   10609: An example is
                   10610: 
                   10611:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10612: 
                   10613: The respective map entry is
                   10614: 
                   10615:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10616:   title="Problem 2">
                   10617:  </resource>
                   10618: 
                   10619: Symbs are used by the random number generator, as well as to store and
                   10620: restore data specific to a certain instance of for example a problem.
                   10621: 
                   10622: =head2 Storing And Retrieving Data
                   10623: 
                   10624: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10625: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10626: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10627: is is the non-critical message twin of cstore. These functions are for
                   10628: handlers to store a perl hash to a user's permanent data space in an
                   10629: easy manner, and to retrieve it again on another call. It is expected
                   10630: that a handler would use this once at the beginning to retrieve data,
                   10631: and then again once at the end to send only the new data back.
                   10632: 
                   10633: The data is stored in the user's data directory on the user's
                   10634: homeserver under the ID of the course.
                   10635: 
                   10636: The hash that is returned by restore will have all of the previous
                   10637: value for all of the elements of the hash.
                   10638: 
                   10639: Example:
                   10640: 
                   10641:  #creating a hash
                   10642:  my %hash;
                   10643:  $hash{'foo'}='bar';
                   10644: 
                   10645:  #storing it
                   10646:  &Apache::lonnet::cstore(\%hash);
                   10647: 
                   10648:  #changing a value
                   10649:  $hash{'foo'}='notbar';
                   10650: 
                   10651:  #adding a new value
                   10652:  $hash{'bar'}='foo';
                   10653:  &Apache::lonnet::cstore(\%hash);
                   10654: 
                   10655:  #retrieving the hash
                   10656:  my %history=&Apache::lonnet::restore();
                   10657: 
                   10658:  #print the hash
                   10659:  foreach my $key (sort(keys(%history))) {
                   10660:    print("\%history{$key} = $history{$key}");
                   10661:  }
                   10662: 
                   10663: Will print out:
1.191     harris41 10664: 
1.394     bowersj2 10665:  %history{1:foo} = bar
                   10666:  %history{1:keys} = foo:timestamp
                   10667:  %history{1:timestamp} = 990455579
                   10668:  %history{2:bar} = foo
                   10669:  %history{2:foo} = notbar
                   10670:  %history{2:keys} = foo:bar:timestamp
                   10671:  %history{2:timestamp} = 990455580
                   10672:  %history{bar} = foo
                   10673:  %history{foo} = notbar
                   10674:  %history{timestamp} = 990455580
                   10675:  %history{version} = 2
                   10676: 
                   10677: Note that the special hash entries C<keys>, C<version> and
                   10678: C<timestamp> were added to the hash. C<version> will be equal to the
                   10679: total number of versions of the data that have been stored. The
                   10680: C<timestamp> attribute will be the UNIX time the hash was
                   10681: stored. C<keys> is available in every historical section to list which
                   10682: keys were added or changed at a specific historical revision of a
                   10683: hash.
                   10684: 
                   10685: B<Warning>: do not store the hash that restore returns directly. This
                   10686: will cause a mess since it will restore the historical keys as if the
                   10687: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10688: 
1.394     bowersj2 10689: Calling convention:
1.191     harris41 10690: 
1.394     bowersj2 10691:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10692:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10693: 
1.394     bowersj2 10694: For more detailed information, see lonnet specific documentation.
1.191     harris41 10695: 
1.394     bowersj2 10696: =head1 RETURN MESSAGES
1.191     harris41 10697: 
1.394     bowersj2 10698: =over 4
1.191     harris41 10699: 
1.394     bowersj2 10700: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10701: 
1.394     bowersj2 10702: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10703: when the connection is brought back up
1.191     harris41 10704: 
1.394     bowersj2 10705: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10706: for later delivery
1.191     harris41 10707: 
1.967     bisitz   10708: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10709: 
1.394     bowersj2 10710: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10711: that was requested
1.191     harris41 10712: 
1.243     albertel 10713: =back
1.191     harris41 10714: 
1.243     albertel 10715: =head1 PUBLIC SUBROUTINES
1.191     harris41 10716: 
1.243     albertel 10717: =head2 Session Environment Functions
1.191     harris41 10718: 
1.243     albertel 10719: =over 4
1.191     harris41 10720: 
1.394     bowersj2 10721: =item * 
                   10722: X<appenv()>
1.949     raeburn  10723: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10724: the user envirnoment file, and will be restored for each access this
1.620     albertel 10725: user makes during this session, also modifies the %env for the current
1.949     raeburn  10726: process. Optional rolesarrayref - if defined contains a reference to an array
                   10727: of roles which are exempt from the restriction on modifying user.role entries 
                   10728: in the user's environment.db and in %env.    
1.191     harris41 10729: 
                   10730: =item *
1.394     bowersj2 10731: X<delenv()>
1.987     raeburn  10732: B<delenv($delthis,$regexp)>: removes all items from the session
                   10733: environment file that begin with $delthis. If the 
                   10734: optional second arg - $regexp - is true, $delthis is treated as a 
                   10735: regular expression, otherwise \Q$delthis\E is used. 
                   10736: The values are also deleted from the current processes %env.
1.191     harris41 10737: 
1.795     albertel 10738: =item * get_env_multiple($name) 
                   10739: 
                   10740: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10741: values may be defined and end up as an array ref.
                   10742: 
                   10743: returns an array of values
                   10744: 
1.243     albertel 10745: =back
                   10746: 
                   10747: =head2 User Information
1.191     harris41 10748: 
1.243     albertel 10749: =over 4
1.191     harris41 10750: 
                   10751: =item *
1.394     bowersj2 10752: X<queryauthenticate()>
                   10753: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10754: authentication scheme
                   10755: 
                   10756: =item *
1.394     bowersj2 10757: X<authenticate()>
1.1073    raeburn  10758: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10759: authenticate user from domain's lib servers (first use the current
                   10760: one). C<$upass> should be the users password.
1.1073    raeburn  10761: $checkdefauth is optional (value is 1 if a check should be made to
                   10762:    authenticate user using default authentication method, and allow
                   10763:    account creation if username does not have account in the domain).
                   10764: $clientcancheckhost is optional (value is 1 if checking whether the
                   10765:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10766: 
                   10767: =item *
1.394     bowersj2 10768: X<homeserver()>
                   10769: B<homeserver($uname,$udom)>: find the server which has
                   10770: the user's directory and files (there must be only one), this caches
                   10771: the answer, and also caches if there is a borken connection.
1.191     harris41 10772: 
                   10773: =item *
1.394     bowersj2 10774: X<idget()>
                   10775: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10776: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10777: username, and only 1 username per ID in a specific domain) (returns
                   10778: hash: id=>name,id=>name)
1.191     harris41 10779: 
                   10780: =item *
1.394     bowersj2 10781: X<idrget()>
                   10782: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10783: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10784: 
                   10785: =item *
1.394     bowersj2 10786: X<idput()>
                   10787: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10788: 
                   10789: =item *
1.394     bowersj2 10790: X<rolesinit()>
                   10791: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10792: 
                   10793: =item *
1.551     albertel 10794: X<getsection()>
                   10795: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10796: course $cname, return section name/number or '' for "not in course"
                   10797: and '-1' for "no section"
                   10798: 
                   10799: =item *
1.394     bowersj2 10800: X<userenvironment()>
                   10801: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10802: passed in @what from the requested user's environment, returns a hash
                   10803: 
1.858     raeburn  10804: =item * 
                   10805: X<userlog_query()>
1.859     albertel 10806: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10807: activity.log file. %filters defines filters applied when parsing the
                   10808: log file. These can be start or end timestamps, or the type of action
                   10809: - log to look for Login or Logout events, check for Checkin or
                   10810: Checkout, role for role selection. The response is in the form
                   10811: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10812: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10813: 
1.243     albertel 10814: =back
                   10815: 
                   10816: =head2 User Roles
                   10817: 
                   10818: =over 4
                   10819: 
                   10820: =item *
                   10821: 
1.810     raeburn  10822: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10823:  F: full access
                   10824:  U,I,K: authentication modes (cxx only)
                   10825:  '': forbidden
                   10826:  1: user needs to choose course
                   10827:  2: browse allowed
1.766     albertel 10828:  A: passphrase authentication needed
1.243     albertel 10829: 
                   10830: =item *
                   10831: 
                   10832: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10833: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10834: and course level
                   10835: 
                   10836: =item *
                   10837: 
1.988     raeburn  10838: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10839: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10840: $type is Course (default) or Community.
1.988     raeburn  10841: If $forcedefault evaluates to true, text returned will be default 
                   10842: text for $type. Otherwise, if this is a course, the text returned 
                   10843: will be a custom name for the role (if defined in the course's 
                   10844: environment).  If no custom name is defined the default is returned.
                   10845:    
1.832     raeburn  10846: =item *
                   10847: 
1.935     raeburn  10848: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10849: All arguments are optional. Returns a hash of a roles, either for
                   10850: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10851: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10852: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10853: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10854: For each key, value is set to colon-separated start and end times for
                   10855: the role.  If no username and domain are specified, will default to
1.934     raeburn  10856: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10857: of role statuses (active, future or previous), roles 
                   10858: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10859: to restrict the list of roles reported. If no array ref is 
                   10860: provided for types, will default to return only active roles.
1.834     albertel 10861: 
1.243     albertel 10862: =back
                   10863: 
                   10864: =head2 User Modification
                   10865: 
                   10866: =over 4
                   10867: 
                   10868: =item *
                   10869: 
1.957     raeburn  10870: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10871: user for the level given by URL.  Optional start and end dates (leave empty
                   10872: string or zero for "no date")
1.191     harris41 10873: 
                   10874: =item *
                   10875: 
1.243     albertel 10876: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10877: change a users, password, possible return values are: ok,
                   10878: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10879: refused
1.191     harris41 10880: 
                   10881: =item *
                   10882: 
1.243     albertel 10883: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10884: 
                   10885: =item *
                   10886: 
1.1058    raeburn  10887: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10888:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10889: 
                   10890: will update user information (firstname,middlename,lastname,generation,
                   10891: permanentemail), and if forceid is true, student/employee ID also.
                   10892: A user's institutional affiliation(s) can also be updated.
                   10893: User information fields will not be overwritten with empty entries 
                   10894: unless the field is included in the $candelete array reference.
                   10895: This array is included when a single user is modified via "Manage Users",
                   10896: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10897: 
                   10898: =item *
                   10899: 
1.286     matthew  10900: modifystudent
                   10901: 
1.957     raeburn  10902: modify a student's enrollment and identification information.
1.286     matthew  10903: The course id is resolved based on the current users environment.  
                   10904: This means the envoking user must be a course coordinator or otherwise
                   10905: associated with a course.
                   10906: 
1.297     matthew  10907: This call is essentially a wrapper for lonnet::modifyuser and
                   10908: lonnet::modify_student_enrollment
1.286     matthew  10909: 
                   10910: Inputs: 
                   10911: 
                   10912: =over 4
                   10913: 
1.957     raeburn  10914: =item B<$udom> Student's loncapa domain
1.286     matthew  10915: 
1.957     raeburn  10916: =item B<$uname> Student's loncapa login name
1.286     matthew  10917: 
1.964     bisitz   10918: =item B<$uid> Student/Employee ID
1.286     matthew  10919: 
1.957     raeburn  10920: =item B<$umode> Student's authentication mode
1.286     matthew  10921: 
1.957     raeburn  10922: =item B<$upass> Student's password
1.286     matthew  10923: 
1.957     raeburn  10924: =item B<$first> Student's first name
1.286     matthew  10925: 
1.957     raeburn  10926: =item B<$middle> Student's middle name
1.286     matthew  10927: 
1.957     raeburn  10928: =item B<$last> Student's last name
1.286     matthew  10929: 
1.957     raeburn  10930: =item B<$gene> Student's generation
1.286     matthew  10931: 
1.957     raeburn  10932: =item B<$usec> Student's section in course
1.286     matthew  10933: 
                   10934: =item B<$end> Unix time of the roles expiration
                   10935: 
                   10936: =item B<$start> Unix time of the roles start date
                   10937: 
                   10938: =item B<$forceid> If defined, allow $uid to be changed
                   10939: 
                   10940: =item B<$desiredhome> server to use as home server for student
                   10941: 
1.957     raeburn  10942: =item B<$email> Student's permanent e-mail address
                   10943: 
                   10944: =item B<$type> Type of enrollment (auto or manual)
                   10945: 
1.963     raeburn  10946: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10947: 
                   10948: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10949: 
1.963     raeburn  10950: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10951: 
1.963     raeburn  10952: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10953: 
1.963     raeburn  10954: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10955: 
1.286     matthew  10956: =back
1.297     matthew  10957: 
                   10958: =item *
                   10959: 
                   10960: modify_student_enrollment
                   10961: 
                   10962: Change a students enrollment status in a class.  The environment variable
                   10963: 'role.request.course' must be defined for this function to proceed.
                   10964: 
                   10965: Inputs:
                   10966: 
                   10967: =over 4
                   10968: 
                   10969: =item $udom, students domain
                   10970: 
                   10971: =item $uname, students name
                   10972: 
                   10973: =item $uid, students user id
                   10974: 
                   10975: =item $first, students first name
                   10976: 
                   10977: =item $middle
                   10978: 
                   10979: =item $last
                   10980: 
                   10981: =item $gene
                   10982: 
                   10983: =item $usec
                   10984: 
                   10985: =item $end
                   10986: 
                   10987: =item $start
                   10988: 
1.957     raeburn  10989: =item $type
                   10990: 
                   10991: =item $locktype
                   10992: 
                   10993: =item $cid
                   10994: 
                   10995: =item $selfenroll
                   10996: 
                   10997: =item $context
                   10998: 
1.297     matthew  10999: =back
                   11000: 
1.191     harris41 11001: 
                   11002: =item *
                   11003: 
1.243     albertel 11004: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11005: custom role; give a custom role to a user for the level given by URL.  Specify
                   11006: name and domain of role author, and role name
1.191     harris41 11007: 
                   11008: =item *
                   11009: 
1.243     albertel 11010: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11011: 
                   11012: =item *
                   11013: 
1.243     albertel 11014: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11015: 
                   11016: =back
                   11017: 
                   11018: =head2 Course Infomation
                   11019: 
                   11020: =over 4
1.191     harris41 11021: 
                   11022: =item *
                   11023: 
1.631     albertel 11024: coursedescription($courseid) : returns a hash of information about the
                   11025: specified course id, including all environment settings for the
                   11026: course, the description of the course will be in the hash under the
                   11027: key 'description'
1.191     harris41 11028: 
                   11029: =item *
                   11030: 
1.624     albertel 11031: resdata($name,$domain,$type,@which) : request for current parameter
                   11032: setting for a specific $type, where $type is either 'course' or 'user',
                   11033: @what should be a list of parameters to ask about. This routine caches
                   11034: answers for 5 minutes.
1.243     albertel 11035: 
1.877     foxr     11036: =item *
                   11037: 
                   11038: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11039: data base, returning a hash that is keyed by the resource name and has
                   11040: values that are the resource value.  I believe that the timestamps and
                   11041: versions are also returned.
                   11042: 
                   11043: 
1.243     albertel 11044: =back
                   11045: 
                   11046: =head2 Course Modification
                   11047: 
                   11048: =over 4
1.191     harris41 11049: 
                   11050: =item *
                   11051: 
1.243     albertel 11052: writecoursepref($courseid,%prefs) : write preferences (environment
                   11053: database) for a course
1.191     harris41 11054: 
                   11055: =item *
                   11056: 
1.1011    raeburn  11057: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11058: 
                   11059: =item *
                   11060: 
1.1038    raeburn  11061: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11062: 
                   11063: =back
                   11064: 
                   11065: =head2 Resource Subroutines
                   11066: 
                   11067: =over 4
1.191     harris41 11068: 
                   11069: =item *
                   11070: 
1.243     albertel 11071: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11072: 
                   11073: =item *
                   11074: 
1.243     albertel 11075: repcopy($filename) : subscribes to the requested file, and attempts to
                   11076: replicate from the owning library server, Might return
1.607     raeburn  11077: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11078: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11079: resource. Expects the local filesystem pathname
                   11080: (/home/httpd/html/res/....)
                   11081: 
                   11082: =back
                   11083: 
                   11084: =head2 Resource Information
                   11085: 
                   11086: =over 4
1.191     harris41 11087: 
                   11088: =item *
                   11089: 
1.243     albertel 11090: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11091: a vairety of different possible values, $varname should be a request
                   11092: string, and the other parameters can be used to specify who and what
                   11093: one is asking about.
                   11094: 
                   11095: Possible values for $varname are environment.lastname (or other item
                   11096: from the envirnment hash), user.name (or someother aspect about the
                   11097: user), resource.0.maxtries (or some other part and parameter of a
                   11098: resource)
1.204     albertel 11099: 
                   11100: =item *
                   11101: 
1.243     albertel 11102: directcondval($number) : get current value of a condition; reads from a state
                   11103: string
1.204     albertel 11104: 
                   11105: =item *
                   11106: 
1.243     albertel 11107: condval($condidx) : value of condition index based on state
1.204     albertel 11108: 
                   11109: =item *
                   11110: 
1.243     albertel 11111: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11112: resource's metadata, $what should be either a specific key, or either
                   11113: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11114: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11115: 
                   11116: this function automatically caches all requests
1.191     harris41 11117: 
                   11118: =item *
                   11119: 
1.243     albertel 11120: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11121: network of library servers; returns file handle of where SQL and regex results
                   11122: will be stored for query
1.191     harris41 11123: 
                   11124: =item *
                   11125: 
1.243     albertel 11126: symbread($filename) : return symbolic list entry (filename argument optional);
                   11127: returns the data handle
1.191     harris41 11128: 
                   11129: =item *
                   11130: 
1.243     albertel 11131: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11132: a possible symb for the URL in $thisfn, and if is an encryypted
                   11133: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11134: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11135: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11136: 
1.191     harris41 11137: 
                   11138: =item *
                   11139: 
1.243     albertel 11140: symbclean($symb) : removes versions numbers from a symb, returns the
                   11141: cleaned symb
1.191     harris41 11142: 
                   11143: =item *
                   11144: 
1.243     albertel 11145: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11146: course map, user must be in a course for it to work.
1.191     harris41 11147: 
                   11148: =item *
                   11149: 
1.243     albertel 11150: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11151: 
                   11152: =item *
                   11153: 
1.243     albertel 11154: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11155: a random seed, all arguments are optional, if they aren't sent it uses the
                   11156: environment to derive them. Note: if symb isn't sent and it can't get one
                   11157: from &symbread it will use the current time as its return value
1.191     harris41 11158: 
                   11159: =item *
                   11160: 
1.243     albertel 11161: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11162: unfakeable, receipt
1.191     harris41 11163: 
                   11164: =item *
                   11165: 
1.620     albertel 11166: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11167: 
                   11168: =item *
                   11169: 
1.243     albertel 11170: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11171: 
                   11172: =item *
                   11173: 
1.243     albertel 11174: 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 11175: 
                   11176: =item *
                   11177: 
1.243     albertel 11178: 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 11179: 
                   11180: =item *
                   11181: 
1.243     albertel 11182: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11183: 
                   11184: =item *
                   11185: 
1.243     albertel 11186: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11187: forcing spreadsheet to reevaluate the resource scores next time.
                   11188: 
                   11189: =back
                   11190: 
                   11191: =head2 Storing/Retreiving Data
                   11192: 
                   11193: =over 4
1.191     harris41 11194: 
                   11195: =item *
                   11196: 
1.243     albertel 11197: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11198: for this url; hashref needs to be given and should be a \%hashname; the
                   11199: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11200: be derived from the env
1.191     harris41 11201: 
                   11202: =item *
                   11203: 
1.243     albertel 11204: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11205: uses critical subroutine
1.191     harris41 11206: 
                   11207: =item *
                   11208: 
1.243     albertel 11209: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11210: all args are optional
1.191     harris41 11211: 
                   11212: =item *
                   11213: 
1.717     albertel 11214: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11215: dumps the complete (or key matching regexp) namespace into a hash
                   11216: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11217: normally &store()ed into
                   11218: 
                   11219: $range should be either an integer '100' (give me the first 100
                   11220:                                            matching records)
                   11221:               or be  two integers sperated by a - with no spaces
                   11222:                  '30-50' (give me the 30th through the 50th matching
                   11223:                           records)
                   11224: 
                   11225: 
                   11226: =item *
                   11227: 
                   11228: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11229: replaces a &store() version of data with a replacement set of data
                   11230: for a particular resource in a namespace passed in the $storehash hash 
                   11231: reference
                   11232: 
                   11233: =item *
                   11234: 
1.243     albertel 11235: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11236: works very similar to store/cstore, but all data is stored in a
                   11237: temporary location and can be reset using tmpreset, $storehash should
                   11238: be a hash reference, returns nothing on success
1.191     harris41 11239: 
                   11240: =item *
                   11241: 
1.243     albertel 11242: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11243: similar to restore, but all data is stored in a temporary location and
                   11244: can be reset using tmpreset. Returns a hash of values on success,
                   11245: error string otherwise.
1.191     harris41 11246: 
                   11247: =item *
                   11248: 
1.243     albertel 11249: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11250: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11251: 
                   11252: =item *
                   11253: 
1.243     albertel 11254: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11255: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11256: 
                   11257: =item *
                   11258: 
1.243     albertel 11259: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11260: namesp ($udom and $uname are optional)
1.191     harris41 11261: 
                   11262: =item *
                   11263: 
1.702     albertel 11264: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11265: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11266: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11267: 
1.702     albertel 11268: $range should be either an integer '100' (give me the first 100
                   11269:                                            matching records)
                   11270:               or be  two integers sperated by a - with no spaces
                   11271:                  '30-50' (give me the 30th through the 50th matching
                   11272:                           records)
1.449     matthew  11273: =item *
                   11274: 
                   11275: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11276: $store can be a scalar, an array reference, or if the amount to be 
                   11277: incremented is > 1, a hash reference.
                   11278: 
                   11279: ($udom and $uname are optional)
1.191     harris41 11280: 
                   11281: =item *
                   11282: 
1.243     albertel 11283: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11284: ($udom and $uname are optional)
1.191     harris41 11285: 
                   11286: =item *
                   11287: 
1.243     albertel 11288: cput($namespace,$storehash,$udom,$uname) : critical put
                   11289: ($udom and $uname are optional)
1.191     harris41 11290: 
                   11291: =item *
                   11292: 
1.748     albertel 11293: newput($namespace,$storehash,$udom,$uname) :
                   11294: 
                   11295: Attempts to store the items in the $storehash, but only if they don't
                   11296: currently exist, if this succeeds you can be certain that you have 
                   11297: successfully created a new key value pair in the $namespace db.
                   11298: 
                   11299: 
                   11300: Args:
                   11301:  $namespace: name of database to store values to
                   11302:  $storehash: hashref to store to the db
                   11303:  $udom: (optional) domain of user containing the db
                   11304:  $uname: (optional) name of user caontaining the db
                   11305: 
                   11306: Returns:
                   11307:  'ok' -> succeeded in storing all keys of $storehash
                   11308:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11309:                         least <key> already existed in the db (other
                   11310:                         requested keys may also already exist)
1.967     bisitz   11311:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11312:  'con_lost' -> unable to contact request server
                   11313:  'refused' -> action was not allowed by remote machine
                   11314: 
                   11315: 
                   11316: =item *
                   11317: 
1.243     albertel 11318: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11319: reference filled in from namesp (encrypts the return communication)
                   11320: ($udom and $uname are optional)
1.191     harris41 11321: 
                   11322: =item *
                   11323: 
1.243     albertel 11324: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11325: critical subroutine
                   11326: 
1.806     raeburn  11327: =item *
                   11328: 
1.860     raeburn  11329: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11330: array reference filled in from namespace found in domain level on either
                   11331: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11332: 
                   11333: =item *
                   11334: 
1.860     raeburn  11335: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11336: domain level either on specified domain server ($uhome) or primary domain 
                   11337: server ($udom and $uhome are optional)
1.806     raeburn  11338: 
1.943     raeburn  11339: =item * 
                   11340: 
                   11341: get_domain_defaults($target_domain) : returns hash with defaults for
                   11342: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11343: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11344: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11345: Values are retrieved from cache (if current), or from domain's configuration.db
                   11346: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11347: or lonTabs/domain.tab. 
                   11348: 
                   11349: %domdefaults = &get_auth_defaults($target_domain);
                   11350: 
1.243     albertel 11351: =back
                   11352: 
                   11353: =head2 Network Status Functions
                   11354: 
                   11355: =over 4
1.191     harris41 11356: 
                   11357: =item *
                   11358: 
                   11359: dirlist($uri) : return directory list based on URI
                   11360: 
                   11361: =item *
                   11362: 
1.243     albertel 11363: spareserver() : find server with least workload from spare.tab
                   11364: 
1.986     foxr     11365: 
                   11366: =item *
                   11367: 
                   11368: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11369: if there is no corresponding loncapa host.
                   11370: 
1.243     albertel 11371: =back
                   11372: 
1.986     foxr     11373: 
1.243     albertel 11374: =head2 Apache Request
                   11375: 
                   11376: =over 4
1.191     harris41 11377: 
                   11378: =item *
                   11379: 
1.243     albertel 11380: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11381: localhost, posts hash
                   11382: 
                   11383: =back
                   11384: 
                   11385: =head2 Data to String to Data
                   11386: 
                   11387: =over 4
1.191     harris41 11388: 
                   11389: =item *
                   11390: 
1.243     albertel 11391: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11392: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11393: 
                   11394: =item *
                   11395: 
1.243     albertel 11396: hashref2str($hashref) : convert a hashref into a string complete with
                   11397: escaping and '=' and '&' separators, supports elements that are
                   11398: arrayrefs and hashrefs
1.191     harris41 11399: 
                   11400: =item *
                   11401: 
1.243     albertel 11402: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11403: with escaping and '&' separators, supports elements that are arrayrefs
                   11404: and hashrefs
1.191     harris41 11405: 
                   11406: =item *
                   11407: 
1.243     albertel 11408: str2hash($string) : convert string to hash using unescaping and
                   11409: splitting on '=' and '&', supports elements that are arrayrefs and
                   11410: hashrefs
1.191     harris41 11411: 
                   11412: =item *
                   11413: 
1.243     albertel 11414: str2array($string) : convert string to hash using unescaping and
                   11415: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11416: 
                   11417: =back
                   11418: 
                   11419: =head2 Logging Routines
                   11420: 
                   11421: =over 4
                   11422: 
                   11423: These routines allow one to make log messages in the lonnet.log and
                   11424: lonnet.perm logfiles.
1.191     harris41 11425: 
                   11426: =item *
                   11427: 
1.243     albertel 11428: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11429: 
                   11430: =item *
                   11431: 
1.243     albertel 11432: logthis() : append message to the normal lonnet.log file, it gets
                   11433: preiodically rolled over and deleted.
1.191     harris41 11434: 
                   11435: =item *
                   11436: 
1.243     albertel 11437: logperm() : append a permanent message to lonnet.perm.log, this log
                   11438: file never gets deleted by any automated portion of the system, only
                   11439: messages of critical importance should go in here.
                   11440: 
                   11441: =back
                   11442: 
                   11443: =head2 General File Helper Routines
                   11444: 
                   11445: =over 4
1.191     harris41 11446: 
                   11447: =item *
                   11448: 
1.481     raeburn  11449: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11450: (a) files in /uploaded
                   11451:   (i) If a local copy of the file exists - 
                   11452:       compares modification date of local copy with last-modified date for 
                   11453:       definitive version stored on home server for course. If local copy is 
                   11454:       stale, requests a new version from the home server and stores it. 
                   11455:       If the original has been removed from the home server, then local copy 
                   11456:       is unlinked.
                   11457:   (ii) If local copy does not exist -
                   11458:       requests the file from the home server and stores it. 
                   11459:   
                   11460:   If $caller is 'uploadrep':  
                   11461:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11462:     for request for files originally uploaded via DOCS. 
                   11463:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11464:   
                   11465:   Otherwise:
                   11466:      This indicates a call from the content generation phase of the request.
                   11467:      -  returns the entire contents of the file or -1.
                   11468:      
                   11469: (b) files in /res
                   11470:    - returns the entire contents of a file or -1; 
                   11471:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11472: 
1.712     albertel 11473: 
                   11474: =item *
                   11475: 
                   11476: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11477:                   reference
                   11478: 
                   11479: returns either a stat() list of data about the file or an empty list
                   11480: if the file doesn't exist or couldn't find out about it (connection
                   11481: problems or user unknown)
                   11482: 
1.191     harris41 11483: =item *
                   11484: 
1.243     albertel 11485: filelocation($dir,$file) : returns file system location of a file
                   11486: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11487: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11488: and a file of ../bob will become /a/bob)
1.191     harris41 11489: 
                   11490: =item *
                   11491: 
                   11492: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11493: filelocation except for hrefs
                   11494: 
                   11495: =item *
                   11496: 
                   11497: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11498: 
1.243     albertel 11499: =back
                   11500: 
1.608     albertel 11501: =head2 Usererfile file routines (/uploaded*)
                   11502: 
                   11503: =over 4
                   11504: 
                   11505: =item *
                   11506: 
                   11507: userfileupload(): main rotine for putting a file in a user or course's
                   11508:                   filespace, arguments are,
                   11509: 
1.620     albertel 11510:  formname - required - this is the name of the element in $env where the
1.608     albertel 11511:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11512:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11513:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11514:  context - if coursedoc, store the file in the course of the active role
                   11515:              of the current user; 
                   11516:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11517:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11518:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11519:          if undefined, it will be placed in "unknown"
                   11520: 
                   11521:  (This routine calls clean_filename() to remove any dangerous
                   11522:  characters from the filename, and then calls finuserfileupload() to
                   11523:  complete the transaction)
                   11524: 
                   11525:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11526:  and /adm/notfound.html if unsuccessful
                   11527: 
                   11528: =item *
                   11529: 
                   11530: clean_filename(): routine for cleaing a filename up for storage in
                   11531:                  userfile space, argument is:
                   11532: 
                   11533:  filename - proposed filename
                   11534: 
                   11535: returns: the new clean filename
                   11536: 
                   11537: =item *
                   11538: 
1.1090    raeburn  11539: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11540: userspace, probably shouldn't be called directly
                   11541: 
                   11542:   docuname: username or courseid of destination for the file
                   11543:   docudom: domain of user/course of destination for the file
                   11544:   formname: same as for userfileupload()
1.1090    raeburn  11545:   fname: filename (including subdirectories) for the file
                   11546:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11547:   allfiles: reference to hash used to store objects found by parser
                   11548:   codebase: reference to hash used for codebases of java objects found by parser
                   11549:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11550:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11551:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11552:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11553:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11554:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11555:   mimetype: reference to scalar to accommodate mime type determined
                   11556:             from File::MMagic if $parser = parse.
1.608     albertel 11557: 
                   11558:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11559:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11560:  was 'overwrite').
                   11561:  
1.608     albertel 11562: 
                   11563: =item *
                   11564: 
                   11565: renameuserfile(): renames an existing userfile to a new name
                   11566: 
                   11567:   Args:
                   11568:    docuname: username or courseid of destination for the file
                   11569:    docudom: domain of user/course of destination for the file
                   11570:    old: current file name (including any subdirs under userfiles)
                   11571:    new: desired file name (including any subdirs under userfiles)
                   11572: 
                   11573: =item *
                   11574: 
                   11575: mkdiruserfile(): creates a directory is a userfiles dir
                   11576: 
                   11577:   Args:
                   11578:    docuname: username or courseid of destination for the file
                   11579:    docudom: domain of user/course of destination for the file
                   11580:    dir: dir to create (including any subdirs under userfiles)
                   11581: 
                   11582: =item *
                   11583: 
                   11584: removeuserfile(): removes a file that exists in userfiles
                   11585: 
                   11586:   Args:
                   11587:    docuname: username or courseid of destination for the file
                   11588:    docudom: domain of user/course of destination for the file
                   11589:    fname: filname to delete (including any subdirs under userfiles)
                   11590: 
                   11591: =item *
                   11592: 
                   11593: removeuploadedurl(): convience function for removeuserfile()
                   11594: 
                   11595:   Args:
                   11596:    url:  a full /uploaded/... url to delete
                   11597: 
1.747     albertel 11598: =item * 
                   11599: 
                   11600: get_portfile_permissions():
                   11601:   Args:
                   11602:     domain: domain of user or course contain the portfolio files
                   11603:     user: name of user or num of course contain the portfolio files
                   11604:   Returns:
                   11605:     hashref of a dump of the proper file_permissions.db
                   11606:    
                   11607: 
                   11608: =item * 
                   11609: 
                   11610: get_access_controls():
                   11611: 
                   11612: Args:
                   11613:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11614:   group: (optional) the group you want the files associated with
                   11615:   file: (optional) the file you want access info on
                   11616: 
                   11617: Returns:
1.749     raeburn  11618:     a hash (keys are file names) of hashes containing
                   11619:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11620:         values are XML containing access control settings (see below) 
1.747     albertel 11621: 
                   11622: Internal notes:
                   11623: 
1.749     raeburn  11624:  access controls are stored in file_permissions.db as key=value pairs.
                   11625:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11626:         where scope -> public,guest,course,group,domains or users.
                   11627:               end -> UNIX time for end of access (0 -> no end date)
                   11628:               start -> UNIX time for start of access
                   11629: 
                   11630:     value -> XML description of access control
                   11631:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11632:             <start></start>
                   11633:             <end></end>
                   11634: 
                   11635:             <password></password>  for scope type = guest
                   11636: 
                   11637:             <domain></domain>     for scope type = course or group
                   11638:             <number></number>
                   11639:             <roles id="">
                   11640:              <role></role>
                   11641:              <access></access>
                   11642:              <section></section>
                   11643:              <group></group>
                   11644:             </roles>
                   11645: 
                   11646:             <dom></dom>         for scope type = domains
                   11647: 
                   11648:             <users>             for scope type = users
                   11649:              <user>
                   11650:               <uname></uname>
                   11651:               <udom></udom>
                   11652:              </user>
                   11653:             </users>
                   11654:            </scope> 
                   11655:               
                   11656:  Access data is also aggregated for each file in an additional key=value pair:
                   11657:  key -> path to file/file_name\0accesscontrol 
                   11658:  value -> reference to hash
                   11659:           hash contains key = value pairs
                   11660:           where key = uniqueID:scope_end_start
                   11661:                 value = UNIX time record was last updated
                   11662: 
                   11663:           Used to improve speed of look-ups of access controls for each file.  
                   11664:  
                   11665:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11666: 
                   11667: modify_access_controls():
                   11668: 
                   11669: Modifies access controls for a portfolio file
                   11670: Args
                   11671: 1. file name
                   11672: 2. reference to hash of required changes,
                   11673: 3. domain
                   11674: 4. username
                   11675:   where domain,username are the domain of the portfolio owner 
                   11676:   (either a user or a course) 
                   11677: 
                   11678: Returns:
                   11679: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11680: 2. result of deletions ('ok' or 'error', with error message).
                   11681: 3. reference to hash of any new or updated access controls.
                   11682: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11683:    key = integer (inbound ID)
                   11684:    value = uniqueID  
1.747     albertel 11685: 
1.608     albertel 11686: =back
                   11687: 
1.243     albertel 11688: =head2 HTTP Helper Routines
                   11689: 
                   11690: =over 4
                   11691: 
1.191     harris41 11692: =item *
                   11693: 
                   11694: escape() : unpack non-word characters into CGI-compatible hex codes
                   11695: 
                   11696: =item *
                   11697: 
                   11698: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11699: 
1.243     albertel 11700: =back
                   11701: 
                   11702: =head1 PRIVATE SUBROUTINES
                   11703: 
                   11704: =head2 Underlying communication routines (Shouldn't call)
                   11705: 
                   11706: =over 4
                   11707: 
                   11708: =item *
                   11709: 
                   11710: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11711: 
                   11712: =item *
                   11713: 
                   11714: reply() : uses subreply to send a message to remote machine, logs all failures
                   11715: 
                   11716: =item *
                   11717: 
                   11718: critical() : passes a critical message to another server; if cannot
                   11719: get through then place message in connection buffer directory and
                   11720: returns con_delayed, if incapable of saving message, returns
                   11721: con_failed
                   11722: 
                   11723: =item *
                   11724: 
                   11725: reconlonc() : tries to reconnect lonc client processes.
                   11726: 
                   11727: =back
                   11728: 
                   11729: =head2 Resource Access Logging
                   11730: 
                   11731: =over 4
                   11732: 
                   11733: =item *
                   11734: 
                   11735: flushcourselogs() : flush (save) buffer logs and access logs
                   11736: 
                   11737: =item *
                   11738: 
                   11739: courselog($what) : save message for course in hash
                   11740: 
                   11741: =item *
                   11742: 
                   11743: courseacclog($what) : save message for course using &courselog().  Perform
                   11744: special processing for specific resource types (problems, exams, quizzes, etc).
                   11745: 
1.191     harris41 11746: =item *
                   11747: 
                   11748: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11749: as a PerlChildExitHandler
1.243     albertel 11750: 
                   11751: =back
                   11752: 
                   11753: =head2 Other
                   11754: 
                   11755: =over 4
                   11756: 
                   11757: =item *
                   11758: 
                   11759: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11760: 
                   11761: =back
                   11762: 
                   11763: =cut
1.877     foxr     11764: 

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